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
|
---|---|---|---|---|---|---|---|
BenGorFile/FileBundle | src/BenGorFile/FileBundle/DependencyInjection/Compiler/Application/Command/UploadFileCommandBuilder.php | UploadFileCommandBuilder.register | public function register($file)
{
$this->container->setDefinition(
$this->definitionName($file),
(new Definition(
$this->handler(), [
$this->container->getDefinition(
'bengor.file.infrastructure.domain.model.' . $file . '_filesystem'
),
$this->container->getDefinition(
'bengor.file.infrastructure.persistence.' . $file . '_repository'
),
$this->container->getDefinition(
'bengor.file.infrastructure.domain.model.' . $file . '_factory'
),
]
))->addTag(
'bengor_file_' . $file . '_command_bus_handler', [
'handles' => $this->command(),
]
)
);
} | php | public function register($file)
{
$this->container->setDefinition(
$this->definitionName($file),
(new Definition(
$this->handler(), [
$this->container->getDefinition(
'bengor.file.infrastructure.domain.model.' . $file . '_filesystem'
),
$this->container->getDefinition(
'bengor.file.infrastructure.persistence.' . $file . '_repository'
),
$this->container->getDefinition(
'bengor.file.infrastructure.domain.model.' . $file . '_factory'
),
]
))->addTag(
'bengor_file_' . $file . '_command_bus_handler', [
'handles' => $this->command(),
]
)
);
} | {@inheritdoc} | https://github.com/BenGorFile/FileBundle/blob/82c1fa952e7e7b7a188141a34053ab612b699a21/src/BenGorFile/FileBundle/DependencyInjection/Compiler/Application/Command/UploadFileCommandBuilder.php#L31-L53 |
comodojo/extender.framework | src/Comodojo/Extender/Task/Table.php | Table.add | public function add($name, $class, $description = null) {
if ( array_key_exists($name, $this->data) ) {
$this->logger->warning("Skipping duplicate task $name ($class)");
return false;
}
if ( empty($name) || empty($class) || !class_exists($class) ) {
$this->logger->warning("Skipping invalid task definition", array(
"NAME" => $name,
"CLASS" => $class,
"DESCRIPTION"=> $description
));
return false;
}
$this->data[$name] = new TaskItem(
$this->getConfiguration(),
$this->getEvents(),
$this->getLogger(),
$name,
$class,
$description
);
$this->logger->debug("Task $name ($class) in table");
return true;
} | php | public function add($name, $class, $description = null) {
if ( array_key_exists($name, $this->data) ) {
$this->logger->warning("Skipping duplicate task $name ($class)");
return false;
}
if ( empty($name) || empty($class) || !class_exists($class) ) {
$this->logger->warning("Skipping invalid task definition", array(
"NAME" => $name,
"CLASS" => $class,
"DESCRIPTION"=> $description
));
return false;
}
$this->data[$name] = new TaskItem(
$this->getConfiguration(),
$this->getEvents(),
$this->getLogger(),
$name,
$class,
$description
);
$this->logger->debug("Task $name ($class) in table");
return true;
} | Add a new task to table
@param string $name
@param string $class
@param string $description
@return bool | https://github.com/comodojo/extender.framework/blob/cc9a4fbd29fe0e80965ce4535091c956aad70b27/src/Comodojo/Extender/Task/Table.php#L84-L113 |
comodojo/extender.framework | src/Comodojo/Extender/Task/Table.php | Table.delete | public function delete($name) {
if ( array_key_exists($name, $this->data) ) {
unset($this->data[$name]);
return true;
}
return false;
} | php | public function delete($name) {
if ( array_key_exists($name, $this->data) ) {
unset($this->data[$name]);
return true;
}
return false;
} | Delete a task from table
@param string $name
@return bool | https://github.com/comodojo/extender.framework/blob/cc9a4fbd29fe0e80965ce4535091c956aad70b27/src/Comodojo/Extender/Task/Table.php#L121-L130 |
comodojo/extender.framework | src/Comodojo/Extender/Task/Table.php | Table.addBulk | public function addBulk(array $tasks) {
$result = [];
foreach($tasks as $name => $task) {
if ( empty($task['class']) ) {
$this->logger->warning("Missing class for task $name");
$result[] = false;
} else {
$result[] = $this->add($name, $task['class'], empty($task['description']) ? null : $task['description']);
}
}
return $result;
} | php | public function addBulk(array $tasks) {
$result = [];
foreach($tasks as $name => $task) {
if ( empty($task['class']) ) {
$this->logger->warning("Missing class for task $name");
$result[] = false;
} else {
$result[] = $this->add($name, $task['class'], empty($task['description']) ? null : $task['description']);
}
}
return $result;
} | Load a bulk task list into the table
@param array $tasks
@return bool | https://github.com/comodojo/extender.framework/blob/cc9a4fbd29fe0e80965ce4535091c956aad70b27/src/Comodojo/Extender/Task/Table.php#L138-L159 |
makinacorpus/drupal-umenu | src/AbstractTreeProvider.php | AbstractTreeProvider.findTreeForNode | public function findTreeForNode($nodeId, array $conditions = [])
{
// Not isset() here because result can null (no tree found)
if (\array_key_exists($nodeId, $this->perNodeTree)) {
return $this->perNodeTree[$nodeId];
}
if ($menuIdList = $this->findAllMenuFor($nodeId, $conditions)) {
// Arbitrary take the first
// @todo later give more control to this for users
return $this->perNodeTree[$nodeId] = \reset($menuIdList);
}
$this->perNodeTree[$nodeId] = null;
} | php | public function findTreeForNode($nodeId, array $conditions = [])
{
// Not isset() here because result can null (no tree found)
if (\array_key_exists($nodeId, $this->perNodeTree)) {
return $this->perNodeTree[$nodeId];
}
if ($menuIdList = $this->findAllMenuFor($nodeId, $conditions)) {
// Arbitrary take the first
// @todo later give more control to this for users
return $this->perNodeTree[$nodeId] = \reset($menuIdList);
}
$this->perNodeTree[$nodeId] = null;
} | {@inheritdoc} | https://github.com/makinacorpus/drupal-umenu/blob/346574eb0f5982857c64144e99ad2eacc8c52c5b/src/AbstractTreeProvider.php#L89-L103 |
andyburton/Sonic-Framework | src/Resource/Model/Collection.php | Collection.random | public function random ()
{
$arr = $this->getArrayCopy ();
$rand = array_rand ($arr);
return isset ($arr[$rand])? $arr[$rand] : FALSE;
} | php | public function random ()
{
$arr = $this->getArrayCopy ();
$rand = array_rand ($arr);
return isset ($arr[$rand])? $arr[$rand] : FALSE;
} | Return random collection item
@return \Sonic\Model|FALSE | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/Model/Collection.php#L81-L86 |
andyburton/Sonic-Framework | src/Resource/Model/Collection.php | Collection.toArray | public function toArray ($attributes = FALSE, $relations = array (), $recursive = FALSE)
{
$arr = array ();
$it = $this->getIterator ();
while ($it->valid ())
{
$arr[$it->key ()] = $it->current ()->toArray ($attributes, $relations, $recursive);
$it->next ();
}
return $arr;
} | php | public function toArray ($attributes = FALSE, $relations = array (), $recursive = FALSE)
{
$arr = array ();
$it = $this->getIterator ();
while ($it->valid ())
{
$arr[$it->key ()] = $it->current ()->toArray ($attributes, $relations, $recursive);
$it->next ();
}
return $arr;
} | Return a multidimensional array with objects and their attributes
@param array|boolean $attributes Attributes to include, default to false i.e all attributes
@param array $relations Array of related object attributes or tranformed method attributes to return
e.g. related value - 'query_name' => array ('\Sonic\Model\User\Group', 'name')
e.g. object tranformed value - 'permission_value' => array ('$this', 'getStringValue')
e.g. static tranformed value - 'permission_value' => array ('self', '_getStringValue')
@param integer $recursive Output array recursively, so any $this->children also get output
@return object|boolean | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/Model/Collection.php#L100-L114 |
newup/core | src/Foundation/Composer/Composer.php | Composer.prepareOptions | private function prepareOptions($options, $forceOptions = [])
{
$optionString = '';
foreach ($forceOptions as $option => $value) {
if (is_numeric($option)) {
$options[$value] = null;
} else {
$options[$option] = $value;
}
}
foreach ($options as $option => $value) {
if (is_null($value)) {
$optionString .= ' ' . $option;
} else {
$optionString .= ' ' . $option . '=' . $value;
}
}
return $optionString;
} | php | private function prepareOptions($options, $forceOptions = [])
{
$optionString = '';
foreach ($forceOptions as $option => $value) {
if (is_numeric($option)) {
$options[$value] = null;
} else {
$options[$option] = $value;
}
}
foreach ($options as $option => $value) {
if (is_null($value)) {
$optionString .= ' ' . $option;
} else {
$optionString .= ' ' . $option . '=' . $value;
}
}
return $optionString;
} | Prepares the options string.
@param $options
@param $forceOptions
@return string | https://github.com/newup/core/blob/54128903e7775e67d63284d958b46862c8df71f9/src/Foundation/Composer/Composer.php#L118-L140 |
newup/core | src/Foundation/Composer/Composer.php | Composer.prepareInstallationDirectory | private function prepareInstallationDirectory($directory)
{
if (!$this->files->exists($directory)) {
$this->files->makeDirectory($directory . DIRECTORY_SEPARATOR, 0755, true);
return;
}
$this->files->deleteDirectory($directory, true);
$this->checkInstallationDirectory($directory);
} | php | private function prepareInstallationDirectory($directory)
{
if (!$this->files->exists($directory)) {
$this->files->makeDirectory($directory . DIRECTORY_SEPARATOR, 0755, true);
return;
}
$this->files->deleteDirectory($directory, true);
$this->checkInstallationDirectory($directory);
} | Prepares the installation directory.
This method will create the directory if it does
not exist and will ensure that the directory is
empty if it does.
@param $directory | https://github.com/newup/core/blob/54128903e7775e67d63284d958b46862c8df71f9/src/Foundation/Composer/Composer.php#L151-L161 |
newup/core | src/Foundation/Composer/Composer.php | Composer.checkInstallationDirectory | private function checkInstallationDirectory($directory)
{
if ($this->installationAttempts >= $this->breakAtInstallationAttempt) {
$this->log->error('Installation directory checks failed at max attempts', ['attempts' => $this->installationAttempts]);
throw new PackageInstallationException(null, "The package template could not be installed.");
}
$files = $this->files->allFiles($directory);
$directories = $this->files->directories($directory);
if (count($files) == 0 && count($directories) == 0) {
return;
}
$directoriesReadable = true;
$filesReadable = true;
foreach ($directories as $directory) {
if (!$this->files->isReadable($directory)) {
$this->log->error('Unreadable directory preventing Composer install', ['directory' => $directory]);
$directoriesReadable = false;
}
}
foreach ($files as $file) {
if (!$this->files->isReadable($file->getPathname())) {
$this->log->error('Unreadable file preventing Composer install', ['file' => $file]);
$filesReadable = false;
}
}
if (!$directoriesReadable || !$filesReadable) {
$this->log->critical('Unreadable files/directories, cannot proceed with install.');
throw new InvalidInstallationDirectoryException(null,
"The installation directory ({$directory}) is not empty and could not be cleared due to a permissions issue. Please manually remove all files from the directory and try again.");
}
if (!$this->files->isWritable($directory)) {
$this->log->critical('Installation directory is not writeable by NewUp. Cannot proceed with install.', ['directory' => $directory, 'permissions' => fileperms($directory)]);
throw new InvalidInstallationDirectoryException(null,
"The installation directory ({$directory}) is not writeable by the NewUp process.");
}
// At this point, there is no clear reason why the preparation
// did not succeed. Because of this, we will try again.
$this->installationAttempts++;
$this->log->debug('Installation attempt incremented', ['directory' => $directory, 'attempt' => $this->installationAttempts]);
$this->prepareInstallationDirectory($directory);
} | php | private function checkInstallationDirectory($directory)
{
if ($this->installationAttempts >= $this->breakAtInstallationAttempt) {
$this->log->error('Installation directory checks failed at max attempts', ['attempts' => $this->installationAttempts]);
throw new PackageInstallationException(null, "The package template could not be installed.");
}
$files = $this->files->allFiles($directory);
$directories = $this->files->directories($directory);
if (count($files) == 0 && count($directories) == 0) {
return;
}
$directoriesReadable = true;
$filesReadable = true;
foreach ($directories as $directory) {
if (!$this->files->isReadable($directory)) {
$this->log->error('Unreadable directory preventing Composer install', ['directory' => $directory]);
$directoriesReadable = false;
}
}
foreach ($files as $file) {
if (!$this->files->isReadable($file->getPathname())) {
$this->log->error('Unreadable file preventing Composer install', ['file' => $file]);
$filesReadable = false;
}
}
if (!$directoriesReadable || !$filesReadable) {
$this->log->critical('Unreadable files/directories, cannot proceed with install.');
throw new InvalidInstallationDirectoryException(null,
"The installation directory ({$directory}) is not empty and could not be cleared due to a permissions issue. Please manually remove all files from the directory and try again.");
}
if (!$this->files->isWritable($directory)) {
$this->log->critical('Installation directory is not writeable by NewUp. Cannot proceed with install.', ['directory' => $directory, 'permissions' => fileperms($directory)]);
throw new InvalidInstallationDirectoryException(null,
"The installation directory ({$directory}) is not writeable by the NewUp process.");
}
// At this point, there is no clear reason why the preparation
// did not succeed. Because of this, we will try again.
$this->installationAttempts++;
$this->log->debug('Installation attempt incremented', ['directory' => $directory, 'attempt' => $this->installationAttempts]);
$this->prepareInstallationDirectory($directory);
} | Checks the installation directory to make sure it is ready.
@throws InvalidInstallationDirectoryException
@throws PackageInstallationException
@param $directory | https://github.com/newup/core/blob/54128903e7775e67d63284d958b46862c8df71f9/src/Foundation/Composer/Composer.php#L170-L218 |
newup/core | src/Foundation/Composer/Composer.php | Composer.installPackage | public function installPackage($packageName, $options = [])
{
$process = $this->getProcess();
$processCommand = trim($this->findComposer() . ' create-project ' . $packageName . ' "' .
$this->workingPath . '" ' .
$this->prepareOptions($options, ['--no-ansi', '--no-install']));
$process->setCommandLine($processCommand);
$this->prepareInstallationDirectory($this->workingPath);
$this->log->info('Running Composer command', ['command' => $processCommand]);
$process->run();
if ($process->isSuccessful() == false) {
$composerError = $this->parseComposerErrorMessage($process->getErrorOutput());
$this->log->error('Composer create-project process failure', ['composer' => $composerError]);
$additionalInformation = '';
if (Str::contains($process->getErrorOutput(), 'The system cannot find the path specified. (code: 3)')) {
$additionalInformation = PHP_EOL.PHP_EOL.'Based on the provided error message, the following article may be helpful:'.PHP_EOL.'https://getcomposer.org/doc/articles/troubleshooting.md#-the-system-cannot-find-the-path-specified-windows-';
}
throw new PackageInstallationException($process->getErrorOutput(),
"There was an error installing the package: {$packageName}" . PHP_EOL .
'Composer is reporting the following error:' . PHP_EOL . '--> ' . $composerError.$additionalInformation);
}
return true;
} | php | public function installPackage($packageName, $options = [])
{
$process = $this->getProcess();
$processCommand = trim($this->findComposer() . ' create-project ' . $packageName . ' "' .
$this->workingPath . '" ' .
$this->prepareOptions($options, ['--no-ansi', '--no-install']));
$process->setCommandLine($processCommand);
$this->prepareInstallationDirectory($this->workingPath);
$this->log->info('Running Composer command', ['command' => $processCommand]);
$process->run();
if ($process->isSuccessful() == false) {
$composerError = $this->parseComposerErrorMessage($process->getErrorOutput());
$this->log->error('Composer create-project process failure', ['composer' => $composerError]);
$additionalInformation = '';
if (Str::contains($process->getErrorOutput(), 'The system cannot find the path specified. (code: 3)')) {
$additionalInformation = PHP_EOL.PHP_EOL.'Based on the provided error message, the following article may be helpful:'.PHP_EOL.'https://getcomposer.org/doc/articles/troubleshooting.md#-the-system-cannot-find-the-path-specified-windows-';
}
throw new PackageInstallationException($process->getErrorOutput(),
"There was an error installing the package: {$packageName}" . PHP_EOL .
'Composer is reporting the following error:' . PHP_EOL . '--> ' . $composerError.$additionalInformation);
}
return true;
} | Installs a Composer package, placing it in NewUp's template storage.
@param $packageName
@param array $options
@throws PackageInstallationException
@return bool | https://github.com/newup/core/blob/54128903e7775e67d63284d958b46862c8df71f9/src/Foundation/Composer/Composer.php#L245-L276 |
newup/core | src/Foundation/Composer/Composer.php | Composer.updatePackageDependencies | public function updatePackageDependencies($options = [])
{
$process = $this->getProcess();
$processCommand = trim($this->findComposer() . ' update ' .
$this->prepareOptions($options, ['--no-progress', '--no-ansi']));
$process->setCommandLine($processCommand);
chdir($this->workingPath);
$this->log->info('Changing working directory for Composer update', ['directory' => $this->workingPath]);
$this->log->info('Running Composer command', ['command' => $processCommand]);
$process->run();
if ($process->isSuccessful() == false) {
$this->restoreWorkingDirectory();
$composerError = $process->getErrorOutput();
$this->log->error('Composer update process failure', ['composer' => $composerError]);
throw new PackageInstallationException($process->getErrorOutput(),
"There was an error updating the dependencies." . PHP_EOL .
'Composer is reporting the following error(s):' . PHP_EOL . '--> ' . $composerError);
}
$this->restoreWorkingDirectory();
$this->log->info('Package template dependencies updated', ['directory' => $this->workingPath]);
return true;
} | php | public function updatePackageDependencies($options = [])
{
$process = $this->getProcess();
$processCommand = trim($this->findComposer() . ' update ' .
$this->prepareOptions($options, ['--no-progress', '--no-ansi']));
$process->setCommandLine($processCommand);
chdir($this->workingPath);
$this->log->info('Changing working directory for Composer update', ['directory' => $this->workingPath]);
$this->log->info('Running Composer command', ['command' => $processCommand]);
$process->run();
if ($process->isSuccessful() == false) {
$this->restoreWorkingDirectory();
$composerError = $process->getErrorOutput();
$this->log->error('Composer update process failure', ['composer' => $composerError]);
throw new PackageInstallationException($process->getErrorOutput(),
"There was an error updating the dependencies." . PHP_EOL .
'Composer is reporting the following error(s):' . PHP_EOL . '--> ' . $composerError);
}
$this->restoreWorkingDirectory();
$this->log->info('Package template dependencies updated', ['directory' => $this->workingPath]);
return true;
} | Updates the packages dependencies by running "composer update".
@throws PackageInstallationException
@param array $options
@return bool | https://github.com/newup/core/blob/54128903e7775e67d63284d958b46862c8df71f9/src/Foundation/Composer/Composer.php#L285-L313 |
newup/core | src/Foundation/Composer/Composer.php | Composer.getVersion | public function getVersion()
{
$process = $this->getProcess();
$processCommand = trim($this->findComposer() . ' --version');
$process->setCommandLine($processCommand);
$this->log->info('Running Composer command', ['command' => $processCommand]);
$process->run();
if ($process->isSuccessful() == false) {
$composerError = remove_ansi($process->getErrorOutput());
$this->log->error('Composer version process failure', ['composer' => $composerError]);
throw new ComposerException('There was an error retrieving the Composer version');
}
return $process->getOutput();
} | php | public function getVersion()
{
$process = $this->getProcess();
$processCommand = trim($this->findComposer() . ' --version');
$process->setCommandLine($processCommand);
$this->log->info('Running Composer command', ['command' => $processCommand]);
$process->run();
if ($process->isSuccessful() == false) {
$composerError = remove_ansi($process->getErrorOutput());
$this->log->error('Composer version process failure', ['composer' => $composerError]);
throw new ComposerException('There was an error retrieving the Composer version');
}
return $process->getOutput();
} | Gets the Composer version.
@return string
@throws ComposerException | https://github.com/newup/core/blob/54128903e7775e67d63284d958b46862c8df71f9/src/Foundation/Composer/Composer.php#L332-L347 |
newup/core | src/Foundation/Composer/Composer.php | Composer.selfUpdate | public function selfUpdate()
{
$beforeVersion = $this->getVersion();
$process = $this->getProcess();
$processCommand = trim($this->findComposer() . ' self-update');
$process->setCommandLine($processCommand);
$this->log->info('Running Composer command', ['command' => $processCommand]);
$process->run();
if ($process->isSuccessful() == false) {
$composerError = remove_ansi($process->getErrorOutput());
$this->log->error('Composer self update process failure', ['composer' => $composerError]);
throw new ComposerException('There was an error updating Composer');
}
$afterVersion = $this->getVersion();
if ($beforeVersion == $afterVersion) {
return false;
}
return true;
} | php | public function selfUpdate()
{
$beforeVersion = $this->getVersion();
$process = $this->getProcess();
$processCommand = trim($this->findComposer() . ' self-update');
$process->setCommandLine($processCommand);
$this->log->info('Running Composer command', ['command' => $processCommand]);
$process->run();
if ($process->isSuccessful() == false) {
$composerError = remove_ansi($process->getErrorOutput());
$this->log->error('Composer self update process failure', ['composer' => $composerError]);
throw new ComposerException('There was an error updating Composer');
}
$afterVersion = $this->getVersion();
if ($beforeVersion == $afterVersion) {
return false;
}
return true;
} | Attempts to update Composer.
Returns true if Composer was updated, false if not.
@return bool
@throws ComposerException | https://github.com/newup/core/blob/54128903e7775e67d63284d958b46862c8df71f9/src/Foundation/Composer/Composer.php#L357-L380 |
nasumilu/geometry | src/Builder/PolygonBuilder.php | PolygonBuilder.build | protected function build(GeometryFactoryInterface $geometryFactory, CoordinateSystemInterface $cs, array $argument) : ?Geometry {
$linestrings = [];
$lines = $argument['coordinates'] ?? [];
foreach ($lines as $line) {
$linestrings[] = parent::build($geometryFactory, $cs, ['coordinates' => $line]);
}
return new Polygon($geometryFactory, $cs, ...$linestrings);
} | php | protected function build(GeometryFactoryInterface $geometryFactory, CoordinateSystemInterface $cs, array $argument) : ?Geometry {
$linestrings = [];
$lines = $argument['coordinates'] ?? [];
foreach ($lines as $line) {
$linestrings[] = parent::build($geometryFactory, $cs, ['coordinates' => $line]);
}
return new Polygon($geometryFactory, $cs, ...$linestrings);
} | {@inheritDoc} | https://github.com/nasumilu/geometry/blob/000fafe3e61f1d0682952ad236b7486dded65eae/src/Builder/PolygonBuilder.php#L79-L86 |
schpill/thin | src/Database/Collection.php | Collection.add | public function add($items)
{
if ($items && $items instanceof Container) {
$id = (int) $items->id;
$this->_items[$id] = $items;
} elseif (Arrays::is($items)) {
foreach ($items as $obj) {
if ($obj instanceof Container) {
$this->add($obj);
}
}
} elseif ($items instanceof self) {
$this->add($items->toArray());
}
return $this;
} | php | public function add($items)
{
if ($items && $items instanceof Container) {
$id = (int) $items->id;
$this->_items[$id] = $items;
} elseif (Arrays::is($items)) {
foreach ($items as $obj) {
if ($obj instanceof Container) {
$this->add($obj);
}
}
} elseif ($items instanceof self) {
$this->add($items->toArray());
}
return $this;
} | Add a model item or model array or ModelSet to this set
@param mixed $items model item or arry or ModelSet to add
@return $this | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Database/Collection.php#L61-L77 |
schpill/thin | src/Database/Collection.php | Collection.get | public function get($index = 0)
{
if (is_integer($index)) {
if ($index + 1 > $this->count()) {
return null;
} else {
return Arrays::first(array_slice($this->_items, $index, 1));
}
} else {
if ($this->has($index)) {
return $this->_items[$index];
}
}
return null;
} | php | public function get($index = 0)
{
if (is_integer($index)) {
if ($index + 1 > $this->count()) {
return null;
} else {
return Arrays::first(array_slice($this->_items, $index, 1));
}
} else {
if ($this->has($index)) {
return $this->_items[$index];
}
}
return null;
} | Get item by numeric index
@param int $index model to get
@return Model | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Database/Collection.php#L86-L101 |
schpill/thin | src/Database/Collection.php | Collection.remove | public function remove($param)
{
if ($param instanceof Container) {
$param = $param->id;
}
$item = $this->get($param);
if ($item) {
$id = (int) $item->id;
if ($this->_items[$id]) {
unset($this->_items[$id]);
}
}
return $this;
} | php | public function remove($param)
{
if ($param instanceof Container) {
$param = $param->id;
}
$item = $this->get($param);
if ($item) {
$id = (int) $item->id;
if ($this->_items[$id]) {
unset($this->_items[$id]);
}
}
return $this;
} | Remove a record from the collection
@param int|Model $param model to remove
@return boolean | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Database/Collection.php#L121-L138 |
schpill/thin | src/Database/Collection.php | Collection.has | public function has($param)
{
if ($param instanceof Container) {
$id = (int) $param->id;
} elseif (is_integer($param)) {
$id = $param;
}
if (isset($id) && isset($this->_items[$id])) {
return true;
}
return false;
} | php | public function has($param)
{
if ($param instanceof Container) {
$id = (int) $param->id;
} elseif (is_integer($param)) {
$id = $param;
}
if (isset($id) && isset($this->_items[$id])) {
return true;
}
return false;
} | Determine if a record exists in the collection
@param int|object $param param
@return boolean | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Database/Collection.php#L185-L198 |
schpill/thin | src/Database/Collection.php | Collection.contains | public function contains($value)
{
if ($value instanceof \Closure) {
return ! is_null($this->first($value));
}
return Arrays::in($value, $this->_items);
} | php | public function contains($value)
{
if ($value instanceof \Closure) {
return ! is_null($this->first($value));
}
return Arrays::in($value, $this->_items);
} | Determine if an item exists in the collection.
@param mixed $value
@return bool | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Database/Collection.php#L206-L213 |
schpill/thin | src/Database/Collection.php | Collection.sortBy | public function sortBy(Closure $callback, $args = array(), $asc = false)
{
$results = array();
foreach ($this->_items as $key => $value) {
array_push($args, $value);
$results[$key] = call_user_func_array($callback, $args);
}
if (true === $asc) {
asort($results);
} else {
arsort($results);
}
foreach (array_keys($results) as $key) {
$results[$key] = $this->_items[$key];
}
$this->_items = $results;
return $this;
} | php | public function sortBy(Closure $callback, $args = array(), $asc = false)
{
$results = array();
foreach ($this->_items as $key => $value) {
array_push($args, $value);
$results[$key] = call_user_func_array($callback, $args);
}
if (true === $asc) {
asort($results);
} else {
arsort($results);
}
foreach (array_keys($results) as $key) {
$results[$key] = $this->_items[$key];
}
$this->_items = $results;
return $this;
} | Sort the collection using the given Closure
@param Closure $callback callback
@param boolean $asc asc
@return Collection | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Database/Collection.php#L249-L271 |
schpill/thin | src/Database/Collection.php | Collection.groupBy | public function groupBy($groupBy)
{
$results = array();
foreach ($this->_items as $key => $value) {
$key = is_callable($groupBy) ? $groupBy($value, $key) : dataGet($value, $groupBy);
$results[$key][] = $value;
}
return new self($results);
} | php | public function groupBy($groupBy)
{
$results = array();
foreach ($this->_items as $key => $value) {
$key = is_callable($groupBy) ? $groupBy($value, $key) : dataGet($value, $groupBy);
$results[$key][] = $value;
}
return new self($results);
} | Group an associative array by a field or Closure value.
@param callable|string $groupBy
@return Collection | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Database/Collection.php#L554-L564 |
schpill/thin | src/Database/Collection.php | Collection.keyBy | public function keyBy($keyBy)
{
$results = array();
foreach ($this->_items as $item) {
$key = dataGet($item, $keyBy);
$results[$key] = $item;
}
return new self($results);
} | php | public function keyBy($keyBy)
{
$results = array();
foreach ($this->_items as $item) {
$key = dataGet($item, $keyBy);
$results[$key] = $item;
}
return new self($results);
} | Key an associative array by a field.
@param string $keyBy
@return Collection | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Database/Collection.php#L572-L582 |
schpill/thin | src/Database/Collection.php | Collection.collapse | public function collapse()
{
$results = array();
foreach ($this->_items as $values) {
$results = array_merge($results, $values);
}
return new static($results);
} | php | public function collapse()
{
$results = array();
foreach ($this->_items as $values) {
$results = array_merge($results, $values);
}
return new static($results);
} | Collapse the collection items into a single array.
@return Collection | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Database/Collection.php#L643-L652 |
schpill/thin | src/Database/Collection.php | Collection.first | public function first($callback = null, $default = null)
{
if (is_null($callback)) {
return count($this->_items) > 0 ? Arrays::first($this->_items) : $default;
} else {
foreach ($this->_items as $key => $value) {
if (call_user_func($callback, $key, $value)) {
return $value;
}
}
return value($default);
}
} | php | public function first($callback = null, $default = null)
{
if (is_null($callback)) {
return count($this->_items) > 0 ? Arrays::first($this->_items) : $default;
} else {
foreach ($this->_items as $key => $value) {
if (call_user_func($callback, $key, $value)) {
return $value;
}
}
return value($default);
}
} | First item
@return Model | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Database/Collection.php#L670-L683 |
schpill/thin | src/Database/Collection.php | Collection.extend | public function extend($name, Closure $callback)
{
if (count($this->_items)) {
$collection = array();
foreach ($this->_items as $item) {
if ($item instanceof Container) {
$item->fn($name, $callback);
}
array_push($collection, $item);
}
return new self($collection);
}
return $this;
} | php | public function extend($name, Closure $callback)
{
if (count($this->_items)) {
$collection = array();
foreach ($this->_items as $item) {
if ($item instanceof Container) {
$item->fn($name, $callback);
}
array_push($collection, $item);
}
return new self($collection);
}
return $this;
} | extends each Container item of this collection with a Closure.
@param string $name
@param Closure $callback callback
@return Collection | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Database/Collection.php#L727-L743 |
schpill/thin | src/Database/Collection.php | Collection.toArray | public function toArray($isNumericIndex = true, $itemToArray = false)
{
$array = array();
foreach ($this->_items as $item) {
if (false === $isNumericIndex) {
if (true === $itemToArray) {
if ($item instanceof Container) {
$item = $item->assoc();
}
}
} else {
if (true === $itemToArray) {
if ($item instanceof Container) {
$item = $item->assoc();
}
}
}
$array[] = $item;
}
return $array;
} | php | public function toArray($isNumericIndex = true, $itemToArray = false)
{
$array = array();
foreach ($this->_items as $item) {
if (false === $isNumericIndex) {
if (true === $itemToArray) {
if ($item instanceof Container) {
$item = $item->assoc();
}
}
} else {
if (true === $itemToArray) {
if ($item instanceof Container) {
$item = $item->assoc();
}
}
}
$array[] = $item;
}
return $array;
} | Export all items to a Array
@param boolean $is_numeric_index is numeric index
@param boolean $itemToArray item to array
@return array | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Database/Collection.php#L774-L796 |
schpill/thin | src/Database/Collection.php | Collection.toJson | public function toJson($render = false)
{
$json = json_encode($this->toArray(true, true));
if (false === $render) {
return $json;
} else {
header('content-type: application/json; charset=utf-8');
die($json);
}
} | php | public function toJson($render = false)
{
$json = json_encode($this->toArray(true, true));
if (false === $render) {
return $json;
} else {
header('content-type: application/json; charset=utf-8');
die($json);
}
} | Export all items to a json string
@param boolean $is_numeric_index is numeric index
@param boolean $itemToArray item to array
@return string | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Database/Collection.php#L807-L817 |
schpill/thin | src/Database/Collection.php | Collection.save | public function save()
{
if (count($this->_items)) {
foreach($this->_items as $item) {
if(true === $item->exists()) {
$item->save();
}
}
}
return $this;
} | php | public function save()
{
if (count($this->_items)) {
foreach($this->_items as $item) {
if(true === $item->exists()) {
$item->save();
}
}
}
return $this;
} | Save items
@return Collection | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Database/Collection.php#L905-L916 |
phramework/phramework | src/Models/Response.php | Response.cacheHeaders | public static function cacheHeaders($expires = '+1 hour')
{
if (!headers_sent()) {
header('Cache-Control: private, max-age=3600');
header('Pragma: public');
header('Last-Modified: ' . date(DATE_RFC822, strtotime('-1 second')));
header('Expires: ' . date(DATE_RFC822, strtotime($expires)));
}
} | php | public static function cacheHeaders($expires = '+1 hour')
{
if (!headers_sent()) {
header('Cache-Control: private, max-age=3600');
header('Pragma: public');
header('Last-Modified: ' . date(DATE_RFC822, strtotime('-1 second')));
header('Expires: ' . date(DATE_RFC822, strtotime($expires)));
}
} | Write cache headers | https://github.com/phramework/phramework/blob/40041d1ef23b1f8cdbd26fb112448d6a3dbef012/src/Models/Response.php#L96-L104 |
plinker-rpc/system | src/System.php | System.enumerate | public function enumerate($methods = [], $params = [])
{
if (is_array($methods)) {
$return = [];
foreach ($methods as $key => $value) {
if (is_array($value)) {
$return[$key] = $this->$key(...$value);
} else {
$return[$value] = $this->$value();
}
}
return $return;
} elseif (is_string($methods)) {
return $this->$methods(...$params);
}
} | php | public function enumerate($methods = [], $params = [])
{
if (is_array($methods)) {
$return = [];
foreach ($methods as $key => $value) {
if (is_array($value)) {
$return[$key] = $this->$key(...$value);
} else {
$return[$value] = $this->$value();
}
}
return $return;
} elseif (is_string($methods)) {
return $this->$methods(...$params);
}
} | Enumerate multiple methods, saves on HTTP calls
@param array $methods | https://github.com/plinker-rpc/system/blob/b0b83aad136a91c094eaac8c463df7c916d1c76e/src/System.php#L47-L62 |
plinker-rpc/system | src/System.php | System.system_updates | public function system_updates()
{
if (file_exists($this->tmp_path.'/check-updates')) {
unlink($this->tmp_path.'/check-updates');
}
if ($this->host_os === 'WINDOWS') {
$updSess = new \COM("Microsoft.Update.Session");
$updSrc = $updSess->CreateUpdateSearcher();
$result = $updSrc->Search('IsInstalled=0 and Type=\'Software\' and IsHidden=0');
return !empty($result->Updates->Count) ? '1' : '0';
}
if ($this->distro() === 'UBUNTU') {
$get_updates = shell_exec('apt-get -s dist-upgrade');
if (preg_match('/^(\d+).+upgrade.+(\d+).+newly\sinstall/m', $get_updates, $matches)) {
$result = (int) $matches[1] + (int) $matches[2];
} else {
$result = 0;
}
return !empty($result) ? '1' : '0';
}
if ($this->distro() === 'CENTOS') {
exec('yum check-update', $output, $exitCode);
return ($exitCode == 100) ? '1' : '0';
}
return '-1';
} | php | public function system_updates()
{
if (file_exists($this->tmp_path.'/check-updates')) {
unlink($this->tmp_path.'/check-updates');
}
if ($this->host_os === 'WINDOWS') {
$updSess = new \COM("Microsoft.Update.Session");
$updSrc = $updSess->CreateUpdateSearcher();
$result = $updSrc->Search('IsInstalled=0 and Type=\'Software\' and IsHidden=0');
return !empty($result->Updates->Count) ? '1' : '0';
}
if ($this->distro() === 'UBUNTU') {
$get_updates = shell_exec('apt-get -s dist-upgrade');
if (preg_match('/^(\d+).+upgrade.+(\d+).+newly\sinstall/m', $get_updates, $matches)) {
$result = (int) $matches[1] + (int) $matches[2];
} else {
$result = 0;
}
return !empty($result) ? '1' : '0';
}
if ($this->distro() === 'CENTOS') {
exec('yum check-update', $output, $exitCode);
return ($exitCode == 100) ? '1' : '0';
}
return '-1';
} | Check system for updates
@return int 1=has updates, 0=no updates, -1=unknown | https://github.com/plinker-rpc/system/blob/b0b83aad136a91c094eaac8c463df7c916d1c76e/src/System.php#L69-L97 |
plinker-rpc/system | src/System.php | System.disk_space | public function disk_space($path = '/')
{
if ($this->host_os === 'WINDOWS') {
$wmi = new \COM("winmgmts:\\\\.\\root\\cimv2");
$disks = $wmi->ExecQuery("Select * from Win32_LogicalDisk");
foreach ($disks as $d) {
if ($d->Name == $path) {
$ds = $d->Size;
$df = $d->FreeSpace;
}
}
} else {
$ds = disk_total_space($path);
$df = disk_free_space($path);
}
return ($df > 0 && $ds > 0 && $df < $ds) ? floor($df/$ds * 100) : 0;
} | php | public function disk_space($path = '/')
{
if ($this->host_os === 'WINDOWS') {
$wmi = new \COM("winmgmts:\\\\.\\root\\cimv2");
$disks = $wmi->ExecQuery("Select * from Win32_LogicalDisk");
foreach ($disks as $d) {
if ($d->Name == $path) {
$ds = $d->Size;
$df = $d->FreeSpace;
}
}
} else {
$ds = disk_total_space($path);
$df = disk_free_space($path);
}
return ($df > 0 && $ds > 0 && $df < $ds) ? floor($df/$ds * 100) : 0;
} | Get diskspace
@param string $path
@return int | https://github.com/plinker-rpc/system/blob/b0b83aad136a91c094eaac8c463df7c916d1c76e/src/System.php#L105-L122 |
plinker-rpc/system | src/System.php | System.total_disk_space | public function total_disk_space($path = '/')
{
$ds = 0;
if ($this->host_os === 'WINDOWS') {
$wmi = new \COM("winmgmts:\\\\.\\root\\cimv2");
$disks = $wmi->ExecQuery("Select * from Win32_LogicalDisk");
foreach ($disks as $d) {
if ($d->Name == $path) {
$ds = $d->Size;
}
}
} else {
$ds = disk_total_space($path);
}
return $ds;
} | php | public function total_disk_space($path = '/')
{
$ds = 0;
if ($this->host_os === 'WINDOWS') {
$wmi = new \COM("winmgmts:\\\\.\\root\\cimv2");
$disks = $wmi->ExecQuery("Select * from Win32_LogicalDisk");
foreach ($disks as $d) {
if ($d->Name == $path) {
$ds = $d->Size;
}
}
} else {
$ds = disk_total_space($path);
}
return $ds;
} | Get total diskspace
@param string $path
@return int | https://github.com/plinker-rpc/system/blob/b0b83aad136a91c094eaac8c463df7c916d1c76e/src/System.php#L130-L146 |
plinker-rpc/system | src/System.php | System.memory_stats | public function memory_stats()
{
if ($this->host_os === 'WINDOWS') {
$wmi = new \COM("winmgmts:\\\\.\\root\\cimv2");
$os = $wmi->ExecQuery("SELECT * FROM Win32_OperatingSystem");
foreach ($os as $m) {
$mem_total = $m->TotalVisibleMemorySize;
$mem_free = $m->FreePhysicalMemory;
}
$prefMemory = $wmi->ExecQuery("SELECT * FROM Win32_PerfFormattedData_PerfOS_Memory");
foreach ($prefMemory as $pm) {
$mem_cache = $pm->CacheBytes/1024;
}
$mem_buff = 0;
} else {
$fh = fopen('/proc/meminfo', 'r');
$mem_free = $mem_buff = $mem_cache = $mem_total = 0;
while ($line = fgets($fh)) {
$pieces = array();
if (preg_match('/^MemTotal:\s+(\d+)\skB$/', $line, $pieces)) {
$mem_total = $pieces[1];
}
if (preg_match('/^MemFree:\s+(\d+)\skB$/', $line, $pieces)) {
$mem_free = $pieces[1];
}
if (preg_match('/^Buffers:\s+(\d+)\skB$/', $line, $pieces)) {
$mem_buff = $pieces[1];
}
if (preg_match('/^Cached:\s+(\d+)\skB$/', $line, $pieces)) {
$mem_cache = $pieces[1];
break;
}
}
fclose($fh);
}
$result['used'] = round(($mem_total - ($mem_buff + $mem_cache + $mem_free)) * 100 / $mem_total);
$result['cache'] = round(($mem_cache + $mem_buff) * 100 / $mem_total);
$result['free'] = round($mem_free * 100 / $mem_total);
return $result;
} | php | public function memory_stats()
{
if ($this->host_os === 'WINDOWS') {
$wmi = new \COM("winmgmts:\\\\.\\root\\cimv2");
$os = $wmi->ExecQuery("SELECT * FROM Win32_OperatingSystem");
foreach ($os as $m) {
$mem_total = $m->TotalVisibleMemorySize;
$mem_free = $m->FreePhysicalMemory;
}
$prefMemory = $wmi->ExecQuery("SELECT * FROM Win32_PerfFormattedData_PerfOS_Memory");
foreach ($prefMemory as $pm) {
$mem_cache = $pm->CacheBytes/1024;
}
$mem_buff = 0;
} else {
$fh = fopen('/proc/meminfo', 'r');
$mem_free = $mem_buff = $mem_cache = $mem_total = 0;
while ($line = fgets($fh)) {
$pieces = array();
if (preg_match('/^MemTotal:\s+(\d+)\skB$/', $line, $pieces)) {
$mem_total = $pieces[1];
}
if (preg_match('/^MemFree:\s+(\d+)\skB$/', $line, $pieces)) {
$mem_free = $pieces[1];
}
if (preg_match('/^Buffers:\s+(\d+)\skB$/', $line, $pieces)) {
$mem_buff = $pieces[1];
}
if (preg_match('/^Cached:\s+(\d+)\skB$/', $line, $pieces)) {
$mem_cache = $pieces[1];
break;
}
}
fclose($fh);
}
$result['used'] = round(($mem_total - ($mem_buff + $mem_cache + $mem_free)) * 100 / $mem_total);
$result['cache'] = round(($mem_cache + $mem_buff) * 100 / $mem_total);
$result['free'] = round($mem_free * 100 / $mem_total);
return $result;
} | Get memory usage
@return array | https://github.com/plinker-rpc/system/blob/b0b83aad136a91c094eaac8c463df7c916d1c76e/src/System.php#L153-L198 |
plinker-rpc/system | src/System.php | System.memory_total | public function memory_total()
{
$mem_total = 0;
if ($this->host_os === 'WINDOWS') {
$wmi = new \COM("winmgmts:\\\\.\\root\\cimv2");
$os = $wmi->ExecQuery("SELECT * FROM Win32_OperatingSystem");
foreach ($os as $m) {
$mem_total = $m->TotalVisibleMemorySize;
}
} else {
$fh = fopen('/proc/meminfo', 'r');
while ($line = fgets($fh)) {
$pieces = array();
if (preg_match('/^MemTotal:\s+(\d+)\skB$/', trim($line), $pieces)) {
$mem_total = $pieces[1];
break;
}
}
fclose($fh);
}
return $mem_total;
} | php | public function memory_total()
{
$mem_total = 0;
if ($this->host_os === 'WINDOWS') {
$wmi = new \COM("winmgmts:\\\\.\\root\\cimv2");
$os = $wmi->ExecQuery("SELECT * FROM Win32_OperatingSystem");
foreach ($os as $m) {
$mem_total = $m->TotalVisibleMemorySize;
}
} else {
$fh = fopen('/proc/meminfo', 'r');
while ($line = fgets($fh)) {
$pieces = array();
if (preg_match('/^MemTotal:\s+(\d+)\skB$/', trim($line), $pieces)) {
$mem_total = $pieces[1];
break;
}
}
fclose($fh);
}
return $mem_total;
} | Get memory total kB
@return int | https://github.com/plinker-rpc/system/blob/b0b83aad136a91c094eaac8c463df7c916d1c76e/src/System.php#L205-L228 |
plinker-rpc/system | src/System.php | System.cpu_usage | public function cpu_usage()
{
if ($this->host_os === 'WINDOWS') {
$wmi = new \COM("winmgmts:\\\\.\\root\\cimv2");
$cpus = $wmi->ExecQuery("SELECT LoadPercentage FROM Win32_Processor");
foreach ($cpus as $cpu) {
$return = $cpu->LoadPercentage;
}
} else {
$return = shell_exec('top -d 0.5 -b -n2 | grep "Cpu(s)"|tail -n 1 | awk \'{print $2 + $4}\'');
}
return trim($return);
} | php | public function cpu_usage()
{
if ($this->host_os === 'WINDOWS') {
$wmi = new \COM("winmgmts:\\\\.\\root\\cimv2");
$cpus = $wmi->ExecQuery("SELECT LoadPercentage FROM Win32_Processor");
foreach ($cpus as $cpu) {
$return = $cpu->LoadPercentage;
}
} else {
$return = shell_exec('top -d 0.5 -b -n2 | grep "Cpu(s)"|tail -n 1 | awk \'{print $2 + $4}\'');
}
return trim($return);
} | Get CPU usage in percentage
@return int | https://github.com/plinker-rpc/system/blob/b0b83aad136a91c094eaac8c463df7c916d1c76e/src/System.php#L235-L248 |
plinker-rpc/system | src/System.php | System.machine_id | public function machine_id()
{
// check stmp path
if (!file_exists($this->tmp_path.'/system')) {
mkdir($this->tmp_path.'/system', 0755, true);
}
// file already generated
if (file_exists($this->tmp_path.'/system/machine-id')) {
return file_get_contents($this->tmp_path.'/system/machine-id');
}
if (file_exists('/var/lib/dbus/machine-id')) {
$id = trim(`cat /var/lib/dbus/machine-id`);
file_put_contents($this->tmp_path.'/system/machine-id', $id);
return $id;
}
if (file_exists('/etc/machine-id')) {
$id = trim(`cat /etc/machine-id`);
file_put_contents($this->tmp_path.'/system/machine-id', $id);
return $id;
}
$id = sha1(uniqid(true));
file_put_contents($this->tmp_path.'/system/machine-id', $id);
return $id;
} | php | public function machine_id()
{
// check stmp path
if (!file_exists($this->tmp_path.'/system')) {
mkdir($this->tmp_path.'/system', 0755, true);
}
// file already generated
if (file_exists($this->tmp_path.'/system/machine-id')) {
return file_get_contents($this->tmp_path.'/system/machine-id');
}
if (file_exists('/var/lib/dbus/machine-id')) {
$id = trim(`cat /var/lib/dbus/machine-id`);
file_put_contents($this->tmp_path.'/system/machine-id', $id);
return $id;
}
if (file_exists('/etc/machine-id')) {
$id = trim(`cat /etc/machine-id`);
file_put_contents($this->tmp_path.'/system/machine-id', $id);
return $id;
}
$id = sha1(uniqid(true));
file_put_contents($this->tmp_path.'/system/machine-id', $id);
return $id;
} | Get system machine-id
- Generates one if does not have one (windows).
@return string | https://github.com/plinker-rpc/system/blob/b0b83aad136a91c094eaac8c463df7c916d1c76e/src/System.php#L256-L283 |
plinker-rpc/system | src/System.php | System.netstat | public function netstat($parse = true)
{
$result = trim(shell_exec('netstat -pant'));
if ($parse) {
$lines = explode(PHP_EOL, $result);
unset($lines[0]);
unset($lines[1]);
$columns = [
'Proto',
'Recv-Q',
'Send-Q',
'Local Address',
'Foreign Address',
'State',
'PID/Program',
'Process Name',
];
$result = [];
foreach ($lines as $row => $line) {
$column = array_values(array_filter(explode(' ', $line), 'strlen'));
foreach ($columns as $col => $key) {
$result[$row][$key] = @$column[$col];
}
}
$result = array_values($result);
}
return $result;
} | php | public function netstat($parse = true)
{
$result = trim(shell_exec('netstat -pant'));
if ($parse) {
$lines = explode(PHP_EOL, $result);
unset($lines[0]);
unset($lines[1]);
$columns = [
'Proto',
'Recv-Q',
'Send-Q',
'Local Address',
'Foreign Address',
'State',
'PID/Program',
'Process Name',
];
$result = [];
foreach ($lines as $row => $line) {
$column = array_values(array_filter(explode(' ', $line), 'strlen'));
foreach ($columns as $col => $key) {
$result[$row][$key] = @$column[$col];
}
}
$result = array_values($result);
}
return $result;
} | Get netstat output
@return string | https://github.com/plinker-rpc/system/blob/b0b83aad136a91c094eaac8c463df7c916d1c76e/src/System.php#L290-L321 |
plinker-rpc/system | src/System.php | System.arch | public function arch()
{
if ($this->host_os === 'WINDOWS') {
$wmi = new \COM("winmgmts:\\\\.\\root\\cimv2");
$cpu= $wmi->ExecQuery("Select * from Win32_Processor");
foreach ($cpu as $c) {
$arch = '32-bit';
$cpu_arch = $c->AddressWidth;
if ($cpu_arch != 32) {
$os = $wmi->ExecQuery("Select * from Win32_OperatingSystem");
foreach ($os as $o) {
if ($o->Version >= 6.0) {
$arch = objItem.OSArchitecture;
}
}
}
}
} else {
$arch = shell_exec('arch');
}
return trim($arch);
} | php | public function arch()
{
if ($this->host_os === 'WINDOWS') {
$wmi = new \COM("winmgmts:\\\\.\\root\\cimv2");
$cpu= $wmi->ExecQuery("Select * from Win32_Processor");
foreach ($cpu as $c) {
$arch = '32-bit';
$cpu_arch = $c->AddressWidth;
if ($cpu_arch != 32) {
$os = $wmi->ExecQuery("Select * from Win32_OperatingSystem");
foreach ($os as $o) {
if ($o->Version >= 6.0) {
$arch = objItem.OSArchitecture;
}
}
}
}
} else {
$arch = shell_exec('arch');
}
return trim($arch);
} | Get system architecture
@return string | https://github.com/plinker-rpc/system/blob/b0b83aad136a91c094eaac8c463df7c916d1c76e/src/System.php#L328-L352 |
plinker-rpc/system | src/System.php | System.hostname | public function hostname()
{
if ($this->host_os === 'WINDOWS') {
$wmi = new \COM("winmgmts:\\\\.\\root\\cimv2");
$computer = $wmi->ExecQuery("SELECT * FROM Win32_ComputerSystem");
foreach ($computer as $c) {
$hostname = $c->Name;
}
} else {
$hostname = shell_exec('hostname');
}
return trim($hostname);
} | php | public function hostname()
{
if ($this->host_os === 'WINDOWS') {
$wmi = new \COM("winmgmts:\\\\.\\root\\cimv2");
$computer = $wmi->ExecQuery("SELECT * FROM Win32_ComputerSystem");
foreach ($computer as $c) {
$hostname = $c->Name;
}
} else {
$hostname = shell_exec('hostname');
}
return trim($hostname);
} | Get system hostname
@return string | https://github.com/plinker-rpc/system/blob/b0b83aad136a91c094eaac8c463df7c916d1c76e/src/System.php#L359-L372 |
plinker-rpc/system | src/System.php | System.logins | public function logins($parse = true)
{
$result = trim(shell_exec('last'));
if ($parse) {
$lines = explode(PHP_EOL, $result);
// detect end by empty line space
$end = 0;
foreach ($lines as $no => $line) {
if (trim($line) == '') {
$end = $no;
break;
}
}
// filter out end lines
foreach (range($end, count($lines)) as $key) {
unset($lines[$key]);
}
// define columns
$columns = [
'User',
'Terminal',
'Display',
'Day',
'Month',
'Day Date',
'Day Time',
'-',
'Disconnected',
'Duration',
];
// generic match rows for columns and set into return
$result = [];
foreach ($lines as $row => $line) {
$column = array_values(array_filter(explode(' ', $line), 'strlen'));
foreach ($columns as $col => $key) {
$result[$row][$key] = @$column[$col];
}
}
// fix
$fix = [];
foreach ($result as $key => $row) {
if ($row['User'] == 'reboot') {
$fix[] = [
'User' => 'Reboot',
'Terminal' => '',
'Date' => '',
'Disconnected' => '',
'Duration' => '',
];
} else {
if ($row['Duration'] == 'no') {
$row['Duration'] = '';
}
if ($row['Disconnected'] == '-') {
$row['Disconnected'] = '';
}
$fix[] = [
'User' => $row['User'],
'Terminal' => $row['Terminal'],
'Display' => $row['Display'],
'Date' => $row['Day'].' '.$row['Month'].' '.$row['Day Date'].' '.$row['Day Time'],
'Disconnected' => $row['Disconnected'],
'Duration' => trim($row['Duration'], '()'),
];
}
}
$result = $fix;
}
return $result;
} | php | public function logins($parse = true)
{
$result = trim(shell_exec('last'));
if ($parse) {
$lines = explode(PHP_EOL, $result);
// detect end by empty line space
$end = 0;
foreach ($lines as $no => $line) {
if (trim($line) == '') {
$end = $no;
break;
}
}
// filter out end lines
foreach (range($end, count($lines)) as $key) {
unset($lines[$key]);
}
// define columns
$columns = [
'User',
'Terminal',
'Display',
'Day',
'Month',
'Day Date',
'Day Time',
'-',
'Disconnected',
'Duration',
];
// generic match rows for columns and set into return
$result = [];
foreach ($lines as $row => $line) {
$column = array_values(array_filter(explode(' ', $line), 'strlen'));
foreach ($columns as $col => $key) {
$result[$row][$key] = @$column[$col];
}
}
// fix
$fix = [];
foreach ($result as $key => $row) {
if ($row['User'] == 'reboot') {
$fix[] = [
'User' => 'Reboot',
'Terminal' => '',
'Date' => '',
'Disconnected' => '',
'Duration' => '',
];
} else {
if ($row['Duration'] == 'no') {
$row['Duration'] = '';
}
if ($row['Disconnected'] == '-') {
$row['Disconnected'] = '';
}
$fix[] = [
'User' => $row['User'],
'Terminal' => $row['Terminal'],
'Display' => $row['Display'],
'Date' => $row['Day'].' '.$row['Month'].' '.$row['Day Date'].' '.$row['Day Time'],
'Disconnected' => $row['Disconnected'],
'Duration' => trim($row['Duration'], '()'),
];
}
}
$result = $fix;
}
return $result;
} | Get system last logins
@return string | https://github.com/plinker-rpc/system/blob/b0b83aad136a91c094eaac8c463df7c916d1c76e/src/System.php#L379-L455 |
plinker-rpc/system | src/System.php | System.top | public function top($parse = true)
{
if (!file_exists($this->tmp_path.'/system')) {
mkdir($this->tmp_path.'/system', 0755, true);
}
shell_exec('top -n 1 -b > '.$this->tmp_path.'/system/top-output');
usleep(25000);
$result = trim(file_get_contents($this->tmp_path.'/system/top-output'));
if ($parse) {
$lines = explode(PHP_EOL, $result);
// detect start by empty line space
$start = 0;
foreach ($lines as $no => $line) {
if (trim($line) == '') {
$start = $no;
break;
}
}
// filter out header lines
foreach (range(0, $start) as $key) {
unset($lines[$key]);
}
//remove column line
unset($lines[$start+1]);
// define columns
$columns = [
'PID',
'USER',
'PR',
'NI',
'VIRT',
'RES',
'SHR',
'S',
'%CPU',
'%MEM',
'TIME+',
'COMMAND'
];
// match rows for columns and set into return
$result = [];
foreach ($lines as $row => $line) {
$column = array_values(array_filter(explode(' ', $line), 'strlen'));
foreach ($columns as $col => $key) {
$result[$row][$key] = @$column[$col];
}
}
$result = array_values($result);
}
return $result;
} | php | public function top($parse = true)
{
if (!file_exists($this->tmp_path.'/system')) {
mkdir($this->tmp_path.'/system', 0755, true);
}
shell_exec('top -n 1 -b > '.$this->tmp_path.'/system/top-output');
usleep(25000);
$result = trim(file_get_contents($this->tmp_path.'/system/top-output'));
if ($parse) {
$lines = explode(PHP_EOL, $result);
// detect start by empty line space
$start = 0;
foreach ($lines as $no => $line) {
if (trim($line) == '') {
$start = $no;
break;
}
}
// filter out header lines
foreach (range(0, $start) as $key) {
unset($lines[$key]);
}
//remove column line
unset($lines[$start+1]);
// define columns
$columns = [
'PID',
'USER',
'PR',
'NI',
'VIRT',
'RES',
'SHR',
'S',
'%CPU',
'%MEM',
'TIME+',
'COMMAND'
];
// match rows for columns and set into return
$result = [];
foreach ($lines as $row => $line) {
$column = array_values(array_filter(explode(' ', $line), 'strlen'));
foreach ($columns as $col => $key) {
$result[$row][$key] = @$column[$col];
}
}
$result = array_values($result);
}
return $result;
} | Get system top output
@param string | https://github.com/plinker-rpc/system/blob/b0b83aad136a91c094eaac8c463df7c916d1c76e/src/System.php#L472-L527 |
plinker-rpc/system | src/System.php | System.uname | public function uname()
{
if ($this->host_os === 'WINDOWS') {
$wmi = new \COM("winmgmts:\\\\.\\root\\cimv2");
$os= $wmi->ExecQuery("Select * from Win32_OperatingSystem");
foreach ($os as $o) {
$osname = explode('|', $o->Name);
$uname = $osname[0].' '.$o->Version;
}
} else {
$uname = shell_exec('uname -rs');
}
return trim($uname);
} | php | public function uname()
{
if ($this->host_os === 'WINDOWS') {
$wmi = new \COM("winmgmts:\\\\.\\root\\cimv2");
$os= $wmi->ExecQuery("Select * from Win32_OperatingSystem");
foreach ($os as $o) {
$osname = explode('|', $o->Name);
$uname = $osname[0].' '.$o->Version;
}
} else {
$uname = shell_exec('uname -rs');
}
return trim($uname);
} | Get system name/kernel version
@return string | https://github.com/plinker-rpc/system/blob/b0b83aad136a91c094eaac8c463df7c916d1c76e/src/System.php#L534-L548 |
plinker-rpc/system | src/System.php | System.cpu_info | public function cpu_info($parse = true)
{
$lines = trim(shell_exec('lscpu'));
if (!$parse) {
return $lines;
}
if (empty($lines)) {
return [];
}
$lines = explode(PHP_EOL, $lines);
$return = [];
foreach ($lines as $line) {
$parts = explode(':', $line);
$return[trim($parts[0])] = trim($parts[1]);
}
return $return;
} | php | public function cpu_info($parse = true)
{
$lines = trim(shell_exec('lscpu'));
if (!$parse) {
return $lines;
}
if (empty($lines)) {
return [];
}
$lines = explode(PHP_EOL, $lines);
$return = [];
foreach ($lines as $line) {
$parts = explode(':', $line);
$return[trim($parts[0])] = trim($parts[1]);
}
return $return;
} | Get system CPU info | https://github.com/plinker-rpc/system/blob/b0b83aad136a91c094eaac8c463df7c916d1c76e/src/System.php#L553-L574 |
plinker-rpc/system | src/System.php | System.load | public function load($parse = true)
{
$result = trim(shell_exec('cat /proc/loadavg'));
if (!$parse) {
return $result;
}
// break into parts
$parts = explode(' ', $result);
// current/total processes
$procs = explode('/', isset($parts[3]) ? trim($parts[3]) : '0/0');
return [
'1m' => isset($parts[0]) ? number_format(trim($parts[0]), 2) : '0.00',
'5m' => isset($parts[1]) ? number_format(trim($parts[1]), 2) : '0.00',
'15m' => isset($parts[2]) ? number_format(trim($parts[2]), 2) : '0.00',
'curr_proc' => $procs[0],
'totl_proc' => $procs[1],
'last_pid' => isset($parts[4]) ? trim($parts[4]) : 0
];
} | php | public function load($parse = true)
{
$result = trim(shell_exec('cat /proc/loadavg'));
if (!$parse) {
return $result;
}
// break into parts
$parts = explode(' ', $result);
// current/total processes
$procs = explode('/', isset($parts[3]) ? trim($parts[3]) : '0/0');
return [
'1m' => isset($parts[0]) ? number_format(trim($parts[0]), 2) : '0.00',
'5m' => isset($parts[1]) ? number_format(trim($parts[1]), 2) : '0.00',
'15m' => isset($parts[2]) ? number_format(trim($parts[2]), 2) : '0.00',
'curr_proc' => $procs[0],
'totl_proc' => $procs[1],
'last_pid' => isset($parts[4]) ? trim($parts[4]) : 0
];
} | Get system load avarages and process count/last pid | https://github.com/plinker-rpc/system/blob/b0b83aad136a91c094eaac8c463df7c916d1c76e/src/System.php#L594-L616 |
plinker-rpc/system | src/System.php | System.disks | public function disks($parse = true)
{
if ($this->host_os !== 'WINDOWS') {
$result = shell_exec('df -h --output=source,fstype,size,used,avail,pcent,target -x tmpfs -x devtmpfs');
} else {
$result = '';
}
if ($parse) {
if (empty($result)) {
return [];
}
$lines = explode(PHP_EOL, trim($result));
unset($lines[0]);
$columns = [
'Filesystem',
'Type',
'Size',
'Used',
'Avail',
'Used (%)',
'Mounted'
];
$result = [];
foreach ($lines as $row => $line) {
$column = array_values(array_filter(explode(' ', $line), 'strlen'));
foreach ($columns as $col => $key) {
$result[$row][$key] = @$column[$col];
}
}
$result = array_values($result);
}
return $result;
} | php | public function disks($parse = true)
{
if ($this->host_os !== 'WINDOWS') {
$result = shell_exec('df -h --output=source,fstype,size,used,avail,pcent,target -x tmpfs -x devtmpfs');
} else {
$result = '';
}
if ($parse) {
if (empty($result)) {
return [];
}
$lines = explode(PHP_EOL, trim($result));
unset($lines[0]);
$columns = [
'Filesystem',
'Type',
'Size',
'Used',
'Avail',
'Used (%)',
'Mounted'
];
$result = [];
foreach ($lines as $row => $line) {
$column = array_values(array_filter(explode(' ', $line), 'strlen'));
foreach ($columns as $col => $key) {
$result[$row][$key] = @$column[$col];
}
}
$result = array_values($result);
}
return $result;
} | Get disk file system table
@return string | https://github.com/plinker-rpc/system/blob/b0b83aad136a91c094eaac8c463df7c916d1c76e/src/System.php#L623-L659 |
plinker-rpc/system | src/System.php | System.uptime | public function uptime($option = '-p')
{
if ($this->host_os === 'WINDOWS') {
$wmi = new \COM("winmgmts:\\\\.\\root\\cimv2");
$os = $wmi->ExecQuery("SELECT * FROM Win32_OperatingSystem");
foreach ($os as $o) {
$date = explode('.', $o->LastBootUpTime);
$uptime_date = DateTime::createFromFormat('YmdHis', $date[0]);
$now = DateTime::createFromFormat('U', time());
$interval = $uptime_date->diff($now);
$uptime = $interval->format('up %a days, %h hours, %i minutes');
}
} else {
$uptime = shell_exec('uptime '.$option);
}
return trim($uptime);
} | php | public function uptime($option = '-p')
{
if ($this->host_os === 'WINDOWS') {
$wmi = new \COM("winmgmts:\\\\.\\root\\cimv2");
$os = $wmi->ExecQuery("SELECT * FROM Win32_OperatingSystem");
foreach ($os as $o) {
$date = explode('.', $o->LastBootUpTime);
$uptime_date = DateTime::createFromFormat('YmdHis', $date[0]);
$now = DateTime::createFromFormat('U', time());
$interval = $uptime_date->diff($now);
$uptime = $interval->format('up %a days, %h hours, %i minutes');
}
} else {
$uptime = shell_exec('uptime '.$option);
}
return trim($uptime);
} | Get system uptime | https://github.com/plinker-rpc/system/blob/b0b83aad136a91c094eaac8c463df7c916d1c76e/src/System.php#L664-L682 |
plinker-rpc/system | src/System.php | System.ping | public function ping($host = '', $port = 80)
{
$start = microtime(true);
$file = @fsockopen($host, $port, $errno, $errstr, 5);
$stop = microtime(true);
$status = 0;
if (!$file) {
$status = -1;
} else {
fclose($file);
$status = round((($stop - $start) * 1000), 2);
}
return $status;
} | php | public function ping($host = '', $port = 80)
{
$start = microtime(true);
$file = @fsockopen($host, $port, $errno, $errstr, 5);
$stop = microtime(true);
$status = 0;
if (!$file) {
$status = -1;
} else {
fclose($file);
$status = round((($stop - $start) * 1000), 2);
}
return $status;
} | Ping a server and return timing
@return float | https://github.com/plinker-rpc/system/blob/b0b83aad136a91c094eaac8c463df7c916d1c76e/src/System.php#L689-L703 |
plinker-rpc/system | src/System.php | System.distro | public function distro()
{
if (file_exists('/etc/redhat-release')) {
$centos_array = explode(' ', file_get_contents('/etc/redhat-release'));
return strtoupper($centos_array[0]);
}
if (file_exists('/etc/os-release')) {
preg_match('/ID=([a-zA-Z]+)/', file_get_contents('/etc/os-release'), $matches);
return strtoupper($matches[1]);
}
return false;
} | php | public function distro()
{
if (file_exists('/etc/redhat-release')) {
$centos_array = explode(' ', file_get_contents('/etc/redhat-release'));
return strtoupper($centos_array[0]);
}
if (file_exists('/etc/os-release')) {
preg_match('/ID=([a-zA-Z]+)/', file_get_contents('/etc/os-release'), $matches);
return strtoupper($matches[1]);
}
return false;
} | Get system distro
@return string | https://github.com/plinker-rpc/system/blob/b0b83aad136a91c094eaac8c463df7c916d1c76e/src/System.php#L710-L722 |
plinker-rpc/system | src/System.php | System.reboot | public function reboot()
{
if (!file_exists($this->tmp_path.'/reboot.sh')) {
file_put_contents($this->tmp_path.'/reboot.sh', '#!/bin/bash'.PHP_EOL.'/sbin/shutdown -r now');
chmod($this->tmp_path.'/reboot.sh', 0750);
}
shell_exec($this->tmp_path.'/reboot.sh');
return true;
} | php | public function reboot()
{
if (!file_exists($this->tmp_path.'/reboot.sh')) {
file_put_contents($this->tmp_path.'/reboot.sh', '#!/bin/bash'.PHP_EOL.'/sbin/shutdown -r now');
chmod($this->tmp_path.'/reboot.sh', 0750);
}
shell_exec($this->tmp_path.'/reboot.sh');
return true;
} | Reboot the system
@requires root
@return void | https://github.com/plinker-rpc/system/blob/b0b83aad136a91c094eaac8c463df7c916d1c76e/src/System.php#L763-L771 |
QoboLtd/cakephp-translations | src/Model/Table/LanguagesTable.php | LanguagesTable.localeToLanguage | public function localeToLanguage(string $locale): string
{
if (empty($locale)) {
throw new InvalidArgumentException("Locale must be a non-emptystring.");
}
// Truncate all, starting with underscore, at, or dot
$result = (string)preg_replace('/(_|@|\.).*$/', '', strtolower($locale));
// Convert to lowercase for consistency
$result = strtolower($result);
return $result;
} | php | public function localeToLanguage(string $locale): string
{
if (empty($locale)) {
throw new InvalidArgumentException("Locale must be a non-emptystring.");
}
// Truncate all, starting with underscore, at, or dot
$result = (string)preg_replace('/(_|@|\.).*$/', '', strtolower($locale));
// Convert to lowercase for consistency
$result = strtolower($result);
return $result;
} | Convert locale to language
On Linux, have a look at /usr/share/locale for the
list of possible locales and locale formats.
@throws \InvalidArgumentException when locale is not a string
@param string $locale Locale string (example: ru_RU.KOI8-R)
@return string Language (example: ru) | https://github.com/QoboLtd/cakephp-translations/blob/b488eafce71a55d517b975342487812f0d2d375a/src/Model/Table/LanguagesTable.php#L97-L109 |
QoboLtd/cakephp-translations | src/Model/Table/LanguagesTable.php | LanguagesTable.isRtl | public function isRtl(string $language): bool
{
$result = false;
// Simplify and verify, just in case
$language = $this->localeToLanguage($language);
if (in_array($language, $this->getRtl())) {
$result = true;
}
return $result;
} | php | public function isRtl(string $language): bool
{
$result = false;
// Simplify and verify, just in case
$language = $this->localeToLanguage($language);
if (in_array($language, $this->getRtl())) {
$result = true;
}
return $result;
} | Check if given language is right-to-left
@param string $language Language code or locale string (example: ru_RU.KOI8-R)
@return bool | https://github.com/QoboLtd/cakephp-translations/blob/b488eafce71a55d517b975342487812f0d2d375a/src/Model/Table/LanguagesTable.php#L129-L140 |
QoboLtd/cakephp-translations | src/Model/Table/LanguagesTable.php | LanguagesTable.getAvailable | public function getAvailable(): array
{
$result = [];
$dbLanguages = $this->find('list', ['keyField' => 'code', 'valueField' => 'name'])
->where(['trashed IS' => null])
->toArray();
$supportedLanguages = $this->getSupported();
$result = array_diff_assoc($supportedLanguages, $dbLanguages);
return $result;
} | php | public function getAvailable(): array
{
$result = [];
$dbLanguages = $this->find('list', ['keyField' => 'code', 'valueField' => 'name'])
->where(['trashed IS' => null])
->toArray();
$supportedLanguages = $this->getSupported();
$result = array_diff_assoc($supportedLanguages, $dbLanguages);
return $result;
} | Get a list of all available languages
Available languages are those that are in
configuration, but haven't yet been used for
an active language.
@return mixed[] | https://github.com/QoboLtd/cakephp-translations/blob/b488eafce71a55d517b975342487812f0d2d375a/src/Model/Table/LanguagesTable.php#L163-L174 |
QoboLtd/cakephp-translations | src/Model/Table/LanguagesTable.php | LanguagesTable.getName | public function getName(string $code): string
{
$result = $code;
if (empty($code)) {
throw new InvalidArgumentException("Code must be a non-empty string.");
}
$languages = $this->getSupported();
if (!empty($languages[$code])) {
$result = $languages[$code];
}
return $result;
} | php | public function getName(string $code): string
{
$result = $code;
if (empty($code)) {
throw new InvalidArgumentException("Code must be a non-empty string.");
}
$languages = $this->getSupported();
if (!empty($languages[$code])) {
$result = $languages[$code];
}
return $result;
} | Get language name by code
@throws \InvalidArgumentException when code is not a string
@param string $code Language code to lookup
@return string | https://github.com/QoboLtd/cakephp-translations/blob/b488eafce71a55d517b975342487812f0d2d375a/src/Model/Table/LanguagesTable.php#L183-L197 |
QoboLtd/cakephp-translations | src/Model/Table/LanguagesTable.php | LanguagesTable.addOrRestore | public function addOrRestore(array $data): \Translations\Model\Entity\Language
{
if (empty($data['code'])) {
throw new InvalidArgumentException("Language data is missing 'code' key");
}
if (empty($data['is_rtl'])) {
$data['is_rtl'] = $this->isRtl($data['code']);
}
if (empty($data['name'])) {
$data['name'] = $this->getName($data['code']);
}
/**
* @var \Cake\Datasource\EntityInterface $deletedEntity
*/
$deletedEntity = $this->find('onlyTrashed')
->where(['code' => $data['code']])
->first();
if (!empty($deletedEntity)) {
return $this->restoreTrash($deletedEntity);
}
$newEntity = $this->newEntity();
$newEntity = $this->patchEntity($newEntity, $data);
/**
* @var \Translations\Model\Entity\Language $result
*/
$result = $this->save($newEntity);
return $result;
} | php | public function addOrRestore(array $data): \Translations\Model\Entity\Language
{
if (empty($data['code'])) {
throw new InvalidArgumentException("Language data is missing 'code' key");
}
if (empty($data['is_rtl'])) {
$data['is_rtl'] = $this->isRtl($data['code']);
}
if (empty($data['name'])) {
$data['name'] = $this->getName($data['code']);
}
/**
* @var \Cake\Datasource\EntityInterface $deletedEntity
*/
$deletedEntity = $this->find('onlyTrashed')
->where(['code' => $data['code']])
->first();
if (!empty($deletedEntity)) {
return $this->restoreTrash($deletedEntity);
}
$newEntity = $this->newEntity();
$newEntity = $this->patchEntity($newEntity, $data);
/**
* @var \Translations\Model\Entity\Language $result
*/
$result = $this->save($newEntity);
return $result;
} | Add a new language or restore a deleted one
@throws \InvalidArgumentException when data is wrong or incomplete
@param mixed[] $data Language data to populate Entity with
@return \Translations\Model\Entity\Language | https://github.com/QoboLtd/cakephp-translations/blob/b488eafce71a55d517b975342487812f0d2d375a/src/Model/Table/LanguagesTable.php#L206-L239 |
tarsana/syntax | src/Text.php | Text.unwrap | public static function unwrap(string $text, string $wrappers) : string
{
$size = strlen($wrappers);
for ($i = 0; $i < $size; $i += 2) {
if (substr($text, 0, 1) == substr($wrappers, $i, 1)
&& substr($text, -1) == substr($wrappers, $i + 1, 1))
return substr($text, 1, strlen($text) - 2);
}
return $text;
} | php | public static function unwrap(string $text, string $wrappers) : string
{
$size = strlen($wrappers);
for ($i = 0; $i < $size; $i += 2) {
if (substr($text, 0, 1) == substr($wrappers, $i, 1)
&& substr($text, -1) == substr($wrappers, $i + 1, 1))
return substr($text, 1, strlen($text) - 2);
}
return $text;
} | ('"Hello"', '""') => 'Hello'
('(Hey)', '()') => 'Hey'
('(Hey)', '""()') => 'Hey' | https://github.com/tarsana/syntax/blob/fd3f8a25e3be0e391c8fd486ccfcffe913ade534/src/Text.php#L83-L92 |
luoxiaojun1992/lb_framework | components/algos/math/Num2Chinese.php | Num2Chinese.number2Chinese | public function number2Chinese($simple = true)
{
$str = '';
$unitPos = 0;
while ($this->num > 0) {
//分段字符串
$sectionStr = '';
//取最低四位
$section = $this->getLowBitPart($this->num, 4);
//获取段中文字符串
$this->section2Chinese($section, $sectionStr);
//拼接段数字单位
$sectionStr .= ($section != 0) ? self::CHINESE_UNIT_SECTION[$unitPos] : self::CHINESE_UNIT_SECTION[0];
$this->num = intval($this->num / 10000);
++$unitPos;
//补零
if (($section < 1000) && ($section > 0) && $this->num > 0) {
$sectionStr = self::CHINESE_NUM_CHAR[0] . $sectionStr;
}
$str = $sectionStr . $str;
}
return $str;
} | php | public function number2Chinese($simple = true)
{
$str = '';
$unitPos = 0;
while ($this->num > 0) {
//分段字符串
$sectionStr = '';
//取最低四位
$section = $this->getLowBitPart($this->num, 4);
//获取段中文字符串
$this->section2Chinese($section, $sectionStr);
//拼接段数字单位
$sectionStr .= ($section != 0) ? self::CHINESE_UNIT_SECTION[$unitPos] : self::CHINESE_UNIT_SECTION[0];
$this->num = intval($this->num / 10000);
++$unitPos;
//补零
if (($section < 1000) && ($section > 0) && $this->num > 0) {
$sectionStr = self::CHINESE_NUM_CHAR[0] . $sectionStr;
}
$str = $sectionStr . $str;
}
return $str;
} | 数字转中文
@param bool $simple
@return string | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/algos/math/Num2Chinese.php#L60-L90 |
luoxiaojun1992/lb_framework | components/algos/math/Num2Chinese.php | Num2Chinese.section2Chinese | private function section2Chinese($section, &$str, $simple = true)
{
$unitPos = 0;
while ($section > 0) {
//每一位数字字符串
$vStr = '';
//取最低一位
$v = $this->getLowBitPart($section, 1);
//拼接数字中文和单位
$vStr .= self::CHINESE_NUM_CHAR[$v];
$vStr .= ($v != 0) ? self::CHINESE_UNIT_CHAR[$unitPos] : self::CHINESE_UNIT_CHAR[0];
++$unitPos;
$section = intval($section / 10);
$str = $vStr . $str;
}
} | php | private function section2Chinese($section, &$str, $simple = true)
{
$unitPos = 0;
while ($section > 0) {
//每一位数字字符串
$vStr = '';
//取最低一位
$v = $this->getLowBitPart($section, 1);
//拼接数字中文和单位
$vStr .= self::CHINESE_NUM_CHAR[$v];
$vStr .= ($v != 0) ? self::CHINESE_UNIT_CHAR[$unitPos] : self::CHINESE_UNIT_CHAR[0];
++$unitPos;
$section = intval($section / 10);
$str = $vStr . $str;
}
} | 分段数字转中文
@param $section
@param $str
@param bool $simple | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/algos/math/Num2Chinese.php#L99-L119 |
chilimatic/chilimatic-framework | lib/cgenerator/Mysql.php | Mysql.scan_table | public function scan_table($table_name = '')
{
if (empty($table_name)) return false;
$this->_l_table_name = strtolower($table_name);
$this->table_name = $table_name;
$this->tpl_replacements['table_name'] = $table_name;
// get a more detailed description of the table
$sql = "SHOW FULL COLUMNS FROM `$table_name`";
$res = $this->db->query($sql);
$this->table_model = $this->db->fetch_object_list($res);
return true;
} | php | public function scan_table($table_name = '')
{
if (empty($table_name)) return false;
$this->_l_table_name = strtolower($table_name);
$this->table_name = $table_name;
$this->tpl_replacements['table_name'] = $table_name;
// get a more detailed description of the table
$sql = "SHOW FULL COLUMNS FROM `$table_name`";
$res = $this->db->query($sql);
$this->table_model = $this->db->fetch_object_list($res);
return true;
} | fetches a numeric table list
@param $table_name string
@return boolean | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/cgenerator/Mysql.php#L92-L107 |
chilimatic/chilimatic-framework | lib/cgenerator/Mysql.php | Mysql.get_type_value | public function get_type_value($type = null, $type_cast = false)
{
if (empty($type)) return "null";
if (strpos(strtolower($type), 'int') !== false) {
return ($type_cast) ? '(int)' : 0;
}
if (strpos(strtolower($type), 'float') !== false) {
return ($type_cast) ? '(float)' : 0;
}
if (strpos(strtolower($type), 'char') !== false) {
return ($type_cast) ? '(string)' : "''";
}
if (strpos(strtolower($type), 'enum') !== false) {
return ($type_cast) ? '(string)' : "''";
}
if (strpos(strtolower($type), 'dec') !== false) {
return ($type_cast) ? '(float)' : 0;
}
if (strpos(strtolower($type), 'text') !== false) {
return ($type_cast) ? '(string)' : "''";
}
if (strpos(strtolower($type), 'bit') !== false) {
return ($type_cast) ? '(string)' : "''";
}
if (strpos(strtolower($type), 'bool') !== false) {
return ($type_cast) ? '(boolean)' : "false";
}
if (strpos(strtolower($type), 'datetime') !== false) {
return ($type_cast) ? '(string)' : "'0000-00-00 00:00:00'";
}
if (strpos(strtolower($type), 'date') !== false) {
return ($type_cast) ? '(string)' : "'0000-00-00'";
}
if (strpos(strtolower($type), 'year') !== false) {
return ($type_cast) ? '(string)' : "'0000'";
}
if (strpos(strtolower($type), 'time') !== false) {
return ($type_cast) ? '(int)' : 0;
}
if (strpos(strtolower($type), 'double')) {
return ($type_cast) ? '(double)' : 0;
}
return "null";
} | php | public function get_type_value($type = null, $type_cast = false)
{
if (empty($type)) return "null";
if (strpos(strtolower($type), 'int') !== false) {
return ($type_cast) ? '(int)' : 0;
}
if (strpos(strtolower($type), 'float') !== false) {
return ($type_cast) ? '(float)' : 0;
}
if (strpos(strtolower($type), 'char') !== false) {
return ($type_cast) ? '(string)' : "''";
}
if (strpos(strtolower($type), 'enum') !== false) {
return ($type_cast) ? '(string)' : "''";
}
if (strpos(strtolower($type), 'dec') !== false) {
return ($type_cast) ? '(float)' : 0;
}
if (strpos(strtolower($type), 'text') !== false) {
return ($type_cast) ? '(string)' : "''";
}
if (strpos(strtolower($type), 'bit') !== false) {
return ($type_cast) ? '(string)' : "''";
}
if (strpos(strtolower($type), 'bool') !== false) {
return ($type_cast) ? '(boolean)' : "false";
}
if (strpos(strtolower($type), 'datetime') !== false) {
return ($type_cast) ? '(string)' : "'0000-00-00 00:00:00'";
}
if (strpos(strtolower($type), 'date') !== false) {
return ($type_cast) ? '(string)' : "'0000-00-00'";
}
if (strpos(strtolower($type), 'year') !== false) {
return ($type_cast) ? '(string)' : "'0000'";
}
if (strpos(strtolower($type), 'time') !== false) {
return ($type_cast) ? '(int)' : 0;
}
if (strpos(strtolower($type), 'double')) {
return ($type_cast) ? '(double)' : 0;
}
return "null";
} | get type value parses the mysql type and returns
@param $type string
@param bool|string $type_cast string
@return string | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/cgenerator/Mysql.php#L118-L176 |
chilimatic/chilimatic-framework | lib/cgenerator/Mysql.php | Mysql.generate_primary_key_statement | public function generate_primary_key_statement()
{
if (empty($this->primary_key)) return false;
if (count($this->primary_key) == 1) {
$this->tpl_replacements['primary_key_assign_statement'] = "'{$this->primary_key[0]}'";
$this->tpl_replacements['primary_key_if_statement'] = 'empty($this->' . (string)strtolower((string)$this->primary_key[0]) . ')';
$this->tpl_replacements['primary_key_where_statement'] = ' `' . (string)$this->primary_key[0] . '` = \'{$this->' . (string)strtolower((string)$this->primary_key[0]) . '}\'';
$this->tpl_replacements['primary_key_method_statement'] = '$' . strtolower((string)$this->primary_key[0]) . " = null";
return true;
}
$this->tpl_replacements['primary_key_assign_statement'] = 'array(';
foreach ($this->primary_key as $p_key) {
$this->tpl_replacements['primary_key_assign_statement'] .= "'$p_key',";
$this->tpl_replacements['primary_key_if_statement'] .= ' || empty($this->' . (string)strtolower((string)$p_key) . ')';
$this->tpl_replacements['primary_key_where_statement'] .= ' AND `' . (string)$p_key . '` = \'{$this->' . (string)strtolower((string)$p_key) . '}\'';
$this->tpl_replacements['primary_key_method_statement'] .= '$' . (string)strtolower((string)$p_key) . " = null,";
}
$this->tpl_replacements['primary_key_if_statement'] = substr($this->primary_key_if_statement, 4);
$this->tpl_replacements['primary_key_assign_statement'] = substr($this->primary_key_assign_statement, 0, -1) . ')';
$this->tpl_replacements['primary_key_method_statement'] = substr($this->primary_key_method_statement, 0, -1);
$this->tpl_replacements['primary_key_where_statement'] = substr($this->primary_key_where_statement, 5);
return true;
} | php | public function generate_primary_key_statement()
{
if (empty($this->primary_key)) return false;
if (count($this->primary_key) == 1) {
$this->tpl_replacements['primary_key_assign_statement'] = "'{$this->primary_key[0]}'";
$this->tpl_replacements['primary_key_if_statement'] = 'empty($this->' . (string)strtolower((string)$this->primary_key[0]) . ')';
$this->tpl_replacements['primary_key_where_statement'] = ' `' . (string)$this->primary_key[0] . '` = \'{$this->' . (string)strtolower((string)$this->primary_key[0]) . '}\'';
$this->tpl_replacements['primary_key_method_statement'] = '$' . strtolower((string)$this->primary_key[0]) . " = null";
return true;
}
$this->tpl_replacements['primary_key_assign_statement'] = 'array(';
foreach ($this->primary_key as $p_key) {
$this->tpl_replacements['primary_key_assign_statement'] .= "'$p_key',";
$this->tpl_replacements['primary_key_if_statement'] .= ' || empty($this->' . (string)strtolower((string)$p_key) . ')';
$this->tpl_replacements['primary_key_where_statement'] .= ' AND `' . (string)$p_key . '` = \'{$this->' . (string)strtolower((string)$p_key) . '}\'';
$this->tpl_replacements['primary_key_method_statement'] .= '$' . (string)strtolower((string)$p_key) . " = null,";
}
$this->tpl_replacements['primary_key_if_statement'] = substr($this->primary_key_if_statement, 4);
$this->tpl_replacements['primary_key_assign_statement'] = substr($this->primary_key_assign_statement, 0, -1) . ')';
$this->tpl_replacements['primary_key_method_statement'] = substr($this->primary_key_method_statement, 0, -1);
$this->tpl_replacements['primary_key_where_statement'] = substr($this->primary_key_where_statement, 5);
return true;
} | generates the primary key statement
@return bool | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/cgenerator/Mysql.php#L183-L210 |
chilimatic/chilimatic-framework | lib/cgenerator/Mysql.php | Mysql.init | public function init()
{
// the table model is an object list
if (empty($this->table_model)) {
return false;
}
// get a short tag based on the table name
if (!$this->get_table_short_tag()) return false;
$this->tpl_replacements['where_statement'] = '';
$this->tpl_replacements['load_row_list'] = '';
$this->tpl_replacements['trait_list'] = "\n\nuse " . $this->namespace . "Database;\n\n";
$this->tpl_replacements['update_insert_list'] = '';
$i = 0;
$count = count($this->table_model);
// try to fit all possibilities of generated code in here
// otherwise it would be iterated much more often
foreach ($this->table_model as $column) {
// to reduce the use of the strtolower function ;) just do it once
$property_name = strtolower($column->Field);
// get a list of properties
$property_list_unsorted[(string)$property_name] = (string)"\t/**" . ($column->Comment ? self::STD_INTEND_PROPERTIES . " * comment: $column->Comment" : '');
$property_list_unsorted[(string)$property_name] .= (string)($column->Extra || strtolower($column->Null) == 'no' ? self::STD_INTEND_PROPERTIES . " * Extra: $column->Extra[Not null]" : '');
$property_list_unsorted[(string)$property_name] .= (string)" " . self::STD_INTEND_PROPERTIES . " * @var $column->Type" . ($column->Key == 'PRI' ? " [PRIMARY KEY]" : '') . self::STD_INTEND_PROPERTIES . " */" . self::STD_INTEND_PROPERTIES . "public $" . $property_name . " = " . $this->get_type_value((($column->Null == 'NO' && !$this->with_null) ? $column->Type : '')) . ";\n\n";
if ($column->Key == 'PRI') {
$this->primary_key[] = $column->Field;
if (!empty($this->where_statement)) {
$this->tpl_replacements['where_statement'] .= (string)' AND ';
}
// generate generic where statement based on the primary keys
$this->tpl_replacements['where_statement'] .= (string)"`$column->Field` = '\$this->" . $property_name . "'";
$this->tpl_replacements['constructor_key_list'] = '';
$this->tpl_replacements['constructor_key_list'] .= (string)"\t\t" . '$this->' . $property_name . ' = $' . $property_name . ";\n";
}
if ($column->Null == 'NO') {
$this->tpl_replacements['mandatory_fields'][] = (string)$property_name;
}
// mysql list for the save function
$this->tpl_replacements['update_insert_list'] .= (string)"\t\t\$sql .= (\$this->$property_name !== " . (($column->Null == 'NO' && !$this->with_null) ? $this->get_type_value($column->Type) : 'null') . ") ? \"";
$this->tpl_replacements['update_insert_list'] .= (string)"`$column->Field`= '\" . Database_Tool::db_sanitize(stripslashes(\$this->$property_name)) . \"'";
$this->tpl_replacements['update_insert_list'] .= (string)($count != $i + 1 ? ', "' : '"') . " : '';\n";
// get multi keys for assignment
if ($column->Key == 'MUL') {
$this->key_list = (string)$column->Field;
}
// get multi keys for assignment
if ($column->Key == 'UNI') {
$this->key_list = (string)$column->Field;
}
// assign the SQL field list
$this->sql_field_list[] = (string)"`$this->table_short_tag`.`$column->Field`";
// generates the load row property assignment list
$this->tpl_replacements['load_row_list'] .= (string)"\t\t\$this->" . strtolower($column->Field) . " = " . (($column->Null == 'NO' && !$this->with_null) ? $this->get_type_value($column->Type, true) : '') . " isset(\$row->" . $column->Field . ") ? \$row->" . $column->Field . " : " . (($column->Null == 'NO' && !$this->with_null) ? $this->get_type_value($column->Type) : 'null') . ";\n";
$i = $i + 1;
}
// remove the last coma
// add the db to the listing of the class properties
$property_list_unsorted['db'] = (string)"\t/**" . self::STD_INTEND_PROPERTIES . " * Database object" . self::STD_INTEND_PROPERTIES . " * @var Object" . self::STD_INTEND_PROPERTIES . " */" . self::STD_INTEND_PROPERTIES . "public \$db = null;\n\n";
$property_list_unsorted['mandatory'] = (string)"\t/**" . self::STD_INTEND_PROPERTIES . " * list of mandatory fields " . self::STD_INTEND_PROPERTIES . " * @var array" . self::STD_INTEND_PROPERTIES . " */" . self::STD_INTEND_PROPERTIES . "public \$mandatory_field = array('" . implode("','", $this->tpl_replacements['mandatory_fields']) . "');\n\n";
// sort alpabetical based on the key
ksort($property_list_unsorted);
$this->tpl_replacements['property_list'] = implode("\n\n", $property_list_unsorted);
unset($property_list_unsorted);
$this->generate_primary_key_statement();
// implode the field list
$this->tpl_replacements['sql_field_list'] = implode(', ', $this->sql_field_list);
$this->tpl_replacements['constructor_param_list'] = '$' . strtolower(implode("'\n\t\t* @param ', $", $this->primary_key));
return true;
} | php | public function init()
{
// the table model is an object list
if (empty($this->table_model)) {
return false;
}
// get a short tag based on the table name
if (!$this->get_table_short_tag()) return false;
$this->tpl_replacements['where_statement'] = '';
$this->tpl_replacements['load_row_list'] = '';
$this->tpl_replacements['trait_list'] = "\n\nuse " . $this->namespace . "Database;\n\n";
$this->tpl_replacements['update_insert_list'] = '';
$i = 0;
$count = count($this->table_model);
// try to fit all possibilities of generated code in here
// otherwise it would be iterated much more often
foreach ($this->table_model as $column) {
// to reduce the use of the strtolower function ;) just do it once
$property_name = strtolower($column->Field);
// get a list of properties
$property_list_unsorted[(string)$property_name] = (string)"\t/**" . ($column->Comment ? self::STD_INTEND_PROPERTIES . " * comment: $column->Comment" : '');
$property_list_unsorted[(string)$property_name] .= (string)($column->Extra || strtolower($column->Null) == 'no' ? self::STD_INTEND_PROPERTIES . " * Extra: $column->Extra[Not null]" : '');
$property_list_unsorted[(string)$property_name] .= (string)" " . self::STD_INTEND_PROPERTIES . " * @var $column->Type" . ($column->Key == 'PRI' ? " [PRIMARY KEY]" : '') . self::STD_INTEND_PROPERTIES . " */" . self::STD_INTEND_PROPERTIES . "public $" . $property_name . " = " . $this->get_type_value((($column->Null == 'NO' && !$this->with_null) ? $column->Type : '')) . ";\n\n";
if ($column->Key == 'PRI') {
$this->primary_key[] = $column->Field;
if (!empty($this->where_statement)) {
$this->tpl_replacements['where_statement'] .= (string)' AND ';
}
// generate generic where statement based on the primary keys
$this->tpl_replacements['where_statement'] .= (string)"`$column->Field` = '\$this->" . $property_name . "'";
$this->tpl_replacements['constructor_key_list'] = '';
$this->tpl_replacements['constructor_key_list'] .= (string)"\t\t" . '$this->' . $property_name . ' = $' . $property_name . ";\n";
}
if ($column->Null == 'NO') {
$this->tpl_replacements['mandatory_fields'][] = (string)$property_name;
}
// mysql list for the save function
$this->tpl_replacements['update_insert_list'] .= (string)"\t\t\$sql .= (\$this->$property_name !== " . (($column->Null == 'NO' && !$this->with_null) ? $this->get_type_value($column->Type) : 'null') . ") ? \"";
$this->tpl_replacements['update_insert_list'] .= (string)"`$column->Field`= '\" . Database_Tool::db_sanitize(stripslashes(\$this->$property_name)) . \"'";
$this->tpl_replacements['update_insert_list'] .= (string)($count != $i + 1 ? ', "' : '"') . " : '';\n";
// get multi keys for assignment
if ($column->Key == 'MUL') {
$this->key_list = (string)$column->Field;
}
// get multi keys for assignment
if ($column->Key == 'UNI') {
$this->key_list = (string)$column->Field;
}
// assign the SQL field list
$this->sql_field_list[] = (string)"`$this->table_short_tag`.`$column->Field`";
// generates the load row property assignment list
$this->tpl_replacements['load_row_list'] .= (string)"\t\t\$this->" . strtolower($column->Field) . " = " . (($column->Null == 'NO' && !$this->with_null) ? $this->get_type_value($column->Type, true) : '') . " isset(\$row->" . $column->Field . ") ? \$row->" . $column->Field . " : " . (($column->Null == 'NO' && !$this->with_null) ? $this->get_type_value($column->Type) : 'null') . ";\n";
$i = $i + 1;
}
// remove the last coma
// add the db to the listing of the class properties
$property_list_unsorted['db'] = (string)"\t/**" . self::STD_INTEND_PROPERTIES . " * Database object" . self::STD_INTEND_PROPERTIES . " * @var Object" . self::STD_INTEND_PROPERTIES . " */" . self::STD_INTEND_PROPERTIES . "public \$db = null;\n\n";
$property_list_unsorted['mandatory'] = (string)"\t/**" . self::STD_INTEND_PROPERTIES . " * list of mandatory fields " . self::STD_INTEND_PROPERTIES . " * @var array" . self::STD_INTEND_PROPERTIES . " */" . self::STD_INTEND_PROPERTIES . "public \$mandatory_field = array('" . implode("','", $this->tpl_replacements['mandatory_fields']) . "');\n\n";
// sort alpabetical based on the key
ksort($property_list_unsorted);
$this->tpl_replacements['property_list'] = implode("\n\n", $property_list_unsorted);
unset($property_list_unsorted);
$this->generate_primary_key_statement();
// implode the field list
$this->tpl_replacements['sql_field_list'] = implode(', ', $this->sql_field_list);
$this->tpl_replacements['constructor_param_list'] = '$' . strtolower(implode("'\n\t\t* @param ', $", $this->primary_key));
return true;
} | initializes the whole object generating process
@return boolean | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/cgenerator/Mysql.php#L218-L301 |
RadialCorp/magento-core | src/app/code/community/Radial/Amqp/Helper/Config.php | Radial_Amqp_Helper_Config.getQueueConfigurationScopes | public function getQueueConfigurationScopes()
{
// cache of seen, unique AMQP configurations
$configurations = array();
// list of stores to produce unique AMQP configuration
$uniqueStores = array();
foreach (Mage::app()->getStores(true) as $store) {
$amqpConfig = $this->getStoreLevelAmqpConfigurations($store);
if (!in_array($amqpConfig, $configurations, true)) {
$configurations[] = $amqpConfig;
$uniqueStores[] = $store;
}
}
return $uniqueStores;
} | php | public function getQueueConfigurationScopes()
{
// cache of seen, unique AMQP configurations
$configurations = array();
// list of stores to produce unique AMQP configuration
$uniqueStores = array();
foreach (Mage::app()->getStores(true) as $store) {
$amqpConfig = $this->getStoreLevelAmqpConfigurations($store);
if (!in_array($amqpConfig, $configurations, true)) {
$configurations[] = $amqpConfig;
$uniqueStores[] = $store;
}
}
return $uniqueStores;
} | Get an array of stores with unique AMQP configuration.
@return Mage_Core_Model_Store[] | https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Amqp/Helper/Config.php#L58-L72 |
RadialCorp/magento-core | src/app/code/community/Radial/Amqp/Helper/Config.php | Radial_Amqp_Helper_Config.getStoreLevelAmqpConfigurations | public function getStoreLevelAmqpConfigurations(Mage_Core_Model_Store $store)
{
$coreConfig = $this->_coreHelper->getConfigModel($store);
$amqpConfig = $this->_helper->getConfigModel($store);
return array(
'store_id' => $coreConfig->storeId,
'username' => $amqpConfig->username,
'password' => $amqpConfig->password,
);
} | php | public function getStoreLevelAmqpConfigurations(Mage_Core_Model_Store $store)
{
$coreConfig = $this->_coreHelper->getConfigModel($store);
$amqpConfig = $this->_helper->getConfigModel($store);
return array(
'store_id' => $coreConfig->storeId,
'username' => $amqpConfig->username,
'password' => $amqpConfig->password,
);
} | Return config values that may vary by website/store for the given
store scope.
@param Mage_Core_Model_Store $store
@return array Config values for store id, AMQP username and AMQP password | https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Amqp/Helper/Config.php#L79-L88 |
RadialCorp/magento-core | src/app/code/community/Radial/Amqp/Helper/Config.php | Radial_Amqp_Helper_Config.getWebsiteLevelAmqpConfigurations | public function getWebsiteLevelAmqpConfigurations(Mage_Core_Model_Website $website)
{
$storeIdPath = $this->_coreConfigMap->getPathForKey(self::STORE_ID_CONFIG_KEY);
$usernamePath = $this->_amqpConfigMap->getPathForKey(self::USERNAME_CONFIG_KEY);
$passwordPath = $this->_amqpConfigMap->getPathForKey(self::PASSWORD_CONFIG_KEY);
$defaultCoreConfig = $this->_coreHelper->getConfigModel(Mage::app()->getStore(0));
$defaultAmqpConfig = $this->_helper->getConfigModel(Mage::app()->getStore(0));
// get website level config values, falling back to any not available to the
// website with default store config values
return array(
'store_id' => $website->getConfig($storeIdPath) ?: $defaultCoreConfig->storeId,
'username' => $website->getConfig($usernamePath) ?: $defaultAmqpConfig->username,
'password' => $this->_mageHelper->decrypt($website->getConfig($passwordPath)) ?: $defaultAmqpConfig->password,
);
} | php | public function getWebsiteLevelAmqpConfigurations(Mage_Core_Model_Website $website)
{
$storeIdPath = $this->_coreConfigMap->getPathForKey(self::STORE_ID_CONFIG_KEY);
$usernamePath = $this->_amqpConfigMap->getPathForKey(self::USERNAME_CONFIG_KEY);
$passwordPath = $this->_amqpConfigMap->getPathForKey(self::PASSWORD_CONFIG_KEY);
$defaultCoreConfig = $this->_coreHelper->getConfigModel(Mage::app()->getStore(0));
$defaultAmqpConfig = $this->_helper->getConfigModel(Mage::app()->getStore(0));
// get website level config values, falling back to any not available to the
// website with default store config values
return array(
'store_id' => $website->getConfig($storeIdPath) ?: $defaultCoreConfig->storeId,
'username' => $website->getConfig($usernamePath) ?: $defaultAmqpConfig->username,
'password' => $this->_mageHelper->decrypt($website->getConfig($passwordPath)) ?: $defaultAmqpConfig->password,
);
} | Return config values that may vary by website/store for the given
website.
@param Mage_Core_Model_Website $website
@return array Config values for store id, AMQP username and AMQP password | https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Amqp/Helper/Config.php#L95-L111 |
RadialCorp/magento-core | src/app/code/community/Radial/Amqp/Helper/Config.php | Radial_Amqp_Helper_Config.updateLastTimestamp | public function updateLastTimestamp(ITestMessage $payload, Mage_Core_Model_Store $store)
{
list($scope, $scopeId) = $this->getScopeForStoreSettings($store);
return Mage::getModel('core/config_data')
->addData(array(
'path' => $this->_amqpConfigMap->getPathForKey('last_test_message_timestamp'),
'value' => $payload->getTimestamp()->format(self::TIMESTAMP_FORMAT),
'scope' => $scope,
'scope_id' => $scopeId,
))
->save();
} | php | public function updateLastTimestamp(ITestMessage $payload, Mage_Core_Model_Store $store)
{
list($scope, $scopeId) = $this->getScopeForStoreSettings($store);
return Mage::getModel('core/config_data')
->addData(array(
'path' => $this->_amqpConfigMap->getPathForKey('last_test_message_timestamp'),
'value' => $payload->getTimestamp()->format(self::TIMESTAMP_FORMAT),
'scope' => $scope,
'scope_id' => $scopeId,
))
->save();
} | Update the core_config_data setting for timestamp from the last test
message received. Value should be saved in the most appropriate scope for
the store being processed. E.g. if the store is the default store, or has
the same AMQP configuration as the default store, the timestamp should be
updated in the default scope. If the stores AMQP configuration matches a
website level configuration, should be saved within that website's scope.
@param ITestMessage $payload
@param Mage_Core_Model_Store $store
@return Mage_Core_Model_Config_Data | https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Amqp/Helper/Config.php#L123-L134 |
RadialCorp/magento-core | src/app/code/community/Radial/Amqp/Helper/Config.php | Radial_Amqp_Helper_Config.getScopeForStoreSettings | public function getScopeForStoreSettings(Mage_Core_Model_Store $store)
{
$storeSettings = $this->getStoreLevelAmqpConfigurations($store);
$defaultStoreSettings = $this->getStoreLevelAmqpConfigurations(Mage::app()->getStore(0));
// start at the lowest possible level, the "default" scope and work up
if ($this->_isDefaultStore($store) || $storeSettings === $defaultStoreSettings) {
return array(self::DEFAULT_SCOPE_CODE, self::DEFAULT_STORE_ID);
}
// If no match for the default scope, check the website the store belongs to.
$website = $store->getWebsite();
if ($website && $storeSettings === $this->getWebsiteLevelAmqpConfigurations($website)) {
return array(self::WEBSITE_SCOPE_CODE, $website->getId());
}
// if no match for default or website, scope must be at the store level
return array(self::STORE_SCOPE_CODE, $store->getId());
} | php | public function getScopeForStoreSettings(Mage_Core_Model_Store $store)
{
$storeSettings = $this->getStoreLevelAmqpConfigurations($store);
$defaultStoreSettings = $this->getStoreLevelAmqpConfigurations(Mage::app()->getStore(0));
// start at the lowest possible level, the "default" scope and work up
if ($this->_isDefaultStore($store) || $storeSettings === $defaultStoreSettings) {
return array(self::DEFAULT_SCOPE_CODE, self::DEFAULT_STORE_ID);
}
// If no match for the default scope, check the website the store belongs to.
$website = $store->getWebsite();
if ($website && $storeSettings === $this->getWebsiteLevelAmqpConfigurations($website)) {
return array(self::WEBSITE_SCOPE_CODE, $website->getId());
}
// if no match for default or website, scope must be at the store level
return array(self::STORE_SCOPE_CODE, $store->getId());
} | Return the lowest possible scope and scope id with the same configurations
as the given store with "default" scope being the lowest, website second
and store view last. E.g. if the store has the same AMQP configuration as
a website with an id of 2 but different from the default store's AMQP
configuration, this should return 'website' and 2. If the store has the
same configuration as (or is) the default store, should return 'default'
and 0.
@param Mage_Core_Model_Store $store
@return mixed[] Tuple of scope "type" and scope id | https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Amqp/Helper/Config.php#L146-L161 |
romaricdrigon/OrchestraBundle | Controller/GenericController.php | GenericController.listAction | public function listAction(RepositoryDefinitionInterface $repository_definition, RepositoryInterface $repository, EntityReflectionInterface $entity)
{
$name = $this->get('orchestra.resolver.repository_name')->getName($repository_definition);
if (false === $entity->isListable()) {
throw new DomainErrorException('Entity '.$entity->getName().' is not listable. Maybe you forgot to implement ListableEntityInterface?');
}
// Get objects to show
$objects = $repository->listing();
// Do not use empty, Doctrine Collection does not support it, only count
$noData = (0 === count($objects));
// We will also need titles for our table header
$headers = [];
if (false === $noData) {
$headers = $this->get('orchestra.resolver.listing_header')->getHeaders($objects[0], 'viewListing');
}
// Finally, we need the routes for each entity
$actions = $this->get('orchestra.core_entity.action_collection_builder')->build($entity);
return $this->render('RomaricDrigonOrchestraBundle:Generic:list.html.twig', [
'actions' => $actions,
'headers' => $headers,
'no_data' => $noData,
'objects' => $objects,
'title' => $name
]);
} | php | public function listAction(RepositoryDefinitionInterface $repository_definition, RepositoryInterface $repository, EntityReflectionInterface $entity)
{
$name = $this->get('orchestra.resolver.repository_name')->getName($repository_definition);
if (false === $entity->isListable()) {
throw new DomainErrorException('Entity '.$entity->getName().' is not listable. Maybe you forgot to implement ListableEntityInterface?');
}
// Get objects to show
$objects = $repository->listing();
// Do not use empty, Doctrine Collection does not support it, only count
$noData = (0 === count($objects));
// We will also need titles for our table header
$headers = [];
if (false === $noData) {
$headers = $this->get('orchestra.resolver.listing_header')->getHeaders($objects[0], 'viewListing');
}
// Finally, we need the routes for each entity
$actions = $this->get('orchestra.core_entity.action_collection_builder')->build($entity);
return $this->render('RomaricDrigonOrchestraBundle:Generic:list.html.twig', [
'actions' => $actions,
'headers' => $headers,
'no_data' => $noData,
'objects' => $objects,
'title' => $name
]);
} | Action used when a repository "listing" is called
@param RepositoryDefinitionInterface $repository_definition
@param RepositoryInterface $repository
@param EntityReflectionInterface $entity
@throws DomainErrorException
@return \Symfony\Component\HttpFoundation\Response | https://github.com/romaricdrigon/OrchestraBundle/blob/4abb9736fcb6b23ed08ebd14ab169867339a4785/Controller/GenericController.php#L52-L82 |
romaricdrigon/OrchestraBundle | Controller/GenericController.php | GenericController.repositoryQueryAction | public function repositoryQueryAction(RepositoryDefinitionInterface $repository_definition, RepositoryInterface $repository, EntityReflectionInterface $entity, $repository_method)
{
return $this->render('RomaricDrigonOrchestraBundle:Generic:dashboard.html.twig', []);
} | php | public function repositoryQueryAction(RepositoryDefinitionInterface $repository_definition, RepositoryInterface $repository, EntityReflectionInterface $entity, $repository_method)
{
return $this->render('RomaricDrigonOrchestraBundle:Generic:dashboard.html.twig', []);
} | Action used when a method on en Repository is called
@param RepositoryDefinitionInterface $repository_definition
@param RepositoryInterface $repository
@param EntityReflectionInterface $entity
@param string $repository_method
@return \Symfony\Component\HttpFoundation\Response | https://github.com/romaricdrigon/OrchestraBundle/blob/4abb9736fcb6b23ed08ebd14ab169867339a4785/Controller/GenericController.php#L108-L111 |
romaricdrigon/OrchestraBundle | Controller/GenericController.php | GenericController.repositoryCommandAction | public function repositoryCommandAction(Request $request, RepositoryDefinitionInterface $repository_definition, RepositoryInterface $repository, $repository_method, CommandInterface $command)
{
$form = $this->createForm('orchestra_command_type', $command, [
'command' => $command
]);
$repoName = $this->get('orchestra.resolver.repository_name')->getName($repository_definition);
if ($request->isMethod('POST')) {
if ($form->handleRequest($request) && $form->isValid()) {
// Pass the command to the repository, and we're done!
call_user_func([$repository, $repository_method], $command);
$this->get('session')->getFlashBag()->add(
'success',
'Command run with success!'
);
// We redirect to "listing" page/action
$listRoute = $this->get('orchestra.resolver.repository_route_name')->getRouteName($repository, 'listing');
return $this->redirect($this->generateUrl($listRoute));
} else {
$this->get('session')->getFlashBag()->add(
'error',
'An error happened!'
);
}
}
return $this->render('RomaricDrigonOrchestraBundle:Generic:repositoryCommand.html.twig', [
'form' => $form->createView(),
'title' => $repoName
]);
} | php | public function repositoryCommandAction(Request $request, RepositoryDefinitionInterface $repository_definition, RepositoryInterface $repository, $repository_method, CommandInterface $command)
{
$form = $this->createForm('orchestra_command_type', $command, [
'command' => $command
]);
$repoName = $this->get('orchestra.resolver.repository_name')->getName($repository_definition);
if ($request->isMethod('POST')) {
if ($form->handleRequest($request) && $form->isValid()) {
// Pass the command to the repository, and we're done!
call_user_func([$repository, $repository_method], $command);
$this->get('session')->getFlashBag()->add(
'success',
'Command run with success!'
);
// We redirect to "listing" page/action
$listRoute = $this->get('orchestra.resolver.repository_route_name')->getRouteName($repository, 'listing');
return $this->redirect($this->generateUrl($listRoute));
} else {
$this->get('session')->getFlashBag()->add(
'error',
'An error happened!'
);
}
}
return $this->render('RomaricDrigonOrchestraBundle:Generic:repositoryCommand.html.twig', [
'form' => $form->createView(),
'title' => $repoName
]);
} | Action used when a method accepting a Command, on en Repository is called
@param Request $request
@param RepositoryDefinitionInterface $repository_definition
@param RepositoryInterface $repository
@param string $repository_method
@param CommandInterface $command
@return \Symfony\Component\HttpFoundation\Response | https://github.com/romaricdrigon/OrchestraBundle/blob/4abb9736fcb6b23ed08ebd14ab169867339a4785/Controller/GenericController.php#L123-L157 |
romaricdrigon/OrchestraBundle | Controller/GenericController.php | GenericController.entityCommandAction | public function entityCommandAction(Request $request, CommandInterface $command, EntityReflectionInterface $entity, $entity_method, EntityInterface $object = null)
{
if (null === $object) {
throw new NotFoundHttpException();
}
$form = $this->createForm('orchestra_command_type', $command, [
'command' => $command
]);
if ($request->isMethod('POST')) {
if ($form->handleRequest($request) && $form->isValid()) {
// Pass the command to the repository, and we're done!
call_user_func([$object, $entity_method], $command);
// We have to save the result!
// We use our provided ObjectManager, not Doctrine
$this->getObjectManager()->saveObject($object);
$this->get('session')->getFlashBag()->add(
'success',
'Command run with success!'
);
} else {
$this->get('session')->getFlashBag()->add(
'error',
'An error happened!'
);
}
}
return $this->render('RomaricDrigonOrchestraBundle:Generic:entityCommand.html.twig', [
'form' => $form->createView(),
'title' => $entity->getName().' - '.$entity_method
]);
} | php | public function entityCommandAction(Request $request, CommandInterface $command, EntityReflectionInterface $entity, $entity_method, EntityInterface $object = null)
{
if (null === $object) {
throw new NotFoundHttpException();
}
$form = $this->createForm('orchestra_command_type', $command, [
'command' => $command
]);
if ($request->isMethod('POST')) {
if ($form->handleRequest($request) && $form->isValid()) {
// Pass the command to the repository, and we're done!
call_user_func([$object, $entity_method], $command);
// We have to save the result!
// We use our provided ObjectManager, not Doctrine
$this->getObjectManager()->saveObject($object);
$this->get('session')->getFlashBag()->add(
'success',
'Command run with success!'
);
} else {
$this->get('session')->getFlashBag()->add(
'error',
'An error happened!'
);
}
}
return $this->render('RomaricDrigonOrchestraBundle:Generic:entityCommand.html.twig', [
'form' => $form->createView(),
'title' => $entity->getName().' - '.$entity_method
]);
} | Action used when a method accepting a Command, on en Entity is called
@param Request $request
@param CommandInterface $command
@param EntityReflectionInterface $entity
@param string $entity_method
@param EntityInterface $object
@throws NotFoundHttpException
@return \Symfony\Component\HttpFoundation\Response | https://github.com/romaricdrigon/OrchestraBundle/blob/4abb9736fcb6b23ed08ebd14ab169867339a4785/Controller/GenericController.php#L170-L205 |
romaricdrigon/OrchestraBundle | Controller/GenericController.php | GenericController.entityEventAction | public function entityEventAction(EntityReflectionInterface $entity, $entity_method, EntityInterface $object = null, RepositoryDefinitionInterface $repository_definition, RepositoryInterface $repository)
{
if (null === $object) {
throw new NotFoundHttpException();
}
// Get the Event
$event = call_user_func([$object, $entity_method]);
// We accept "null", in that case we do nothing, but no other objects
if (null !== $event && ! $event instanceof EventInterface) {
throw new DomainErrorException('An invalid Event was emitted by '.$entity->getName().' '.$entity_method.'. Maybe you forgot to implement EventInterface? Result must be either an implementation either null.');
}
if (! $repository instanceof ReceiveEventInterface) {
throw new DomainErrorException('Repository for Entity '.$entity->getName().' can not receive Events. Maybe you forgot to implement ReceiveEventInterface?');
}
if (null !== $event) {
call_user_func([$repository, 'receive'], $event);
$this->get('session')->getFlashBag()->add(
'success',
'Success!'
);
}
// We redirect to "listing" page/action
$listRoute = $this->get('orchestra.resolver.repository_route_name')->getRouteName($repository_definition, 'listing');
return $this->redirect($this->generateUrl($listRoute));
} | php | public function entityEventAction(EntityReflectionInterface $entity, $entity_method, EntityInterface $object = null, RepositoryDefinitionInterface $repository_definition, RepositoryInterface $repository)
{
if (null === $object) {
throw new NotFoundHttpException();
}
// Get the Event
$event = call_user_func([$object, $entity_method]);
// We accept "null", in that case we do nothing, but no other objects
if (null !== $event && ! $event instanceof EventInterface) {
throw new DomainErrorException('An invalid Event was emitted by '.$entity->getName().' '.$entity_method.'. Maybe you forgot to implement EventInterface? Result must be either an implementation either null.');
}
if (! $repository instanceof ReceiveEventInterface) {
throw new DomainErrorException('Repository for Entity '.$entity->getName().' can not receive Events. Maybe you forgot to implement ReceiveEventInterface?');
}
if (null !== $event) {
call_user_func([$repository, 'receive'], $event);
$this->get('session')->getFlashBag()->add(
'success',
'Success!'
);
}
// We redirect to "listing" page/action
$listRoute = $this->get('orchestra.resolver.repository_route_name')->getRouteName($repository_definition, 'listing');
return $this->redirect($this->generateUrl($listRoute));
} | Action used when a method with a "EmitEvent" annotations is called
@param EntityReflectionInterface $entity
@param string $entity_method
@param EntityInterface $object
@param RepositoryDefinitionInterface $repository_definition
@param RepositoryInterface $repository
@throws DomainErrorException
@throws NotFoundHttpException
@return \Symfony\Component\HttpFoundation\Response | https://github.com/romaricdrigon/OrchestraBundle/blob/4abb9736fcb6b23ed08ebd14ab169867339a4785/Controller/GenericController.php#L219-L250 |
antaresproject/sample_module | src/Http/Form/Configuration.php | Configuration.controlsFieldset | protected function controlsFieldset()
{
return $this->grid->fieldset(function (Fieldset $fieldset) {
$fieldset->legend('Sample Module Configuration');
$fieldset->control('input:text', 'name')
->label(trans('antares/sample_module::messages.configuration.labels.name'))
->attributes(['placeholder' => trans('antares/sample_module::messages.configuration.placeholders.name')])
->wrapper(['class' => 'w300']);
$fieldset->control('input:text', 'url')
->label(trans('antares/sample_module::messages.configuration.labels.url'))
->attributes(['placeholder' => trans('antares/sample_module::messages.configuration.placeholders.url')])
->fieldClass('input-field--group input-field--pre')
->before('<div class="input-field__pre"><span>' . (request()->secure() ? 'https://' : 'http://') . '</span></div>')
->wrapper(['class' => 'w400']);
$fieldset->control('select', 'date_format')
->wrapper(['class' => 'w180'])
->label(trans('antares/sample_module::messages.configuration.labels.date_format'))
->options(function() {
return app(DateFormat::class)->query()->get()->pluck('format', 'id');
});
$options = app(Country::class)->query()->get()->pluck('name', 'code');
$fieldset->control('select', 'default_country')
->label(trans('antares/sample_module::messages.configuration.labels.country'))
->attributes(['data-flag-select', 'data-selectAR' => true, 'class' => 'w200'])
->fieldClass('input-field--icon')
->prepend('<span class = "input-field__icon"><span class = "flag-icon"></span></span>')
->optionsData(function() use($options) {
$codes = $options->keys()->toArray();
$return = [];
foreach ($codes as $code) {
array_set($return, $code, ['country' => $code]);
}
return $return;
})
->options($options);
$checkbox = $fieldset->control('input:checkbox', 'checkbox')
->label(trans('antares/sample_module::messages.configuration.labels.checkbox'))
->value(1);
if (array_get($this->grid->row, 'checkbox')) {
$checkbox->checked();
}
$fieldset->control('ckeditor', 'content')
->label(trans('antares/sample_module::messages.configuration.labels.description'))
->attributes(['scripts' => true, 'class' => 'richtext'])
->name('content');
$fieldset->control('button', 'button')
->attributes(['type' => 'submit', 'value' => trans('Submit'), 'class' => 'btn btn--md btn--primary mdl-button mdl-js-button mdl-js-ripple-effect'])
->value(trans('antares/foundation::label.save_changes'));
});
} | php | protected function controlsFieldset()
{
return $this->grid->fieldset(function (Fieldset $fieldset) {
$fieldset->legend('Sample Module Configuration');
$fieldset->control('input:text', 'name')
->label(trans('antares/sample_module::messages.configuration.labels.name'))
->attributes(['placeholder' => trans('antares/sample_module::messages.configuration.placeholders.name')])
->wrapper(['class' => 'w300']);
$fieldset->control('input:text', 'url')
->label(trans('antares/sample_module::messages.configuration.labels.url'))
->attributes(['placeholder' => trans('antares/sample_module::messages.configuration.placeholders.url')])
->fieldClass('input-field--group input-field--pre')
->before('<div class="input-field__pre"><span>' . (request()->secure() ? 'https://' : 'http://') . '</span></div>')
->wrapper(['class' => 'w400']);
$fieldset->control('select', 'date_format')
->wrapper(['class' => 'w180'])
->label(trans('antares/sample_module::messages.configuration.labels.date_format'))
->options(function() {
return app(DateFormat::class)->query()->get()->pluck('format', 'id');
});
$options = app(Country::class)->query()->get()->pluck('name', 'code');
$fieldset->control('select', 'default_country')
->label(trans('antares/sample_module::messages.configuration.labels.country'))
->attributes(['data-flag-select', 'data-selectAR' => true, 'class' => 'w200'])
->fieldClass('input-field--icon')
->prepend('<span class = "input-field__icon"><span class = "flag-icon"></span></span>')
->optionsData(function() use($options) {
$codes = $options->keys()->toArray();
$return = [];
foreach ($codes as $code) {
array_set($return, $code, ['country' => $code]);
}
return $return;
})
->options($options);
$checkbox = $fieldset->control('input:checkbox', 'checkbox')
->label(trans('antares/sample_module::messages.configuration.labels.checkbox'))
->value(1);
if (array_get($this->grid->row, 'checkbox')) {
$checkbox->checked();
}
$fieldset->control('ckeditor', 'content')
->label(trans('antares/sample_module::messages.configuration.labels.description'))
->attributes(['scripts' => true, 'class' => 'richtext'])
->name('content');
$fieldset->control('button', 'button')
->attributes(['type' => 'submit', 'value' => trans('Submit'), 'class' => 'btn btn--md btn--primary mdl-button mdl-js-button mdl-js-ripple-effect'])
->value(trans('antares/foundation::label.save_changes'));
});
} | creates main controls fieldset
@return \Antares\Html\Form\Fieldset | https://github.com/antaresproject/sample_module/blob/aceab14f392c25e32729018518e9d6b4e6fe23db/src/Http/Form/Configuration.php#L58-L113 |
slexx1234/config | src/Config.php | Config.driver | protected function driver($method, ...$arguments)
{
if ($this->file === null) {
throw new NoFileSpecifiedException();
}
$parts = explode('.', $this->file);
$suffix = end($parts);
$driver = DriversManager::get($suffix);
if ($driver === null) {
throw new UndefinedDriverException($suffix);
}
return call_user_func_array([$driver, $method], $arguments);
} | php | protected function driver($method, ...$arguments)
{
if ($this->file === null) {
throw new NoFileSpecifiedException();
}
$parts = explode('.', $this->file);
$suffix = end($parts);
$driver = DriversManager::get($suffix);
if ($driver === null) {
throw new UndefinedDriverException($suffix);
}
return call_user_func_array([$driver, $method], $arguments);
} | Вызов метода драйвера конфигурации
@param string $method - Имя метода
@param array $arguments - Аргументы метода
@return string
@throws UndefinedDriverException|NoFileSpecifiedException | https://github.com/slexx1234/config/blob/46b42f0cdff2d5091003239d944e1634c24a2b34/src/Config.php#L48-L63 |
hal-platform/hal-core | src/VersionControl/VCSFactory.php | VCSFactory.addAdapter | public function addAdapter(string $type, VCSAdapterInterface $adapter): void
{
$this->adapters[$type] = $adapter;
} | php | public function addAdapter(string $type, VCSAdapterInterface $adapter): void
{
$this->adapters[$type] = $adapter;
} | @param string $type
@param VCSAdapterInterface $adapter
@return void | https://github.com/hal-platform/hal-core/blob/30d456f8392fc873301ad4217d2ae90436c67090/src/VersionControl/VCSFactory.php#L42-L45 |
hal-platform/hal-core | src/VersionControl/VCSFactory.php | VCSFactory.authenticate | public function authenticate(VersionControlProvider $vcs): ?VCSClientInterface
{
$adapter = $this->adapters[$vcs->type()] ?? null;
if (!$adapter) {
$this->addError(self::ERR_VCS_MISCONFIGURED);
return null;
}
$client = $adapter->buildClient($vcs);
if ($client instanceof VCSClientInterface) {
return $client;
}
$this->importErrors($adapter->errors());
return null;
} | php | public function authenticate(VersionControlProvider $vcs): ?VCSClientInterface
{
$adapter = $this->adapters[$vcs->type()] ?? null;
if (!$adapter) {
$this->addError(self::ERR_VCS_MISCONFIGURED);
return null;
}
$client = $adapter->buildClient($vcs);
if ($client instanceof VCSClientInterface) {
return $client;
}
$this->importErrors($adapter->errors());
return null;
} | @param VersionControlProvider $vcs
@return VCSClientInterface|null | https://github.com/hal-platform/hal-core/blob/30d456f8392fc873301ad4217d2ae90436c67090/src/VersionControl/VCSFactory.php#L52-L68 |
hal-platform/hal-core | src/VersionControl/VCSFactory.php | VCSFactory.downloader | public function downloader(VersionControlProvider $vcs): ?VCSDownloaderInterface
{
$adapter = $this->adapters[$vcs->type()] ?? null;
if (!$adapter) {
$this->addError(self::ERR_VCS_MISCONFIGURED);
return null;
}
$downloader = $adapter->buildDownloader($vcs);
if ($downloader instanceof VCSDownloaderInterface) {
return $downloader;
}
$this->importErrors($adapter->errors());
return null;
} | php | public function downloader(VersionControlProvider $vcs): ?VCSDownloaderInterface
{
$adapter = $this->adapters[$vcs->type()] ?? null;
if (!$adapter) {
$this->addError(self::ERR_VCS_MISCONFIGURED);
return null;
}
$downloader = $adapter->buildDownloader($vcs);
if ($downloader instanceof VCSDownloaderInterface) {
return $downloader;
}
$this->importErrors($adapter->errors());
return null;
} | @param VersionControlProvider $vcs
@return VCSDownloaderInterface|null | https://github.com/hal-platform/hal-core/blob/30d456f8392fc873301ad4217d2ae90436c67090/src/VersionControl/VCSFactory.php#L75-L91 |
luoxiaojun1992/lb_framework | components/helpers/FileHelper.php | FileHelper.delete | public static function delete($file_path)
{
$result = false;
if (self::fileExists($file_path)) {
$result = unlink($file_path);
}
return $result;
} | php | public static function delete($file_path)
{
$result = false;
if (self::fileExists($file_path)) {
$result = unlink($file_path);
}
return $result;
} | Delete a file
@param $file_path
@return bool | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/helpers/FileHelper.php#L23-L30 |
luoxiaojun1992/lb_framework | components/helpers/FileHelper.php | FileHelper.download | public static function download($file_path, $file_name, ResponseContract $response = null)
{
if (file_exists(iconv('UTF-8', 'GB2312', $file_path))) {
$file_size = filesize($file_path);
$fp = fopen($file_path, self::READ_BINARY);
self::header('Content-type', 'application/octet-stream', $response);
self::header('Accept-Ranges', 'bytes', $response);
self::header('Accept-Length', $file_size, $response);
self::header('Content-Disposition', 'attachment; filename=' . $file_name, $response);
self::header('Expires', '-1', $response);
self::header('Cache-Control', 'no_cache', $response);
self::header('Pragma', 'no-cache', $response);
//兼容IE11
$ua = Lb::app()->getUserAgent();
$encoded_filename = urlencode($file_name);
if(preg_match("/MSIE/is", $ua) || preg_match(preg_quote("/Trident/7.0/is"), $ua)) {
self::header('Content-Disposition', 'attachment; filename="' . $encoded_filename . '"', $response);
} else if (preg_match("/Firefox/", $ua)) {
self::header('Content-Disposition', 'attachment; filename*="utf8\'\'' . $file_name . '"', $response);
} else {
self::header('Content-Disposition', 'attachment; filename="' . $file_name . '"', $response);
}
echo fread($fp, $file_size);
fclose($fp);
exit;
}
} | php | public static function download($file_path, $file_name, ResponseContract $response = null)
{
if (file_exists(iconv('UTF-8', 'GB2312', $file_path))) {
$file_size = filesize($file_path);
$fp = fopen($file_path, self::READ_BINARY);
self::header('Content-type', 'application/octet-stream', $response);
self::header('Accept-Ranges', 'bytes', $response);
self::header('Accept-Length', $file_size, $response);
self::header('Content-Disposition', 'attachment; filename=' . $file_name, $response);
self::header('Expires', '-1', $response);
self::header('Cache-Control', 'no_cache', $response);
self::header('Pragma', 'no-cache', $response);
//兼容IE11
$ua = Lb::app()->getUserAgent();
$encoded_filename = urlencode($file_name);
if(preg_match("/MSIE/is", $ua) || preg_match(preg_quote("/Trident/7.0/is"), $ua)) {
self::header('Content-Disposition', 'attachment; filename="' . $encoded_filename . '"', $response);
} else if (preg_match("/Firefox/", $ua)) {
self::header('Content-Disposition', 'attachment; filename*="utf8\'\'' . $file_name . '"', $response);
} else {
self::header('Content-Disposition', 'attachment; filename="' . $file_name . '"', $response);
}
echo fread($fp, $file_size);
fclose($fp);
exit;
}
} | Download a file
@param $file_path
@param $file_name
@param $response | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/helpers/FileHelper.php#L69-L95 |
luoxiaojun1992/lb_framework | components/helpers/FileHelper.php | FileHelper.header | protected static function header($headerKey, $headerValue, ResponseContract $response = null)
{
if ($response) {
$response->setHeader($headerKey, $headerValue);
} else {
ResponseKit::setHeader($headerKey, $headerValue);
}
} | php | protected static function header($headerKey, $headerValue, ResponseContract $response = null)
{
if ($response) {
$response->setHeader($headerKey, $headerValue);
} else {
ResponseKit::setHeader($headerKey, $headerValue);
}
} | Set header
@param $headerKey
@param $headerValue
@param ResponseContract|null $response | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/helpers/FileHelper.php#L104-L111 |
luoxiaojun1992/lb_framework | components/helpers/FileHelper.php | FileHelper.upload | public static function upload($file_name, $saved_file_path, $uploaded_file_type_limit = null, $uploaded_file_size_limit = null, $uploaded_file_ext_limit = null)
{
$storage = new \Upload\Storage\FileSystem($saved_file_path);
$file = new \Upload\File($file_name, $storage);
// Optionally you can rename the file on upload
/**
* @var IdGenerator $idGenerator
*/
$idGenerator = IdGenerator::component();
$new_filename = $idGenerator->generate();
$file->setName($new_filename);
// Validate file upload
// MimeType List => http://www.iana.org/assignments/media-types/media-types.xhtml
$validations = [];
if ($uploaded_file_type_limit) {
//You can also add multi mimetype validation
$validations[] = new \Upload\Validation\Mimetype($uploaded_file_type_limit);
}
if ($uploaded_file_size_limit) {
// Ensure file is no larger than 5M (use "B", "K", M", or "G")
$validations[] = new \Upload\Validation\Size($uploaded_file_size_limit);
}
if ($uploaded_file_ext_limit) {
$validations[] = new \Upload\Validation\Extension($uploaded_file_ext_limit);
}
if ($validations) {
$file->addValidations($validations);
}
// Access data about the file that has been uploaded
$data = array(
'name' => $file->getNameWithExtension(),
'extension' => $file->getExtension(),
'mime' => $file->getMimetype(),
'size' => $file->getSize(),
'md5' => $file->getMd5(),
'dimensions' => $file->getDimensions()
);
// Try to upload file
try {
// Success!
$file->upload();
return ['result' => 'success', 'new_name' => $new_filename, 'data' => $data];
} catch (\Throwable $e) {
// Fail!
$errors = $file->getErrors();
return ['result' => 'failed', 'errors' => $errors];
}
} | php | public static function upload($file_name, $saved_file_path, $uploaded_file_type_limit = null, $uploaded_file_size_limit = null, $uploaded_file_ext_limit = null)
{
$storage = new \Upload\Storage\FileSystem($saved_file_path);
$file = new \Upload\File($file_name, $storage);
// Optionally you can rename the file on upload
/**
* @var IdGenerator $idGenerator
*/
$idGenerator = IdGenerator::component();
$new_filename = $idGenerator->generate();
$file->setName($new_filename);
// Validate file upload
// MimeType List => http://www.iana.org/assignments/media-types/media-types.xhtml
$validations = [];
if ($uploaded_file_type_limit) {
//You can also add multi mimetype validation
$validations[] = new \Upload\Validation\Mimetype($uploaded_file_type_limit);
}
if ($uploaded_file_size_limit) {
// Ensure file is no larger than 5M (use "B", "K", M", or "G")
$validations[] = new \Upload\Validation\Size($uploaded_file_size_limit);
}
if ($uploaded_file_ext_limit) {
$validations[] = new \Upload\Validation\Extension($uploaded_file_ext_limit);
}
if ($validations) {
$file->addValidations($validations);
}
// Access data about the file that has been uploaded
$data = array(
'name' => $file->getNameWithExtension(),
'extension' => $file->getExtension(),
'mime' => $file->getMimetype(),
'size' => $file->getSize(),
'md5' => $file->getMd5(),
'dimensions' => $file->getDimensions()
);
// Try to upload file
try {
// Success!
$file->upload();
return ['result' => 'success', 'new_name' => $new_filename, 'data' => $data];
} catch (\Throwable $e) {
// Fail!
$errors = $file->getErrors();
return ['result' => 'failed', 'errors' => $errors];
}
} | Upload a file
@param $file_name
@param $saved_file_path
@param null $uploaded_file_type_limit
@param null $uploaded_file_size_limit
@param null $uploaded_file_ext_limit
@return array | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/helpers/FileHelper.php#L123-L174 |
luoxiaojun1992/lb_framework | components/helpers/FileHelper.php | FileHelper.send | public static function send($filePath, $remoteFileSystem)
{
return (new Client())->put($remoteFileSystem, ['body' => fopen($filePath, self::READ_BINARY)])
->getStatusCode() == HttpHelper::STATUS_OK;
} | php | public static function send($filePath, $remoteFileSystem)
{
return (new Client())->put($remoteFileSystem, ['body' => fopen($filePath, self::READ_BINARY)])
->getStatusCode() == HttpHelper::STATUS_OK;
} | Send a file
@param $filePath
@param $remoteFileSystem
@return bool | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/helpers/FileHelper.php#L183-L187 |
luoxiaojun1992/lb_framework | components/helpers/FileHelper.php | FileHelper.receive | public static function receive($savePath, RequestContract $request = null)
{
file_put_contents($savePath, $request ? $request->getRawContent() : RequestKit::getRawContent());
} | php | public static function receive($savePath, RequestContract $request = null)
{
file_put_contents($savePath, $request ? $request->getRawContent() : RequestKit::getRawContent());
} | Receive a file
@param $savePath
@param RequestContract|null $request | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/helpers/FileHelper.php#L195-L198 |
luoxiaojun1992/lb_framework | components/helpers/FileHelper.php | FileHelper.copy | public static function copy($src, $dst, $context = null)
{
return self::resourceExists($src) ? copy($src, $dst, $context) : false;
} | php | public static function copy($src, $dst, $context = null)
{
return self::resourceExists($src) ? copy($src, $dst, $context) : false;
} | Copy a file or a directory
@param $src
@param $dst
@param null $context
@return bool | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/helpers/FileHelper.php#L208-L211 |
luoxiaojun1992/lb_framework | components/helpers/FileHelper.php | FileHelper.move | public static function move($oldName, $newName, $context = null)
{
return self::rename($oldName, $newName, $context);
} | php | public static function move($oldName, $newName, $context = null)
{
return self::rename($oldName, $newName, $context);
} | Move a file or a directory
@param $oldName
@param $newName
@param null $context
@return bool | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/helpers/FileHelper.php#L221-L224 |
luoxiaojun1992/lb_framework | components/helpers/FileHelper.php | FileHelper.rename | public static function rename($oldName, $newName, $context = null)
{
return self::resourceExists($oldName) ? rename($oldName, $newName, $context) : false;
} | php | public static function rename($oldName, $newName, $context = null)
{
return self::resourceExists($oldName) ? rename($oldName, $newName, $context) : false;
} | Rename a file or a directory
@param $oldName
@param $newName
@param null $context
@return bool | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/helpers/FileHelper.php#L234-L237 |
heliopsis/ezforms-bundle | Heliopsis/eZFormsBundle/Provider/Handler/Chain.php | Chain.getHandler | public function getHandler( Location $location )
{
foreach ( $this->providers as $providersPriority )
{
foreach ( $providersPriority as $provider )
{
$currentHandler = $provider->getHandler( $location );
if ( !$currentHandler instanceof NullHandler )
{
return $currentHandler;
}
}
}
return new NullHandler();
} | php | public function getHandler( Location $location )
{
foreach ( $this->providers as $providersPriority )
{
foreach ( $providersPriority as $provider )
{
$currentHandler = $provider->getHandler( $location );
if ( !$currentHandler instanceof NullHandler )
{
return $currentHandler;
}
}
}
return new NullHandler();
} | Returns form handler to use at $location
@param \eZ\Publish\API\Repository\Values\Content\Location $location
@return \Heliopsis\eZFormsBundle\FormHandler\FormHandlerInterface | https://github.com/heliopsis/ezforms-bundle/blob/ed87feeb76fcdcd4a4e355d4bc60b83077ba90b4/Heliopsis/eZFormsBundle/Provider/Handler/Chain.php#L52-L68 |
Synapse-Cmf/synapse-cmf | src/Synapse/Cmf/Bundle/Controller/StaticComponentController.php | StaticComponentController.renderAction | public function renderAction(ComponentInterface $component, ContentInterface $content)
{
if (empty($component->getData('_template'))) {
// @todo log
return new Response('');
}
return $this->get('synapse')
->createDecorator($component)
->decorate(array('content' => $content))
;
} | php | public function renderAction(ComponentInterface $component, ContentInterface $content)
{
if (empty($component->getData('_template'))) {
// @todo log
return new Response('');
}
return $this->get('synapse')
->createDecorator($component)
->decorate(array('content' => $content))
;
} | Component rendering action.
@param ComponentInterface $component
@param ContentInterface $content
@return Response | https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Bundle/Controller/StaticComponentController.php#L23-L34 |
chilimatic/chilimatic-framework | lib/cache/handler/ModelCache.php | ModelCache.get | public function get(AbstractModel $model, $param = null)
{
$this->modelStorage->rewind();
foreach ($this->modelStorage as $storedModel) {
if ($storedModel === $model) {
return $model;
}
}
return null;
} | php | public function get(AbstractModel $model, $param = null)
{
$this->modelStorage->rewind();
foreach ($this->modelStorage as $storedModel) {
if ($storedModel === $model) {
return $model;
}
}
return null;
} | @param AbstractModel $model
@param null $param
@return AbstractModel|null | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/cache/handler/ModelCache.php#L56-L67 |
as3io/modlr | src/Events/EventDispatcher.php | EventDispatcher.addListener | public function addListener($eventNames, $listener)
{
$key = $this->getListenerKey($listener);
foreach ((Array) $eventNames as $eventName) {
if (!method_exists($listener, $eventName)) {
throw new \InvalidArgumentException(sprintf('The listener class %s does not have the appropriate event method. Expected method "%s"', get_class($listener), $eventName));
}
$this->listeners[$eventName][$key] = $listener;
}
return $this;
} | php | public function addListener($eventNames, $listener)
{
$key = $this->getListenerKey($listener);
foreach ((Array) $eventNames as $eventName) {
if (!method_exists($listener, $eventName)) {
throw new \InvalidArgumentException(sprintf('The listener class %s does not have the appropriate event method. Expected method "%s"', get_class($listener), $eventName));
}
$this->listeners[$eventName][$key] = $listener;
}
return $this;
} | Adds an event listener.
@param string|array $eventNames The event name(s) to listen for.
@param object $listener The event listener object.
@return self
@throws \InvalidArgumentException If the listener does not contain the event method. | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Events/EventDispatcher.php#L29-L39 |
as3io/modlr | src/Events/EventDispatcher.php | EventDispatcher.dispatch | public function dispatch($eventName, EventArguments $arguments = null)
{
if (false === $this->hasListeners($eventName)) {
return $this;
}
$arguments = $arguments ?: EventArguments::createEmpty();
foreach ($this->getListeners($eventName) as $listener) {
$listener->$eventName($arguments);
}
return $this;
} | php | public function dispatch($eventName, EventArguments $arguments = null)
{
if (false === $this->hasListeners($eventName)) {
return $this;
}
$arguments = $arguments ?: EventArguments::createEmpty();
foreach ($this->getListeners($eventName) as $listener) {
$listener->$eventName($arguments);
}
return $this;
} | Dispatches an event to all registered listeners.
@param EventArguments|null $arguments
@return self | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Events/EventDispatcher.php#L58-L68 |
as3io/modlr | src/Events/EventDispatcher.php | EventDispatcher.getListeners | protected function getListeners($eventName)
{
if (isset($this->listeners[$eventName])) {
return $this->listeners[$eventName];
}
return null;
} | php | protected function getListeners($eventName)
{
if (isset($this->listeners[$eventName])) {
return $this->listeners[$eventName];
}
return null;
} | Gets all registered listeners for an event name.
@param string $eventName
@return array|null | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Events/EventDispatcher.php#L91-L97 |
as3io/modlr | src/Events/EventDispatcher.php | EventDispatcher.removeListener | public function removeListener($eventNames, $listener)
{
$key = $this->getListenerKey($listener);
foreach ((Array) $eventNames as $eventName) {
if (isset($this->listeners[$eventName][$key])) {
unset($this->listeners[$eventName][$key]);
}
}
return $this;
} | php | public function removeListener($eventNames, $listener)
{
$key = $this->getListenerKey($listener);
foreach ((Array) $eventNames as $eventName) {
if (isset($this->listeners[$eventName][$key])) {
unset($this->listeners[$eventName][$key]);
}
}
return $this;
} | Removes an event listener, if registered.
@param string|array $eventNames The event name(s) to listen for.
@param object $listener The event listener object.
@return self | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Events/EventDispatcher.php#L117-L126 |
inhere/php-library-plus | libs/Log/AbstractLogger.php | AbstractLogger.addRecord | public function addRecord($level, $message, array $context = array())
{
if (!$this->handlers) {
$this->pushHandler(new StreamHandler('php://stderr', static::DEBUG));
}
$levelName = static::getLevelName($level);
} | php | public function addRecord($level, $message, array $context = array())
{
if (!$this->handlers) {
$this->pushHandler(new StreamHandler('php://stderr', static::DEBUG));
}
$levelName = static::getLevelName($level);
} | Adds a log record.
@param int $level The logging level
@param string $message The log message
@param array $context The log context
@return Boolean Whether the record has been processed | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Log/AbstractLogger.php#L185-L192 |
inhere/php-library-plus | libs/Log/AbstractLogger.php | AbstractLogger.log | public function log($level, $message, array $context = array())
{
$level = static::toNumberLevel($level);
return $this->addRecord($level, $message, $context);
} | php | public function log($level, $message, array $context = array())
{
$level = static::toNumberLevel($level);
return $this->addRecord($level, $message, $context);
} | Adds a log record at an arbitrary level.
This method allows for compatibility with common interfaces.
@param int|string $level The log level
@param string $message The log message
@param array $context The log context
@return Boolean Whether the record has been processed | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Log/AbstractLogger.php#L202-L207 |
inhere/php-library-plus | libs/Log/AbstractLogger.php | AbstractLogger.profile | public function profile($name, array $context = [], $category = 'application')
{
$context['startTime'] = microtime(true);
$context['memUsage'] = memory_get_usage();
$context['memPeakUsage'] = memory_get_peak_usage();
$this->profiles[$category][$name] = $context;
} | php | public function profile($name, array $context = [], $category = 'application')
{
$context['startTime'] = microtime(true);
$context['memUsage'] = memory_get_usage();
$context['memPeakUsage'] = memory_get_peak_usage();
$this->profiles[$category][$name] = $context;
} | mark data analysis start
@param $name
@param array $context
@param string $category | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Log/AbstractLogger.php#L230-L237 |
inhere/php-library-plus | libs/Log/AbstractLogger.php | AbstractLogger.write | protected function write($str)
{
$file = $this->getLogPath() . $this->getFilename();
$dir = \dirname($file);
if (!is_dir($dir) && !@mkdir($dir, 0775, true)) {
throw new FileSystemException("Create log directory failed. $dir");
}
// check file size
if (is_file($file) && filesize($file) > $this->maxSize * 1000 * 1000) {
rename($file, substr($file, 0, -3) . time() . '.log');
}
// return error_log($str, 3, $file);
return file_put_contents($file, $str, FILE_APPEND);
} | php | protected function write($str)
{
$file = $this->getLogPath() . $this->getFilename();
$dir = \dirname($file);
if (!is_dir($dir) && !@mkdir($dir, 0775, true)) {
throw new FileSystemException("Create log directory failed. $dir");
}
// check file size
if (is_file($file) && filesize($file) > $this->maxSize * 1000 * 1000) {
rename($file, substr($file, 0, -3) . time() . '.log');
}
// return error_log($str, 3, $file);
return file_put_contents($file, $str, FILE_APPEND);
} | write log info to file
@param string $str
@return bool
@throws FileSystemException | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Log/AbstractLogger.php#L394-L410 |
inhere/php-library-plus | libs/Log/AbstractLogger.php | AbstractLogger.getLevelName | public static function getLevelName($level)
{
if (!isset(static::$levels[$level])) {
throw new \InvalidArgumentException('Level "' . $level . '" is not defined, use one of: ' . implode(', ', array_keys(static::$levels)));
}
return static::$levels[$level];
} | php | public static function getLevelName($level)
{
if (!isset(static::$levels[$level])) {
throw new \InvalidArgumentException('Level "' . $level . '" is not defined, use one of: ' . implode(', ', array_keys(static::$levels)));
}
return static::$levels[$level];
} | Gets the name of the logging level.
@param int $level
@return string | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Log/AbstractLogger.php#L483-L490 |
inhere/php-library-plus | libs/Log/AbstractLogger.php | AbstractLogger.toNumberLevel | public static function toNumberLevel($level)
{
if (\is_string($level) && \defined(__CLASS__ . '::' . strtoupper($level))) {
return \constant(__CLASS__ . '::' . strtoupper($level));
}
return $level;
} | php | public static function toNumberLevel($level)
{
if (\is_string($level) && \defined(__CLASS__ . '::' . strtoupper($level))) {
return \constant(__CLASS__ . '::' . strtoupper($level));
}
return $level;
} | Converts PSR-3 levels to Monolog ones if necessary
@param string|int Level number (monolog) or name (PSR-3)
@return int | https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Log/AbstractLogger.php#L497-L504 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.