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
|
---|---|---|---|---|---|---|---|
tasoftch/php-service-manager | src/ServiceManager.php | ServiceManager.mapArray | public function mapArray( $array, bool $recursive = false) {
$handler = $this->_getMapValueHandler();
$mapper = $recursive ? new RecursiveCallbackMapper($handler) : new CallbackMapper($handler);
$mapping = new CollectionMapping($mapper);
return $mapping->mapCollection($array);
} | php | public function mapArray( $array, bool $recursive = false) {
$handler = $this->_getMapValueHandler();
$mapper = $recursive ? new RecursiveCallbackMapper($handler) : new CallbackMapper($handler);
$mapping = new CollectionMapping($mapper);
return $mapping->mapCollection($array);
} | Maps a given array into and resolves all markers /^\\$([a-zA-Z_][a-zA-Z_0-9]*)$/
with the expected service instance
@param iterable $array
@param bool $recursive
@return iterable | https://github.com/tasoftch/php-service-manager/blob/5f627d81457356f6c087398cd1e8f8e4f9d14822/src/ServiceManager.php#L378-L383 |
tasoftch/php-service-manager | src/ServiceManager.php | ServiceManager.mapValue | public function mapValue($value, bool $recursive = false) {
if(is_iterable($value))
return $this->mapArray($value, $recursive);
return $this->_getMapValueHandler()(NULL, $value);
} | php | public function mapValue($value, bool $recursive = false) {
if(is_iterable($value))
return $this->mapArray($value, $recursive);
return $this->_getMapValueHandler()(NULL, $value);
} | Maps parameters and service instances in value by the registered ones.
If value is an iterable, the mapping will iterate over it (if $recursive is set, also over children), otherwise it will map the passed value if needed.
@param $value
@param bool $recursive
@return array|iterable|mixed | https://github.com/tasoftch/php-service-manager/blob/5f627d81457356f6c087398cd1e8f8e4f9d14822/src/ServiceManager.php#L393-L397 |
tasoftch/php-service-manager | src/ServiceManager.php | ServiceManager._getMapValueHandler | private function _getMapValueHandler() {
return function($key, $value) {
foreach($this->customArgumentHandler as $name => $callable) {
if(is_callable($callable)) {
$value = $callable($key, $value);
} else
trigger_error("Custom argument handler $name is not callable", E_USER_WARNING);
}
return $value;
};
} | php | private function _getMapValueHandler() {
return function($key, $value) {
foreach($this->customArgumentHandler as $name => $callable) {
if(is_callable($callable)) {
$value = $callable($key, $value);
} else
trigger_error("Custom argument handler $name is not callable", E_USER_WARNING);
}
return $value;
};
} | Creates the replacement handler for parameters and service instances
@return \Closure | https://github.com/tasoftch/php-service-manager/blob/5f627d81457356f6c087398cd1e8f8e4f9d14822/src/ServiceManager.php#L403-L413 |
tasoftch/php-service-manager | src/ServiceManager.php | ServiceManager.makeServiceInstance | public function makeServiceInstance(string $className, $arguments = NULL, $configuration = NULL) {
$instance = NULL;
$implInterfaces = class_implements($className);
if(in_array(ConstructorAwareServiceInterface::class, $implInterfaces)) {
/** @var ConstructorAwareServiceInterface $className */
if($args = $className::getConstructorArguments()) {
$newArguments = [];
foreach($args as $argName => $argValue) {
$newArguments[] = is_null($argValue) ? ($arguments[$argName] ?? NULL) : $argValue;
}
$arguments = $newArguments;
}
}
if($arguments)
$arguments = $this->mapArray( AbstractCollection::makeArray($arguments), true);
if(in_array(StaticConstructorServiceInterface::class, $implInterfaces)) {
$instance = new $className($arguments, $this);
} elseif (in_array(DynamicConstructorServiceInterface::class, $implInterfaces)) {
$sig = SignatureService::getSignatureService()->getMethodSignature($className, "__construct");
$args = [];
foreach($sig as $name => $type) {
}
$instance = new $className(...$args);
} else {
$instance = $arguments ? new $className(...array_values($arguments)) : new $className();
}
if($configuration && method_exists($instance, 'setConfiguration')) {
$configuration = $this->mapArray( $configuration );
$instance->setConfiguration($configuration);
}
return $instance;
} | php | public function makeServiceInstance(string $className, $arguments = NULL, $configuration = NULL) {
$instance = NULL;
$implInterfaces = class_implements($className);
if(in_array(ConstructorAwareServiceInterface::class, $implInterfaces)) {
/** @var ConstructorAwareServiceInterface $className */
if($args = $className::getConstructorArguments()) {
$newArguments = [];
foreach($args as $argName => $argValue) {
$newArguments[] = is_null($argValue) ? ($arguments[$argName] ?? NULL) : $argValue;
}
$arguments = $newArguments;
}
}
if($arguments)
$arguments = $this->mapArray( AbstractCollection::makeArray($arguments), true);
if(in_array(StaticConstructorServiceInterface::class, $implInterfaces)) {
$instance = new $className($arguments, $this);
} elseif (in_array(DynamicConstructorServiceInterface::class, $implInterfaces)) {
$sig = SignatureService::getSignatureService()->getMethodSignature($className, "__construct");
$args = [];
foreach($sig as $name => $type) {
}
$instance = new $className(...$args);
} else {
$instance = $arguments ? new $className(...array_values($arguments)) : new $className();
}
if($configuration && method_exists($instance, 'setConfiguration')) {
$configuration = $this->mapArray( $configuration );
$instance->setConfiguration($configuration);
}
return $instance;
} | This method should be used to create service instances. It will check implementations and create it the requested manner.
@param string $className
@param array|iterable|null $arguments
@param array|iterable|null $configuration
@return object|null | https://github.com/tasoftch/php-service-manager/blob/5f627d81457356f6c087398cd1e8f8e4f9d14822/src/ServiceManager.php#L423-L462 |
tasoftch/php-service-manager | src/ServiceManager.php | ServiceManager.getServiceClass | public function getServiceClass(string $serviceName, bool $forced = true): ?string {
if(!isset($this->serviceClassNames[$serviceName])) {
if($this->serviceExists($serviceName)) {
/** @var ContainerInterface $container */
$container = $this->serviceData[$serviceName];
if($container->isInstanceLoaded()) {
$this->serviceClassNames[$serviceName] = get_class( $container->getInstance() );
goto finish;
}
if($container instanceof ServiceAwareContainerInterface) {
$this->serviceClassNames[$serviceName] = $container->getServiceClass();
goto finish;
} elseif($container instanceof ConfiguredServiceContainer) {
$cfg = $container->getConfiguration();
// In case of a direct instance fonciguration, get this classname
if($cn = $cfg[AbstractFileConfiguration::SERVICE_CLASS] ?? NULL) {
$this->serviceClassNames[$serviceName] = $cn;
goto finish;
} elseif($cn = $cfg[AbstractFileConfiguration::CONFIG_SERVICE_TYPE_KEY] ?? NULL) {
// If the developer defined the class by configuration in case of container or file initialisation, use this.
$this->serviceClassNames[$serviceName] = $cn;
goto finish;
}
}
// If nothing worked before, finally load the instance
if($forced)
$this->serviceClassNames[$serviceName] = get_class( $container->getInstance() );
} else {
// Mark as not existing
$this->serviceClassNames[$serviceName] = false;
}
}
finish:
return $this->serviceClassNames[$serviceName] ?: NULL;
} | php | public function getServiceClass(string $serviceName, bool $forced = true): ?string {
if(!isset($this->serviceClassNames[$serviceName])) {
if($this->serviceExists($serviceName)) {
/** @var ContainerInterface $container */
$container = $this->serviceData[$serviceName];
if($container->isInstanceLoaded()) {
$this->serviceClassNames[$serviceName] = get_class( $container->getInstance() );
goto finish;
}
if($container instanceof ServiceAwareContainerInterface) {
$this->serviceClassNames[$serviceName] = $container->getServiceClass();
goto finish;
} elseif($container instanceof ConfiguredServiceContainer) {
$cfg = $container->getConfiguration();
// In case of a direct instance fonciguration, get this classname
if($cn = $cfg[AbstractFileConfiguration::SERVICE_CLASS] ?? NULL) {
$this->serviceClassNames[$serviceName] = $cn;
goto finish;
} elseif($cn = $cfg[AbstractFileConfiguration::CONFIG_SERVICE_TYPE_KEY] ?? NULL) {
// If the developer defined the class by configuration in case of container or file initialisation, use this.
$this->serviceClassNames[$serviceName] = $cn;
goto finish;
}
}
// If nothing worked before, finally load the instance
if($forced)
$this->serviceClassNames[$serviceName] = get_class( $container->getInstance() );
} else {
// Mark as not existing
$this->serviceClassNames[$serviceName] = false;
}
}
finish:
return $this->serviceClassNames[$serviceName] ?: NULL;
} | Gets the class of a service instance
@param string $serviceName
@param bool $forced // If set, it will until load the service to get its class name
@return string|null | https://github.com/tasoftch/php-service-manager/blob/5f627d81457356f6c087398cd1e8f8e4f9d14822/src/ServiceManager.php#L487-L526 |
tasoftch/php-service-manager | src/ServiceManager.php | ServiceManager.yieldServices | public function yieldServices(array $serviceNames, array $classNames, bool $includeSubclasses = true, bool $forceClassDetection = true) {
$matchClass = function($className) use ($includeSubclasses, $classNames) {
if(in_array($className, $classNames))
return true;
if($includeSubclasses) {
foreach($classNames as $cn) {
if(is_subclass_of($className, $cn))
return true;
}
}
return false;
};
/**
* @var string $serviceName
* @var ContainerInterface $container
*/
foreach($this->serviceData as $serviceName => $container) {
if(in_array($serviceName, $serviceNames) || $matchClass($this->getServiceClass($serviceName, $forceClassDetection))) {
yield $serviceName => new ServicePromise(function() use($container) {return $container->getInstance();});
}
}
} | php | public function yieldServices(array $serviceNames, array $classNames, bool $includeSubclasses = true, bool $forceClassDetection = true) {
$matchClass = function($className) use ($includeSubclasses, $classNames) {
if(in_array($className, $classNames))
return true;
if($includeSubclasses) {
foreach($classNames as $cn) {
if(is_subclass_of($className, $cn))
return true;
}
}
return false;
};
/**
* @var string $serviceName
* @var ContainerInterface $container
*/
foreach($this->serviceData as $serviceName => $container) {
if(in_array($serviceName, $serviceNames) || $matchClass($this->getServiceClass($serviceName, $forceClassDetection))) {
yield $serviceName => new ServicePromise(function() use($container) {return $container->getInstance();});
}
}
} | Yields all services that match required service names or required class names.
@param array $serviceNames
@param array $classNames
@param bool $includeSubclasses
@param bool $forceClassDetection
@return \Generator | https://github.com/tasoftch/php-service-manager/blob/5f627d81457356f6c087398cd1e8f8e4f9d14822/src/ServiceManager.php#L538-L561 |
UnionOfRAD/li3_quality | extensions/command/Syntax.php | Syntax.run | public function run($path = null /* , ... */) {
$this->header('Syntax Check');
$rules = $this->_rules();
$subjects = array();
$success = true;
foreach (func_get_args() ?: array(getcwd()) as $path) {
$subjects = array_merge($subjects, $this->_subjects($path));
}
$this->out(sprintf(
'Performing %d rules on path `%s`...',
count($rules),
$path
));
foreach ($subjects as $path) {
$testable = new Testable(array('path' => $path->getPathname()));
try {
$result = $rules->apply($testable);
} catch (ParserException $e) {
$this->error("[FAIL] $path", "red");
$this->error("Parse error: " . $e->getMessage(), "red");
if ($this->verbose) {
$this->error(print_r($e->parserData, true), "red");
}
$success = false;
continue;
}
if ($result['success']) {
if ($this->verbose) {
$this->out("[OK ] $path", "green");
}
} else {
$this->error("[FAIL] $path", "red");
$output = array(
array("Line", "Position", "Violation"),
array("----", "--------", "---------")
);
foreach ($result['violations'] as $violation) {
$params = $violation;
$output[] = array(
$params['line'],
$params['position'],
$params['message']
);
}
$this->columns($output, array(
'style' => 'red', 'error' => true
));
$success = false;
}
if (count($result['warnings']) > 0) {
$output = array(
array("Line", "Position", "Warning"),
array("----", "--------", "-------")
);
foreach ($result['warnings'] as $warning) {
$params = $warning;
$output[] = array(
$params['line'],
$params['position'],
$params['message']
);
}
$this->columns($output, array(
'style' => 'yellow', 'error' => false
));
}
}
return $success;
} | php | public function run($path = null /* , ... */) {
$this->header('Syntax Check');
$rules = $this->_rules();
$subjects = array();
$success = true;
foreach (func_get_args() ?: array(getcwd()) as $path) {
$subjects = array_merge($subjects, $this->_subjects($path));
}
$this->out(sprintf(
'Performing %d rules on path `%s`...',
count($rules),
$path
));
foreach ($subjects as $path) {
$testable = new Testable(array('path' => $path->getPathname()));
try {
$result = $rules->apply($testable);
} catch (ParserException $e) {
$this->error("[FAIL] $path", "red");
$this->error("Parse error: " . $e->getMessage(), "red");
if ($this->verbose) {
$this->error(print_r($e->parserData, true), "red");
}
$success = false;
continue;
}
if ($result['success']) {
if ($this->verbose) {
$this->out("[OK ] $path", "green");
}
} else {
$this->error("[FAIL] $path", "red");
$output = array(
array("Line", "Position", "Violation"),
array("----", "--------", "---------")
);
foreach ($result['violations'] as $violation) {
$params = $violation;
$output[] = array(
$params['line'],
$params['position'],
$params['message']
);
}
$this->columns($output, array(
'style' => 'red', 'error' => true
));
$success = false;
}
if (count($result['warnings']) > 0) {
$output = array(
array("Line", "Position", "Warning"),
array("----", "--------", "-------")
);
foreach ($result['warnings'] as $warning) {
$params = $warning;
$output[] = array(
$params['line'],
$params['position'],
$params['message']
);
}
$this->columns($output, array(
'style' => 'yellow', 'error' => false
));
}
}
return $success;
} | Runs the syntax checker on given path/s.
@param string $path Absolute or relative path to a directory
to search recursively for files to check. By default will not descend
into known library directories (i.e. `libraries`, `vendors`). If ommitted
will use current working directory. Also works on single files.
@return boolean Will (indirectly) exit with status `1` if one or more rules
failed otherwise with `0`. | https://github.com/UnionOfRAD/li3_quality/blob/acb72a43ae835e6d200bc0eba1a61aee610e36bf/extensions/command/Syntax.php#L67-L142 |
UnionOfRAD/li3_quality | extensions/command/Syntax.php | Syntax._subjects | protected function _subjects($path) {
if (is_file($path)) {
$current = new SplFileInfo($path);
return $current->getExtension() === 'php' ? array($current) : array();
}
$files = new RecursiveCallbackFilterIterator(
new RecursiveDirectoryIterator($path),
function($current, $key, $iterator) {
$noDescend = array(
'.git',
'libraries',
'vendor'
);
if ($iterator->hasChildren()) {
if ($current->isDir() && in_array($current->getBasename(), $noDescend)) {
return false;
}
return true;
}
if ($current->isFile()) {
return $current->getExtension() === 'php';
}
return false;
}
);
return iterator_to_array(new RecursiveIteratorIterator($files));
} | php | protected function _subjects($path) {
if (is_file($path)) {
$current = new SplFileInfo($path);
return $current->getExtension() === 'php' ? array($current) : array();
}
$files = new RecursiveCallbackFilterIterator(
new RecursiveDirectoryIterator($path),
function($current, $key, $iterator) {
$noDescend = array(
'.git',
'libraries',
'vendor'
);
if ($iterator->hasChildren()) {
if ($current->isDir() && in_array($current->getBasename(), $noDescend)) {
return false;
}
return true;
}
if ($current->isFile()) {
return $current->getExtension() === 'php';
}
return false;
}
);
return iterator_to_array(new RecursiveIteratorIterator($files));
} | Retrieves subjects. Will return only PHP files.
@param string $path
@return array Returns an array of SplFieldInfo objects. | https://github.com/UnionOfRAD/li3_quality/blob/acb72a43ae835e6d200bc0eba1a61aee610e36bf/extensions/command/Syntax.php#L150-L176 |
UnionOfRAD/li3_quality | extensions/command/Syntax.php | Syntax._rules | protected function _rules() {
$rules = new Rules();
$files = array(
$this->config,
Libraries::get('li3_quality', 'path') . '/config/syntax.json'
);
foreach ($files as $file) {
if (file_exists($file)) {
$this->out("Loading configuration file `{$file}`...");
$config = json_decode(file_get_contents($file), true) + array(
'name' => null,
'rules' => array(),
'options' => array()
);
break;
}
}
foreach ($config['rules'] as $ruleName) {
$class = Libraries::locate('rules.syntax', $ruleName);
$rules->add(new $class());
}
if ($config['options']) {
$rules->options($config['options']);
}
return $rules;
} | php | protected function _rules() {
$rules = new Rules();
$files = array(
$this->config,
Libraries::get('li3_quality', 'path') . '/config/syntax.json'
);
foreach ($files as $file) {
if (file_exists($file)) {
$this->out("Loading configuration file `{$file}`...");
$config = json_decode(file_get_contents($file), true) + array(
'name' => null,
'rules' => array(),
'options' => array()
);
break;
}
}
foreach ($config['rules'] as $ruleName) {
$class = Libraries::locate('rules.syntax', $ruleName);
$rules->add(new $class());
}
if ($config['options']) {
$rules->options($config['options']);
}
return $rules;
} | Loads rules configuration.
@return object | https://github.com/UnionOfRAD/li3_quality/blob/acb72a43ae835e6d200bc0eba1a61aee610e36bf/extensions/command/Syntax.php#L183-L210 |
igorwanbarros/autenticacao-laravel | src/Migrations/2016_12_28_164912_autenticacao_create_dashboard_table.php | AutenticacaoCreateDashboardTable.up | public function up()
{
Schema::create('autenticacao_dashboard', function (Blueprint $tb) {
$tb->increments('id');
$tb->string('titulo');
$tb->enum('tamanho', ['GRANDE', 'MEDIO', 'PEQUENO'])->default('MEDIO');
$tb->string('dashboard_name');
$tb->integer('user_id', false, true);
$tb->foreign('user_id')->references('id')->on('autenticacao_users');
$tb->timestamps();
$tb->softDeletes();
});
} | php | public function up()
{
Schema::create('autenticacao_dashboard', function (Blueprint $tb) {
$tb->increments('id');
$tb->string('titulo');
$tb->enum('tamanho', ['GRANDE', 'MEDIO', 'PEQUENO'])->default('MEDIO');
$tb->string('dashboard_name');
$tb->integer('user_id', false, true);
$tb->foreign('user_id')->references('id')->on('autenticacao_users');
$tb->timestamps();
$tb->softDeletes();
});
} | Run the migrations.
@return void | https://github.com/igorwanbarros/autenticacao-laravel/blob/e7e8217dae433934fe46c34516fb2f6f5f932fc1/src/Migrations/2016_12_28_164912_autenticacao_create_dashboard_table.php#L13-L25 |
sulu/SuluSalesOrderBundle | Order/OrderDependencyManager.php | OrderDependencyManager.getWorkflows | public function getWorkflows($order)
{
$workflows = array();
$actions = array(
'confirm' => array(
'section' => $this->getName(),
'title' => 'salesorder.orders.confirm',
'event' => 'sulu.salesorder.order.confirm.clicked'
),
'edit' => array(
'section' => $this->getName(),
'title' => 'salesorder.orders.edit',
'event' => 'sulu.salesorder.order.edit.clicked'
),
'delete' => array(
'section' => $this->getName(),
'title' => 'salesorder.orders.delete',
'event' => 'sulu.salesorder.order.delete',
'parameters'=> array('id'=> $order->getId())
),
);
// define workflows by order's status
$orderStatusId = $order->getStatus()->getId();
// order is in created state
if ($orderStatusId === OrderStatus::STATUS_CREATED) {
$workflows[] = $actions['confirm'];
}
// order is confirmed
else if ($orderStatusId === OrderStatus::STATUS_CONFIRMED) {
$workflows[] = $actions['edit'];
}
// order is allowed to be deleted
if ($this->allowDelete($order)) {
$workflows[] = $actions['delete'];
}
// get workflows from dependencies
/** @var SalesDependencyClassInterface $dependency */
foreach ($this->dependencyClasses as $dependency) {
$workflows = array_merge($workflows, $dependency->getWorkflows($order));
}
return $workflows;
} | php | public function getWorkflows($order)
{
$workflows = array();
$actions = array(
'confirm' => array(
'section' => $this->getName(),
'title' => 'salesorder.orders.confirm',
'event' => 'sulu.salesorder.order.confirm.clicked'
),
'edit' => array(
'section' => $this->getName(),
'title' => 'salesorder.orders.edit',
'event' => 'sulu.salesorder.order.edit.clicked'
),
'delete' => array(
'section' => $this->getName(),
'title' => 'salesorder.orders.delete',
'event' => 'sulu.salesorder.order.delete',
'parameters'=> array('id'=> $order->getId())
),
);
// define workflows by order's status
$orderStatusId = $order->getStatus()->getId();
// order is in created state
if ($orderStatusId === OrderStatus::STATUS_CREATED) {
$workflows[] = $actions['confirm'];
}
// order is confirmed
else if ($orderStatusId === OrderStatus::STATUS_CONFIRMED) {
$workflows[] = $actions['edit'];
}
// order is allowed to be deleted
if ($this->allowDelete($order)) {
$workflows[] = $actions['delete'];
}
// get workflows from dependencies
/** @var SalesDependencyClassInterface $dependency */
foreach ($this->dependencyClasses as $dependency) {
$workflows = array_merge($workflows, $dependency->getWorkflows($order));
}
return $workflows;
} | returns all possible workflows for the current entity
@param Order $order
@return array | https://github.com/sulu/SuluSalesOrderBundle/blob/1de6d43e8e6d0cc1e703b687085445f50f97ecdc/Order/OrderDependencyManager.php#L95-L139 |
ben-gibson/foursquare-venue-client | src/Factory/Venue/DetailFactory.php | DetailFactory.create | public function create(Description $description)
{
$timeZone = $description->getOptionalProperty('timeZone');
$likesDescription = $description->getOptionalProperty('likes');
$hereNowDescription = $description->getOptionalProperty('hereNow');
return new Detail(
$description->getMandatoryProperty('verified'),
$this->getCreatedAt($description),
$this->getBestPhoto($description),
$description->getOptionalProperty('rating'),
$description->getOptionalProperty('url'),
($hereNowDescription instanceof Description) ? $hereNowDescription->getMandatoryProperty('count') : null,
$description->getOptionalProperty('tags', []),
($likesDescription instanceof Description) ? $likesDescription->getMandatoryProperty('count'): null,
($timeZone !== null) ? new \DateTimeZone($timeZone) : null
);
} | php | public function create(Description $description)
{
$timeZone = $description->getOptionalProperty('timeZone');
$likesDescription = $description->getOptionalProperty('likes');
$hereNowDescription = $description->getOptionalProperty('hereNow');
return new Detail(
$description->getMandatoryProperty('verified'),
$this->getCreatedAt($description),
$this->getBestPhoto($description),
$description->getOptionalProperty('rating'),
$description->getOptionalProperty('url'),
($hereNowDescription instanceof Description) ? $hereNowDescription->getMandatoryProperty('count') : null,
$description->getOptionalProperty('tags', []),
($likesDescription instanceof Description) ? $likesDescription->getMandatoryProperty('count'): null,
($timeZone !== null) ? new \DateTimeZone($timeZone) : null
);
} | Create a venue from a description.
@param Description $description The venue details description.
@return Detail | https://github.com/ben-gibson/foursquare-venue-client/blob/ce5e7c308f87d5ccc28ab8d27a9cb51bd106d969/src/Factory/Venue/DetailFactory.php#L34-L51 |
ben-gibson/foursquare-venue-client | src/Factory/Venue/DetailFactory.php | DetailFactory.getCreatedAt | private function getCreatedAt(Description $description)
{
$createdAt = $description->getOptionalProperty('createdAt');
return ($createdAt !== null) ? (new \DateTimeImmutable())->setTimestamp($createdAt) : null;
} | php | private function getCreatedAt(Description $description)
{
$createdAt = $description->getOptionalProperty('createdAt');
return ($createdAt !== null) ? (new \DateTimeImmutable())->setTimestamp($createdAt) : null;
} | Get created at.
@param Description $description The venue details description.
@return \DateTimeImmutable|null | https://github.com/ben-gibson/foursquare-venue-client/blob/ce5e7c308f87d5ccc28ab8d27a9cb51bd106d969/src/Factory/Venue/DetailFactory.php#L60-L65 |
ben-gibson/foursquare-venue-client | src/Factory/Venue/DetailFactory.php | DetailFactory.getBestPhoto | private function getBestPhoto(Description $description)
{
$bestPhotoDescription = $description->getOptionalProperty('bestPhoto');
if ($bestPhotoDescription instanceof Description) {
return $this->photoFactory->create($bestPhotoDescription);
}
return null;
} | php | private function getBestPhoto(Description $description)
{
$bestPhotoDescription = $description->getOptionalProperty('bestPhoto');
if ($bestPhotoDescription instanceof Description) {
return $this->photoFactory->create($bestPhotoDescription);
}
return null;
} | Get best photo.
@param Description $description The venue details description.
@return Photo|null | https://github.com/ben-gibson/foursquare-venue-client/blob/ce5e7c308f87d5ccc28ab8d27a9cb51bd106d969/src/Factory/Venue/DetailFactory.php#L74-L83 |
fxpio/fxp-doctrine-console | Command/Delete.php | Delete.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$id = $input->getArgument($this->adapter->getIdentifierArgument());
$instance = $this->adapter->get($id);
$this->validateInstance($instance);
$this->adapter->delete($instance);
$this->showMessage($output, $instance, 'The %s <info>%s</info> was deleted with successfully');
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$id = $input->getArgument($this->adapter->getIdentifierArgument());
$instance = $this->adapter->get($id);
$this->validateInstance($instance);
$this->adapter->delete($instance);
$this->showMessage($output, $instance, 'The %s <info>%s</info> was deleted with successfully');
} | {@inheritdoc} | https://github.com/fxpio/fxp-doctrine-console/blob/2fc16d7a4eb0f247075c50de225ec2670ca5479a/Command/Delete.php#L30-L39 |
temp/media-converter | src/Converter/AudioConverter.php | AudioConverter.createFormat | private function createFormat($audioFormat)
{
switch ($audioFormat) {
case 'aac':
$format = new Aac();
break;
case 'flac':
$format = new Flac();
break;
case 'vorbis':
$format = new Vorbis();
break;
case 'mp3':
default:
$format = new Mp3();
break;
}
return $format;
} | php | private function createFormat($audioFormat)
{
switch ($audioFormat) {
case 'aac':
$format = new Aac();
break;
case 'flac':
$format = new Flac();
break;
case 'vorbis':
$format = new Vorbis();
break;
case 'mp3':
default:
$format = new Mp3();
break;
}
return $format;
} | @param string $audioFormat
@return DefaultAudio | https://github.com/temp/media-converter/blob/a6e8768c583aa461be568f13e592ae49294e5e33/src/Converter/AudioConverter.php#L55-L77 |
temp/media-converter | src/Converter/AudioConverter.php | AudioConverter.convert | public function convert($inFilename, Specification $spec, $outFilename)
{
$audio = $this->ffmpeg->open($inFilename);
$format = $this->createFormat($spec->getAudioFormat());
if ($spec->getAudioCodec()) {
$format->setAudioCodec($spec->getAudioCodec());
}
if ($spec->getAudioBitrate()) {
$format->setAudioKiloBitrate($spec->getAudioBitrate());
}
if ($spec->getAudioSamplerate()) {
$audio->addFilter(new AudioResamplableFilter($spec->getAudioSamplerate()));
}
if ($spec->getAudioChannels()) {
$format->setAudioChannels($spec->getAudioChannels());
}
$audio->save($format, $outFilename);
} | php | public function convert($inFilename, Specification $spec, $outFilename)
{
$audio = $this->ffmpeg->open($inFilename);
$format = $this->createFormat($spec->getAudioFormat());
if ($spec->getAudioCodec()) {
$format->setAudioCodec($spec->getAudioCodec());
}
if ($spec->getAudioBitrate()) {
$format->setAudioKiloBitrate($spec->getAudioBitrate());
}
if ($spec->getAudioSamplerate()) {
$audio->addFilter(new AudioResamplableFilter($spec->getAudioSamplerate()));
}
if ($spec->getAudioChannels()) {
$format->setAudioChannels($spec->getAudioChannels());
}
$audio->save($format, $outFilename);
} | @param string $inFilename
@param Audio $spec
@param string $outFilename
@return string | https://github.com/temp/media-converter/blob/a6e8768c583aa461be568f13e592ae49294e5e33/src/Converter/AudioConverter.php#L86-L109 |
Phpillip/phpillip | src/PropertyHandler/LastModifiedPropertyHandler.php | LastModifiedPropertyHandler.handle | public function handle($value, array $context)
{
$lastModified = new DateTime();
$lastModified->setTimestamp($context['file']->getMTime());
return $lastModified;
} | php | public function handle($value, array $context)
{
$lastModified = new DateTime();
$lastModified->setTimestamp($context['file']->getMTime());
return $lastModified;
} | {@inheritdoc} | https://github.com/Phpillip/phpillip/blob/c37afaafb536361e7e0b564659f1cd5b80b98be9/src/PropertyHandler/LastModifiedPropertyHandler.php#L32-L38 |
composer-synchronizer/composer-synchronizer | src/Synchronizers/CakePhp3/CakePhp3Synchronizer.php | CakePhp3Synchronizer.synchronizeConfigs | protected function synchronizeConfigs(array $configFiles): void
{
foreach($configFiles as $variableName => $path) {
$rowToAdd = $this->createRow($path);
Helpers::appendToFile($this->configurationFile, $rowToAdd);
}
} | php | protected function synchronizeConfigs(array $configFiles): void
{
foreach($configFiles as $variableName => $path) {
$rowToAdd = $this->createRow($path);
Helpers::appendToFile($this->configurationFile, $rowToAdd);
}
} | ************************* Synchronization methods ************************** | https://github.com/composer-synchronizer/composer-synchronizer/blob/ca1c2f4dd05e0142148c030dba63b5081edb2bc3/src/Synchronizers/CakePhp3/CakePhp3Synchronizer.php#L103-L109 |
Synapse-Cmf/synapse-cmf | src/Synapse/Page/Bundle/Form/PageMenu/PageMenuItemType.php | PageMenuItemType.initChoices | protected function initChoices($loader)
{
$this->choices = $loader->retrieveAll(array('online' => true))->reduce(function ($r, Page $page) {
$r[$page->getName()] = $page->getId();
return $r;
}, array());
return $this;
} | php | protected function initChoices($loader)
{
$this->choices = $loader->retrieveAll(array('online' => true))->reduce(function ($r, Page $page) {
$r[$page->getName()] = $page->getId();
return $r;
}, array());
return $this;
} | @param $loader
@return $this | https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Page/Bundle/Form/PageMenu/PageMenuItemType.php#L79-L88 |
Clevis/Se34 | Se34/ElementComponent.php | ElementComponent.getRoot | private function getRoot()
{
if ($this->root === NULL)
{
$selector = reset($this->parameters);
$strategy = key($this->parameters);
if ($selector instanceof Element)
{
$this->root = $selector;
}
else
{
$this->root = $this->parent->findElement($strategy, $selector);
}
$expectedTagName = next($this->parameters);
$expectedAttributes = next($this->parameters);
if ($expectedTagName !== FALSE)
{
$actualTagName = $this->root->name();
if ($actualTagName !== $expectedTagName)
{
throw new ViewStateException("Root element of '" . get_class($this) . "' is expected to be tag '$expectedTagName', but is '$actualTagName'.");
}
}
if ($expectedAttributes !== FALSE)
{
foreach ($expectedAttributes as $attributeName => $expectedAttributeValue)
{
$actualAttributeValue = $this->root->attribute($attributeName);
if ($actualAttributeValue !== $expectedAttributeValue)
{
throw new ViewStateException("Root element's attribute '$attributeName' is expected to be '$expectedAttributeValue', but is '$actualAttributeValue'.");
}
}
}
}
return $this->root;
} | php | private function getRoot()
{
if ($this->root === NULL)
{
$selector = reset($this->parameters);
$strategy = key($this->parameters);
if ($selector instanceof Element)
{
$this->root = $selector;
}
else
{
$this->root = $this->parent->findElement($strategy, $selector);
}
$expectedTagName = next($this->parameters);
$expectedAttributes = next($this->parameters);
if ($expectedTagName !== FALSE)
{
$actualTagName = $this->root->name();
if ($actualTagName !== $expectedTagName)
{
throw new ViewStateException("Root element of '" . get_class($this) . "' is expected to be tag '$expectedTagName', but is '$actualTagName'.");
}
}
if ($expectedAttributes !== FALSE)
{
foreach ($expectedAttributes as $attributeName => $expectedAttributeValue)
{
$actualAttributeValue = $this->root->attribute($attributeName);
if ($actualAttributeValue !== $expectedAttributeValue)
{
throw new ViewStateException("Root element's attribute '$attributeName' is expected to be '$expectedAttributeValue', but is '$actualAttributeValue'.");
}
}
}
}
return $this->root;
} | Get root element of this component.
@return Element | https://github.com/Clevis/Se34/blob/c52d579a831ba5642dae464882da012b0409ae46/Se34/ElementComponent.php#L15-L52 |
Clevis/Se34 | Se34/ElementComponent.php | ElementComponent.findElement | public function findElement($strategy, $selector)
{
$this->modifyCriteria($strategy, $selector);
return $this->getRoot()->findElement($strategy, $selector);
} | php | public function findElement($strategy, $selector)
{
$this->modifyCriteria($strategy, $selector);
return $this->getRoot()->findElement($strategy, $selector);
} | Find the first element that matches the criteria and return it. Or throw
an exception.
@param string $strategy
@param string $selector
@return Element | https://github.com/Clevis/Se34/blob/c52d579a831ba5642dae464882da012b0409ae46/Se34/ElementComponent.php#L72-L76 |
Clevis/Se34 | Se34/ElementComponent.php | ElementComponent.findElements | public function findElements($strategy, $selector)
{
$this->modifyCriteria($strategy, $selector);
return $this->getRoot()->findElements($strategy, $selector);
} | php | public function findElements($strategy, $selector)
{
$this->modifyCriteria($strategy, $selector);
return $this->getRoot()->findElements($strategy, $selector);
} | Find all elements that match given criteria. If none found, than return
an empty array.
@param string $strategy
@param string $selector
@return Element[] | https://github.com/Clevis/Se34/blob/c52d579a831ba5642dae464882da012b0409ae46/Se34/ElementComponent.php#L86-L90 |
ScreamingDev/phpsemver | lib/PHPSemVer/Config/RuleSet/Trigger.php | Trigger.getInstances | public function getInstances()
{
if (null === $this->instances) {
$this->instances = [];
foreach ($this->getAll() as $className) {
$className = '\\PHPSemVer\\Trigger\\' . str_replace('/', '\\', $className);
$this->instances[] = new $className();
}
}
return $this->instances;
} | php | public function getInstances()
{
if (null === $this->instances) {
$this->instances = [];
foreach ($this->getAll() as $className) {
$className = '\\PHPSemVer\\Trigger\\' . str_replace('/', '\\', $className);
$this->instances[] = new $className();
}
}
return $this->instances;
} | Get all trigger instances from the config.
@return AbstractTrigger[] | https://github.com/ScreamingDev/phpsemver/blob/11a4bc508f71dee73d4f5fee2e9d39e7984d3e15/lib/PHPSemVer/Config/RuleSet/Trigger.php#L44-L57 |
ekyna/AdminBundle | Controller/SecurityController.php | SecurityController.loginAction | public function loginAction(Request $request)
{
/** @var $session \Symfony\Component\HttpFoundation\Session\Session */
$session = $request->getSession();
$authErrorKey = Security::AUTHENTICATION_ERROR;
$lastUsernameKey = Security::LAST_USERNAME;
// get the error if any (works with forward and redirect -- see below)
if ($request->attributes->has($authErrorKey)) {
$error = $request->attributes->get($authErrorKey);
} elseif (null !== $session && $session->has($authErrorKey)) {
$error = $session->get($authErrorKey);
$session->remove($authErrorKey);
} else {
$error = null;
}
if (!$error instanceof AuthenticationException) {
$error = null; // The value does not come from the security component.
}
// last username entered by the user
$lastUsername = (null === $session) ? '' : $session->get($lastUsernameKey);
$csrfToken = $this->get('security.csrf.token_manager')->getToken('authenticate')->getValue();
return $this->render('EkynaAdminBundle:Security:login.html.twig', [
'last_username' => $lastUsername,
'error' => $error,
'token' => $csrfToken,
]);
} | php | public function loginAction(Request $request)
{
/** @var $session \Symfony\Component\HttpFoundation\Session\Session */
$session = $request->getSession();
$authErrorKey = Security::AUTHENTICATION_ERROR;
$lastUsernameKey = Security::LAST_USERNAME;
// get the error if any (works with forward and redirect -- see below)
if ($request->attributes->has($authErrorKey)) {
$error = $request->attributes->get($authErrorKey);
} elseif (null !== $session && $session->has($authErrorKey)) {
$error = $session->get($authErrorKey);
$session->remove($authErrorKey);
} else {
$error = null;
}
if (!$error instanceof AuthenticationException) {
$error = null; // The value does not come from the security component.
}
// last username entered by the user
$lastUsername = (null === $session) ? '' : $session->get($lastUsernameKey);
$csrfToken = $this->get('security.csrf.token_manager')->getToken('authenticate')->getValue();
return $this->render('EkynaAdminBundle:Security:login.html.twig', [
'last_username' => $lastUsername,
'error' => $error,
'token' => $csrfToken,
]);
} | Login action.
@param Request $request
@return \Symfony\Component\HttpFoundation\Response | https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Controller/SecurityController.php#L23-L54 |
DBRisinajumi/d2company | controllers/CcmpCompanyController.php | CcmpCompanyController.actionView4CustomerOffice | public function actionView4CustomerOffice() {
$pprs_id = Yii::app()->getModule('user')->user()->profile->person_id;
$customer_companies = CcucUserCompany::model()->getPersonCompnies($pprs_id, CcucUserCompany::CCUC_STATUS_PERSON);
if(empty($customer_companies)){
throw new CHttpException(404, Yii::t('D2companyModule.crud_static', 'The requested page does not exist.'));
}
$model = $this->loadModel($customer_companies[0]->ccuc_ccmp_id);
$this->layout='//layouts/main';
$this->render('view4CustomerOffice', array('model' => $model,));
} | php | public function actionView4CustomerOffice() {
$pprs_id = Yii::app()->getModule('user')->user()->profile->person_id;
$customer_companies = CcucUserCompany::model()->getPersonCompnies($pprs_id, CcucUserCompany::CCUC_STATUS_PERSON);
if(empty($customer_companies)){
throw new CHttpException(404, Yii::t('D2companyModule.crud_static', 'The requested page does not exist.'));
}
$model = $this->loadModel($customer_companies[0]->ccuc_ccmp_id);
$this->layout='//layouts/main';
$this->render('view4CustomerOffice', array('model' => $model,));
} | customer office | https://github.com/DBRisinajumi/d2company/blob/20df0db96ac2c8e73471c4bab7d487b67ef4ed0a/controllers/CcmpCompanyController.php#L99-L110 |
DBRisinajumi/d2company | controllers/CcmpCompanyController.php | CcmpCompanyController.actionResetPersonPassword | public function actionResetPersonPassword($ccmp_id,$person_id)
{
//only for validation acces
$model = $this->loadModel($ccmp_id);
yii::import('vendor.dbrisinajumi.person.PersonModule');
//if do not have user, create
$m = Person::model();
$m->resetPassword($person_id);
$this->redirect(array('adminCustomers', 'ccmp_id' => $ccmp_id));
} | php | public function actionResetPersonPassword($ccmp_id,$person_id)
{
//only for validation acces
$model = $this->loadModel($ccmp_id);
yii::import('vendor.dbrisinajumi.person.PersonModule');
//if do not have user, create
$m = Person::model();
$m->resetPassword($person_id);
$this->redirect(array('adminCustomers', 'ccmp_id' => $ccmp_id));
} | send to user new password
@return type | https://github.com/DBRisinajumi/d2company/blob/20df0db96ac2c8e73471c4bab7d487b67ef4ed0a/controllers/CcmpCompanyController.php#L759-L771 |
garyr/memento | lib/Memento/Client.php | Client.getKeys | private function getKeys($argv)
{
$groupKey = null;
$key = null;
if (isset($argv[0])) {
if ($argv[0] instanceof Group\Key) {
$groupKey = $argv[0];
if (isset($argv[1])) {
if ($argv[1] instanceof Key) {
$key = $argv[1];
} else {
throw new \InvalidArgumentException("must be instance of Memento_Key");
}
}
} elseif ($argv[0] instanceof Key) {
$key = $argv[0];
} else {
throw new \InvalidArgumentException("argument 1 must be instance of Memento_Group_Key or Memento_Key");
}
}
return array($key, $groupKey);
} | php | private function getKeys($argv)
{
$groupKey = null;
$key = null;
if (isset($argv[0])) {
if ($argv[0] instanceof Group\Key) {
$groupKey = $argv[0];
if (isset($argv[1])) {
if ($argv[1] instanceof Key) {
$key = $argv[1];
} else {
throw new \InvalidArgumentException("must be instance of Memento_Key");
}
}
} elseif ($argv[0] instanceof Key) {
$key = $argv[0];
} else {
throw new \InvalidArgumentException("argument 1 must be instance of Memento_Group_Key or Memento_Key");
}
}
return array($key, $groupKey);
} | Returns an array to serve as a callable param
for call_user_func_array
@param array $argv Function argument array
@param string $source Method name from which the call was made
@return arrray Returns the method target callable array | https://github.com/garyr/memento/blob/d6cfa9ffec040f96b8361f822f11dcf6d5ff60b4/lib/Memento/Client.php#L32-L56 |
garyr/memento | lib/Memento/Client.php | Client.expire | public function expire()
{
list($key, $groupKey) = $this->getKeys(func_get_args());
$this->engine->setGroupKey($groupKey);
if (!$this->engine->isValid($key)) {
return false;
}
return $this->engine->expire($key);
} | php | public function expire()
{
list($key, $groupKey) = $this->getKeys(func_get_args());
$this->engine->setGroupKey($groupKey);
if (!$this->engine->isValid($key)) {
return false;
}
return $this->engine->expire($key);
} | Wrapper method for expire() call.
@see Memento\Single\Agent::expire()
@see Memento\Group\Agent::expire()
@return boolean returns true if the command was successful | https://github.com/garyr/memento/blob/d6cfa9ffec040f96b8361f822f11dcf6d5ff60b4/lib/Memento/Client.php#L98-L108 |
garyr/memento | lib/Memento/Client.php | Client.getExpires | public function getExpires()
{
list($key, $groupKey) = $this->getKeys(func_get_args());
$this->engine->setGroupKey($groupKey);
if (!$this->engine->isValid($key, true)) {
return null;
}
return $this->engine->getExpires($key);
} | php | public function getExpires()
{
list($key, $groupKey) = $this->getKeys(func_get_args());
$this->engine->setGroupKey($groupKey);
if (!$this->engine->isValid($key, true)) {
return null;
}
return $this->engine->getExpires($key);
} | Wrapper method for getExpires() call.
@see Memento\Single\Agent::getExpires()
@see Memento\Group\Agent::getExpires()
@return mixed returns the time the object expires | https://github.com/garyr/memento/blob/d6cfa9ffec040f96b8361f822f11dcf6d5ff60b4/lib/Memento/Client.php#L118-L128 |
garyr/memento | lib/Memento/Client.php | Client.invalidate | public function invalidate()
{
list($key, $groupKey) = $this->getKeys(func_get_args());
$this->engine->setGroupKey($groupKey);
if (!$this->engine->isValid($key)) {
return true;
}
return $this->engine->invalidate($key);
} | php | public function invalidate()
{
list($key, $groupKey) = $this->getKeys(func_get_args());
$this->engine->setGroupKey($groupKey);
if (!$this->engine->isValid($key)) {
return true;
}
return $this->engine->invalidate($key);
} | Wrapper method for invalidate() call.
@see Memento\Single\Agent::invalidate()
@see Memento\Group\Agent::invalidate()
@return boolean returns true if the invalidation action succeeded | https://github.com/garyr/memento/blob/d6cfa9ffec040f96b8361f822f11dcf6d5ff60b4/lib/Memento/Client.php#L158-L169 |
garyr/memento | lib/Memento/Client.php | Client.keys | public function keys(Group\Key $groupKey)
{
$keys = $this->engine->keys($groupKey);
$hashClass = new \ReflectionClass('Memento\Hash');
$hashConstants = array_values($hashClass->getConstants());
$_keys = array();
foreach ($keys as $i => $key) {
// if key exists as a constant in Memento_Redis_Hash, discard
if (in_array($key, $hashConstants)) {
continue;
}
$_keys[] = $key;
}
return $_keys;
} | php | public function keys(Group\Key $groupKey)
{
$keys = $this->engine->keys($groupKey);
$hashClass = new \ReflectionClass('Memento\Hash');
$hashConstants = array_values($hashClass->getConstants());
$_keys = array();
foreach ($keys as $i => $key) {
// if key exists as a constant in Memento_Redis_Hash, discard
if (in_array($key, $hashConstants)) {
continue;
}
$_keys[] = $key;
}
return $_keys;
} | Wrapper method for exists() call.
@see Memento\Single\Agent::keys()
@see Memento\Group\Agent::keys()
@return array returns an array of keys for the given group key | https://github.com/garyr/memento/blob/d6cfa9ffec040f96b8361f822f11dcf6d5ff60b4/lib/Memento/Client.php#L179-L197 |
garyr/memento | lib/Memento/Client.php | Client.retrieve | public function retrieve()
{
$args = func_get_args();
list($key, $groupKey) = $this->getKeys($args);
$this->engine->setGroupKey($groupKey);
$expired = false;
if ($groupKey instanceof Group\Key) {
if (array_key_exists(2, $args)) {
$expired = $args[2];
}
} else {
if (array_key_exists(1, $args)) {
$expired = $args[1];
}
}
if (!$this->engine->isValid($key, $expired)) {
return null;
}
return $this->engine->retrieve($key, $expired);
} | php | public function retrieve()
{
$args = func_get_args();
list($key, $groupKey) = $this->getKeys($args);
$this->engine->setGroupKey($groupKey);
$expired = false;
if ($groupKey instanceof Group\Key) {
if (array_key_exists(2, $args)) {
$expired = $args[2];
}
} else {
if (array_key_exists(1, $args)) {
$expired = $args[1];
}
}
if (!$this->engine->isValid($key, $expired)) {
return null;
}
return $this->engine->retrieve($key, $expired);
} | Wrapper method for retrieve() call.
@see Memento\Single\Agent::retrieve()
@see Memento\Group\Agent::retrieve()
@return mixed returns the object that was stored or null if not found | https://github.com/garyr/memento/blob/d6cfa9ffec040f96b8361f822f11dcf6d5ff60b4/lib/Memento/Client.php#L207-L229 |
garyr/memento | lib/Memento/Client.php | Client.store | public function store()
{
$args = func_get_args();
list($key, $groupKey) = $this->getKeys($args);
$this->engine->setGroupKey($groupKey);
$expires = 3600; // default
$ttl = null;
if ($groupKey instanceof Group\Key) {
$value = $args[2];
if (array_key_exists(3, $args)) {
$expires = $args[3];
}
if (array_key_exists(4, $args)) {
$ttl = $args[4];
}
} else {
$value = $args[1];
if (array_key_exists(2, $args)) {
$expires = $args[2];
}
if (array_key_exists(3, $args)) {
$ttl = $args[3];
}
}
return $this->engine->store($key, $value, $expires, $ttl);
} | php | public function store()
{
$args = func_get_args();
list($key, $groupKey) = $this->getKeys($args);
$this->engine->setGroupKey($groupKey);
$expires = 3600; // default
$ttl = null;
if ($groupKey instanceof Group\Key) {
$value = $args[2];
if (array_key_exists(3, $args)) {
$expires = $args[3];
}
if (array_key_exists(4, $args)) {
$ttl = $args[4];
}
} else {
$value = $args[1];
if (array_key_exists(2, $args)) {
$expires = $args[2];
}
if (array_key_exists(3, $args)) {
$ttl = $args[3];
}
}
return $this->engine->store($key, $value, $expires, $ttl);
} | Wrapper method for store() call.
@see Memento\Single\Agent::store()
@see Memento\Group\Agent::store()
@return boolean returns true if the issued key exists | https://github.com/garyr/memento/blob/d6cfa9ffec040f96b8361f822f11dcf6d5ff60b4/lib/Memento/Client.php#L239-L271 |
Laralum/Routes | src/RoutesServiceProvider.php | RoutesServiceProvider.boot | public function boot()
{
$this->registerPolicies();
$this->loadViewsFrom(__DIR__.'/Views', 'laralum_routes');
$this->loadTranslationsFrom(__DIR__.'/Translations', 'laralum_routes');
if (!$this->app->routesAreCached()) {
require __DIR__.'/Routes/web.php';
}
// Make sure the permissions are OK
PermissionsChecker::check($this->permissions);
} | php | public function boot()
{
$this->registerPolicies();
$this->loadViewsFrom(__DIR__.'/Views', 'laralum_routes');
$this->loadTranslationsFrom(__DIR__.'/Translations', 'laralum_routes');
if (!$this->app->routesAreCached()) {
require __DIR__.'/Routes/web.php';
}
// Make sure the permissions are OK
PermissionsChecker::check($this->permissions);
} | Bootstrap the application services.
@return void | https://github.com/Laralum/Routes/blob/10db617db456839c5753294d268198aa65f0a3f0/src/RoutesServiceProvider.php#L40-L53 |
Laralum/Routes | src/RoutesServiceProvider.php | RoutesServiceProvider.registerPolicies | public function registerPolicies()
{
foreach ($this->policies as $key => $value) {
Gate::policy($key, $value);
}
} | php | public function registerPolicies()
{
foreach ($this->policies as $key => $value) {
Gate::policy($key, $value);
}
} | I cheated this comes from the AuthServiceProvider extended by the App\Providers\AuthServiceProvider.
Register the application's policies.
@return void | https://github.com/Laralum/Routes/blob/10db617db456839c5753294d268198aa65f0a3f0/src/RoutesServiceProvider.php#L62-L67 |
ntentan/atiaa | src/Descriptor.php | Descriptor.describe | public function describe()
{
$defaultSchema = $this->driver->getDefaultSchema();
$description = [
'schemata' => [],
];
$schemata = $this->getSchemata();
foreach ($schemata as $schema) {
if ($schema['name'] == $defaultSchema) {
$description['tables'] = $this->describeTables($defaultSchema);
$description['views'] = $this->describeViews($defaultSchema);
} else {
$description['schemata'][$schema['name']]['name'] = $schema['name'];
$description['schemata'][$schema['name']]['tables'] = $this->describeTables($schema['name']);
$description['schemata'][$schema['name']]['views'] = $this->describeViews($schema['name']);
}
}
return $description;
} | php | public function describe()
{
$defaultSchema = $this->driver->getDefaultSchema();
$description = [
'schemata' => [],
];
$schemata = $this->getSchemata();
foreach ($schemata as $schema) {
if ($schema['name'] == $defaultSchema) {
$description['tables'] = $this->describeTables($defaultSchema);
$description['views'] = $this->describeViews($defaultSchema);
} else {
$description['schemata'][$schema['name']]['name'] = $schema['name'];
$description['schemata'][$schema['name']]['tables'] = $this->describeTables($schema['name']);
$description['schemata'][$schema['name']]['views'] = $this->describeViews($schema['name']);
}
}
return $description;
} | Returns the description of the database as an array.
@return array | https://github.com/ntentan/atiaa/blob/2604fea83e9643adaa8d1fb65443fb214cfa60e6/src/Descriptor.php#L235-L256 |
ntentan/atiaa | src/Descriptor.php | Descriptor.throwTableExceptions | private function throwTableExceptions($tables, $requestedTables)
{
$foundTables = [];
foreach ($tables as $table) {
$foundTables[] = $table['name'];
}
foreach ($requestedTables as $requestedTable) {
if (array_search($requestedTable, $foundTables) === false) {
throw new exceptions\TableNotFoundException($requestedTable
? "$requestedTable not found on target database."
: 'Please specify a table name.'
);
}
}
} | php | private function throwTableExceptions($tables, $requestedTables)
{
$foundTables = [];
foreach ($tables as $table) {
$foundTables[] = $table['name'];
}
foreach ($requestedTables as $requestedTable) {
if (array_search($requestedTable, $foundTables) === false) {
throw new exceptions\TableNotFoundException($requestedTable
? "$requestedTable not found on target database."
: 'Please specify a table name.'
);
}
}
} | Throws exceptions for which are found in the list of requested tables
but not found in the list of found tables.
@param array $tables
@param array $requestedTables
@throws exceptions\TableNotFoundException | https://github.com/ntentan/atiaa/blob/2604fea83e9643adaa8d1fb65443fb214cfa60e6/src/Descriptor.php#L272-L287 |
rackberg/para | src/Factory/GroupFactory.php | GroupFactory.getGroup | public function getGroup(string $groupName): GroupInterface
{
$group = new Group();
$group->setName($groupName);
return $group;
} | php | public function getGroup(string $groupName): GroupInterface
{
$group = new Group();
$group->setName($groupName);
return $group;
} | {@inheritdoc} | https://github.com/rackberg/para/blob/e0ef1356ed2979670eb7c670d88921406cade46e/src/Factory/GroupFactory.php#L18-L23 |
vi-kon/laravel-parser-markdown | src/ViKon/ParserMarkdown/Skin/Bootstrap/Block/CodeBlockBootstrapRenderer.php | CodeBlockBootstrapRenderer.register | public function register(Renderer $renderer) {
$this->registerTokenRenderer(CodeBlockRule::NAME . CodeBlockRule::OPEN, 'renderOpen', $renderer);
$this->registerTokenRenderer(CodeBlockRule::NAME . CodeBlockRule::CLOSE, 'renderClose', $renderer);
$this->registerTokenRenderer(CodeBlockRule::NAME, 'renderContent', $renderer);
} | php | public function register(Renderer $renderer) {
$this->registerTokenRenderer(CodeBlockRule::NAME . CodeBlockRule::OPEN, 'renderOpen', $renderer);
$this->registerTokenRenderer(CodeBlockRule::NAME . CodeBlockRule::CLOSE, 'renderClose', $renderer);
$this->registerTokenRenderer(CodeBlockRule::NAME, 'renderContent', $renderer);
} | Register renderer
@param \ViKon\Parser\Renderer\Renderer $renderer | https://github.com/vi-kon/laravel-parser-markdown/blob/4b258b407df95f6b6be284252762ef3ddbef1e35/src/ViKon/ParserMarkdown/Skin/Bootstrap/Block/CodeBlockBootstrapRenderer.php#L24-L28 |
endeveit/open-stack-storage | src/Client.php | Client.sendRequest | public function sendRequest(
$url,
$method = 'GET',
$querydata = null,
$headers = null,
$options = null
) {
if (null === $headers) {
$headers = array();
} elseif (!is_array($headers)) {
$headers = (array) $headers;
}
if (null === $options) {
$options = array();
} elseif (!is_array($options)) {
$options = (array) $options;
}
if (!array_key_exists('timeout', $options)) {
$options['timeout'] = $this->timeout;
}
if ($method == self::PUT && !array_key_exists('Content-Length', $headers)) {
if (empty($querydata)) {
$headers['Content-Length'] = 0;
} else {
$headers['Content-Length'] = is_string($querydata)
? strlen($querydata)
: strlen(http_build_query($querydata));
}
}
$response = parent::sendRequest($url, $method, $querydata, $headers, $options);
if (array_key_exists('error_msg', $response) && (null !== $response['error_msg'])) {
throw new Exceptions\Error(substr($response['error_msg'], 0, strpos($response['error_msg'], ';')));
}
if ($response['status'] >= 400) {
throw new Exceptions\ResponseError($response['status']);
}
$response['headers'] = new Client\Headers($response['headers']);
return $response;
} | php | public function sendRequest(
$url,
$method = 'GET',
$querydata = null,
$headers = null,
$options = null
) {
if (null === $headers) {
$headers = array();
} elseif (!is_array($headers)) {
$headers = (array) $headers;
}
if (null === $options) {
$options = array();
} elseif (!is_array($options)) {
$options = (array) $options;
}
if (!array_key_exists('timeout', $options)) {
$options['timeout'] = $this->timeout;
}
if ($method == self::PUT && !array_key_exists('Content-Length', $headers)) {
if (empty($querydata)) {
$headers['Content-Length'] = 0;
} else {
$headers['Content-Length'] = is_string($querydata)
? strlen($querydata)
: strlen(http_build_query($querydata));
}
}
$response = parent::sendRequest($url, $method, $querydata, $headers, $options);
if (array_key_exists('error_msg', $response) && (null !== $response['error_msg'])) {
throw new Exceptions\Error(substr($response['error_msg'], 0, strpos($response['error_msg'], ';')));
}
if ($response['status'] >= 400) {
throw new Exceptions\ResponseError($response['status']);
}
$response['headers'] = new Client\Headers($response['headers']);
return $response;
} | {@inheritdoc}
@param string $url
@param string $method
@param array $querydata
@param array $headers
@param array $options
@return array
@throws \OpenStackStorage\Exceptions\ResponseError
@throws \OpenStackStorage\Exceptions\Error | https://github.com/endeveit/open-stack-storage/blob/4f2559230371d74c3f0de3812594f57a9f79a150/src/Client.php#L58-L104 |
endeveit/open-stack-storage | src/Client.php | Client.processResponseBody | protected function processResponseBody($resp)
{
if ($this->parse_body === true) {
if (isset($resp['headers']['Content-Type'])) {
$contentType = preg_split('/[;\s]+/', $resp['headers']['Content-Type']);
$contentType = $contentType[0];
} else {
$contentType = null;
}
if ((null !== $contentType) && !empty($contentType)) {
if (in_array($contentType, self::$JSON_TYPES) || strpos($contentType, '+json') !== false) {
$this->log('Response body is JSON');
$resp['body_raw'] = $resp['body'];
$resp['body'] = json_decode($resp['body'], true);
return $resp;
}
parent::processResponseBody($resp);
}
}
$this->log('Response body not parsed');
return $resp;
} | php | protected function processResponseBody($resp)
{
if ($this->parse_body === true) {
if (isset($resp['headers']['Content-Type'])) {
$contentType = preg_split('/[;\s]+/', $resp['headers']['Content-Type']);
$contentType = $contentType[0];
} else {
$contentType = null;
}
if ((null !== $contentType) && !empty($contentType)) {
if (in_array($contentType, self::$JSON_TYPES) || strpos($contentType, '+json') !== false) {
$this->log('Response body is JSON');
$resp['body_raw'] = $resp['body'];
$resp['body'] = json_decode($resp['body'], true);
return $resp;
}
parent::processResponseBody($resp);
}
}
$this->log('Response body not parsed');
return $resp;
} | {@inheritdoc}
Overridden method to decode JSON to array instead of stdClass.
@param string $resp
@return object|string | https://github.com/endeveit/open-stack-storage/blob/4f2559230371d74c3f0de3812594f57a9f79a150/src/Client.php#L113-L140 |
rnijveld/pgt | lib/Pgettext/Po.php | Po.toFile | public static function toFile(Stringset $set, $filename)
{
try {
$str = self::toString($set, $options);
if (!file_exists($filename) || is_writable($filename)) {
file_put_contents($filename, $str);
} else {
throw new Exception("Cannot write to file");
}
} catch (\Exception $e) {
throw $e;
}
} | php | public static function toFile(Stringset $set, $filename)
{
try {
$str = self::toString($set, $options);
if (!file_exists($filename) || is_writable($filename)) {
file_put_contents($filename, $str);
} else {
throw new Exception("Cannot write to file");
}
} catch (\Exception $e) {
throw $e;
}
} | Takes a Stringset and a filename and writes a po formatted file.
@param Stringset $set
@param string $filename
@return void | https://github.com/rnijveld/pgt/blob/9d64b4858438a9833065265c2e6d2db94b7e6fcd/lib/Pgettext/Po.php#L34-L46 |
rnijveld/pgt | lib/Pgettext/Po.php | Po.toString | public static function toString(Stringset $set)
{
$str = '';
for ($i = 0; $i < $set->size(); $i += 1) {
$item = $set->item($i);
if (count($item['flags']) > 0) {
$str .= "#, " . implode(", ", $item['flags']) . "\n";
}
if ($item['context'] !== null) {
$str .= "msgctxt " . '"' . $item['context'] . '"' . "\n";
}
$str .= "msgid " . '"' . self::escapeString($item['id']) . '"' . "\n";
if ($item['plural'] !== null) {
$str .= "msgid_plural " . '"' . self::escapeString($item['plural']) . '"' . "\n";
}
if (count($item['strings']) === 1) {
$str .= "msgstr " . '"' . self::escapeString($item['strings'][0]) . '"' . "\n";
} else {
for ($j = 0; $j < count($item['strings']); $j += 1) {
$str .= "msgstr[" . $i . "] " . '"' . self::escapeString($item['strings'][0]) . '"' . "\n";
}
}
$str .= "\n";
}
return $str;
} | php | public static function toString(Stringset $set)
{
$str = '';
for ($i = 0; $i < $set->size(); $i += 1) {
$item = $set->item($i);
if (count($item['flags']) > 0) {
$str .= "#, " . implode(", ", $item['flags']) . "\n";
}
if ($item['context'] !== null) {
$str .= "msgctxt " . '"' . $item['context'] . '"' . "\n";
}
$str .= "msgid " . '"' . self::escapeString($item['id']) . '"' . "\n";
if ($item['plural'] !== null) {
$str .= "msgid_plural " . '"' . self::escapeString($item['plural']) . '"' . "\n";
}
if (count($item['strings']) === 1) {
$str .= "msgstr " . '"' . self::escapeString($item['strings'][0]) . '"' . "\n";
} else {
for ($j = 0; $j < count($item['strings']); $j += 1) {
$str .= "msgstr[" . $i . "] " . '"' . self::escapeString($item['strings'][0]) . '"' . "\n";
}
}
$str .= "\n";
}
return $str;
} | Takes a Stringset and an array of options and creates a po formatted string.
@param Stringset $set
@return string | https://github.com/rnijveld/pgt/blob/9d64b4858438a9833065265c2e6d2db94b7e6fcd/lib/Pgettext/Po.php#L53-L82 |
rnijveld/pgt | lib/Pgettext/Po.php | Po.escapeString | private static function escapeString($str)
{
if (strlen($str) === 0) {
return $str;
}
$str = str_replace(array(
"\r",
"\t",
"\\",
"\$",
"\v",
"\e",
"\f",
"\""
), array(
'\r',
'\t',
'\\\\',
'\$',
'\v',
'\e',
'\f',
'\"'
), $str);
$str = str_replace("\n", "\\n\"\n\"", $str);
$result = '';
$str = str_split($str, 1);
foreach ($str as $chr) {
if (!ctype_print($chr) && $chr !== "\n") {
$result .= '\\' . decoct(ord($chr));
} else {
$result .= $chr;
}
}
if (substr($result, -5) === "\\n\"\n\"") {
$result = substr($result, 0, -5) . "\\n";
}
return $result;
} | php | private static function escapeString($str)
{
if (strlen($str) === 0) {
return $str;
}
$str = str_replace(array(
"\r",
"\t",
"\\",
"\$",
"\v",
"\e",
"\f",
"\""
), array(
'\r',
'\t',
'\\\\',
'\$',
'\v',
'\e',
'\f',
'\"'
), $str);
$str = str_replace("\n", "\\n\"\n\"", $str);
$result = '';
$str = str_split($str, 1);
foreach ($str as $chr) {
if (!ctype_print($chr) && $chr !== "\n") {
$result .= '\\' . decoct(ord($chr));
} else {
$result .= $chr;
}
}
if (substr($result, -5) === "\\n\"\n\"") {
$result = substr($result, 0, -5) . "\\n";
}
return $result;
} | Adds escapes to characters that are in some way special.
@param string $str
@return string | https://github.com/rnijveld/pgt/blob/9d64b4858438a9833065265c2e6d2db94b7e6fcd/lib/Pgettext/Po.php#L89-L130 |
rnijveld/pgt | lib/Pgettext/Po.php | Po.fromString | public static function fromString($str)
{
$stringset = new Stringset();
$entry = array();
$state = null;
$line = 1;
foreach (explode("\n", $str) as $line) {
$line = trim($line);
if (strlen($line) === 0) {
if (count($entry) > 0) {
$stringset->add($entry);
$entry = array();
$state = null;
}
continue;
}
if ($line[0] === '#' && $line[1] === ',') {
$entry['flags'] = array_map('trim', explode(',', substr($line, 2)));
} else if ($line[0] !== '#') {
// non-comment
list($key, $rest) = explode(' ', $line, 2);
switch ($key) {
case 'msgid':
case 'msgid_plural':
case 'msgstr':
case 'msgctxt':
if (strpos($state, 'msgstr') === 0 && $key !== 'msgstr' && count($entry) > 0) {
$stringset->add($entry);
$entry = array();
}
$state = $key;
$entry[$key] = self::parseString($rest);
break;
default:
if (strpos($key, 'msgstr[') === 0) {
$state = $key;
$entry[$key] = self::parseString($rest);
} else {
$entry[$state] .= self::parseString(trim($line));
}
}
}
$line += 1;
}
return $stringset;
} | php | public static function fromString($str)
{
$stringset = new Stringset();
$entry = array();
$state = null;
$line = 1;
foreach (explode("\n", $str) as $line) {
$line = trim($line);
if (strlen($line) === 0) {
if (count($entry) > 0) {
$stringset->add($entry);
$entry = array();
$state = null;
}
continue;
}
if ($line[0] === '#' && $line[1] === ',') {
$entry['flags'] = array_map('trim', explode(',', substr($line, 2)));
} else if ($line[0] !== '#') {
// non-comment
list($key, $rest) = explode(' ', $line, 2);
switch ($key) {
case 'msgid':
case 'msgid_plural':
case 'msgstr':
case 'msgctxt':
if (strpos($state, 'msgstr') === 0 && $key !== 'msgstr' && count($entry) > 0) {
$stringset->add($entry);
$entry = array();
}
$state = $key;
$entry[$key] = self::parseString($rest);
break;
default:
if (strpos($key, 'msgstr[') === 0) {
$state = $key;
$entry[$key] = self::parseString($rest);
} else {
$entry[$state] .= self::parseString(trim($line));
}
}
}
$line += 1;
}
return $stringset;
} | Takes a string in the format of a po file and returns a Stringset
@param string $str
@return Stringset | https://github.com/rnijveld/pgt/blob/9d64b4858438a9833065265c2e6d2db94b7e6fcd/lib/Pgettext/Po.php#L137-L185 |
rnijveld/pgt | lib/Pgettext/Po.php | Po.parseString | private static function parseString($str)
{
if ($str[0] !== '"' || $str[strlen($str) - 1] !== '"') {
throw new Exception("Invalid string delimiters");
}
$result = '';
$start = str_split(substr($str, 1, -1), 1);
$escaped = false;
$data = null;
foreach ($start as $chr) {
if ($escaped === 'yes') {
$escaped = false;
switch ($chr) {
case 'n': $result .= "\n"; break;
case 'r': $result .= "\r"; break;
case 't': $result .= "\t"; break;
case 'v': $result .= "\v"; break;
case 'e': $result .= "\e"; break;
case 'f': $result .= "\f"; break;
case '\\': $result .= "\\"; break;
case '$': $result .= "\$"; break;
case '"': $result .= "\""; break;
case 'x':
$escaped = 'hex';
$data = '0x';
break;
default:
if (ctype_digit($chr) && (int)$chr < 8) {
$escaped = 'oct';
$data = $chr;
} else {
$result .= "\\" . $chr;
}
break;
}
} else if ($escaped === 'hex' && ctype_xdigit($chr)) {
$data .= $chr;
if (strlen($data) === 2) {
$escaped = false;
}
} else if ($escaped === 'oct' && ctype_digit($chr) && (int)$chr < 8) {
$data .= $chr;
if (strlen($data) === 3) {
$escaped = false;
}
} else {
if ($data !== null || $escaped === 'hex' || $escaped === 'oct') {
if (substr($data, 0, 2) === '0x') {
if (strlen($data) === 2) {
$result .= "\\x";
} else {
$result .= chr(hexdec($data));
}
} else {
$result .= chr(octdec($data));
}
$data = null;
}
if ($chr === '\\') {
$escaped = 'yes';
} else if ($chr === '"') {
throw new Exception("Unescaped string delimiter inside string");
} else {
$result .= $chr;
}
}
}
if ($escaped !== false) {
throw new Exception("Unfinished escape sequence");
}
return $result;
} | php | private static function parseString($str)
{
if ($str[0] !== '"' || $str[strlen($str) - 1] !== '"') {
throw new Exception("Invalid string delimiters");
}
$result = '';
$start = str_split(substr($str, 1, -1), 1);
$escaped = false;
$data = null;
foreach ($start as $chr) {
if ($escaped === 'yes') {
$escaped = false;
switch ($chr) {
case 'n': $result .= "\n"; break;
case 'r': $result .= "\r"; break;
case 't': $result .= "\t"; break;
case 'v': $result .= "\v"; break;
case 'e': $result .= "\e"; break;
case 'f': $result .= "\f"; break;
case '\\': $result .= "\\"; break;
case '$': $result .= "\$"; break;
case '"': $result .= "\""; break;
case 'x':
$escaped = 'hex';
$data = '0x';
break;
default:
if (ctype_digit($chr) && (int)$chr < 8) {
$escaped = 'oct';
$data = $chr;
} else {
$result .= "\\" . $chr;
}
break;
}
} else if ($escaped === 'hex' && ctype_xdigit($chr)) {
$data .= $chr;
if (strlen($data) === 2) {
$escaped = false;
}
} else if ($escaped === 'oct' && ctype_digit($chr) && (int)$chr < 8) {
$data .= $chr;
if (strlen($data) === 3) {
$escaped = false;
}
} else {
if ($data !== null || $escaped === 'hex' || $escaped === 'oct') {
if (substr($data, 0, 2) === '0x') {
if (strlen($data) === 2) {
$result .= "\\x";
} else {
$result .= chr(hexdec($data));
}
} else {
$result .= chr(octdec($data));
}
$data = null;
}
if ($chr === '\\') {
$escaped = 'yes';
} else if ($chr === '"') {
throw new Exception("Unescaped string delimiter inside string");
} else {
$result .= $chr;
}
}
}
if ($escaped !== false) {
throw new Exception("Unfinished escape sequence");
}
return $result;
} | PHP String parsing without using eval.
@param string $str Unparsed double-quoted string with escape sequences.
@return string | https://github.com/rnijveld/pgt/blob/9d64b4858438a9833065265c2e6d2db94b7e6fcd/lib/Pgettext/Po.php#L192-L266 |
newup/core | src/Console/Commands/Composer/Which.php | Which.handle | public function handle()
{
$this->line('NewUp is using the Composer that can be found at this location:');
$composer = $this->composer->findComposer();
$this->line($composer);
$formatter = $this->getHelper('formatter');
if ($composer == 'composer') {
$errorMessages = [
'It appears that your composer.phar file is aliased, or set in a PATH variable',
'To find out where it is at, run the relevant command for your system:',
'Windows: where '.$composer,
'Linux: which '.$composer
];
$formattedBlock = $formatter->formatBlock($errorMessages, 'comment', true);
$this->output->writeln($formattedBlock);
}
} | php | public function handle()
{
$this->line('NewUp is using the Composer that can be found at this location:');
$composer = $this->composer->findComposer();
$this->line($composer);
$formatter = $this->getHelper('formatter');
if ($composer == 'composer') {
$errorMessages = [
'It appears that your composer.phar file is aliased, or set in a PATH variable',
'To find out where it is at, run the relevant command for your system:',
'Windows: where '.$composer,
'Linux: which '.$composer
];
$formattedBlock = $formatter->formatBlock($errorMessages, 'comment', true);
$this->output->writeln($formattedBlock);
}
} | Execute the console command.
@return mixed | https://github.com/newup/core/blob/54128903e7775e67d63284d958b46862c8df71f9/src/Console/Commands/Composer/Which.php#L43-L63 |
newestindustry/ginger-rest | src/Ginger/Request.php | Request.go | public function go() {
if ($this->action == "options") {
$file = "options" . $this->getExtension();
} else {
// Check if handler file exists
if ($this->route->route == "/") {
$file = $this->getAction() . $this->getExtension();
} else {
$file = $this->route->resource . "/" . $this->getAction() . $this->getExtension();
}
}
$fullFilePath = stream_resolve_include_path($file);
if ($fullFilePath) {
include $fullFilePath;
} else {
throw new \Ginger\Exception("Not implemented", 501);
}
$this->getResponse()->send();
} | php | public function go() {
if ($this->action == "options") {
$file = "options" . $this->getExtension();
} else {
// Check if handler file exists
if ($this->route->route == "/") {
$file = $this->getAction() . $this->getExtension();
} else {
$file = $this->route->resource . "/" . $this->getAction() . $this->getExtension();
}
}
$fullFilePath = stream_resolve_include_path($file);
if ($fullFilePath) {
include $fullFilePath;
} else {
throw new \Ginger\Exception("Not implemented", 501);
}
$this->getResponse()->send();
} | Load file and dispatch to response | https://github.com/newestindustry/ginger-rest/blob/482b77dc122a60ab0bf143a3c4a1e67168985c83/src/Ginger/Request.php#L101-L121 |
newestindustry/ginger-rest | src/Ginger/Request.php | Request.getAction | public function getAction() {
if ($this->action) {
return $this->action;
} else {
$action = "index";
switch ($_SERVER['REQUEST_METHOD']) {
case "GET":
if (count($this->getFilterParameters()) == 0) {
$action = "index";
} else {
$action = "get";
}
break;
case "POST":
$action = "post";
break;
case "PUT":
$action = "put";
break;
case "DELETE":
$action = "delete";
break;
case "HEAD":
$action = "head";
break;
case "SEARCH":
$action = "search";
break;
case "OPTIONS":
$action = "options";
break;
}
return $action;
}
} | php | public function getAction() {
if ($this->action) {
return $this->action;
} else {
$action = "index";
switch ($_SERVER['REQUEST_METHOD']) {
case "GET":
if (count($this->getFilterParameters()) == 0) {
$action = "index";
} else {
$action = "get";
}
break;
case "POST":
$action = "post";
break;
case "PUT":
$action = "put";
break;
case "DELETE":
$action = "delete";
break;
case "HEAD":
$action = "head";
break;
case "SEARCH":
$action = "search";
break;
case "OPTIONS":
$action = "options";
break;
}
return $action;
}
} | Return current action
@return string | https://github.com/newestindustry/ginger-rest/blob/482b77dc122a60ab0bf143a3c4a1e67168985c83/src/Ginger/Request.php#L195-L230 |
amarcinkowski/hospitalplugin | src/Twig/GetPropertiesExtension.php | GetPropertiesExtension.getProps | private static function getProps($class)
{
if ($class == NULL) {
return array();
}
$class = new \ReflectionClass($class);
$properties = array_filter($class->getProperties(), function ($prop) use($class)
{
return $prop->getDeclaringClass()->name == $class->name;
});
return $properties;
} | php | private static function getProps($class)
{
if ($class == NULL) {
return array();
}
$class = new \ReflectionClass($class);
$properties = array_filter($class->getProperties(), function ($prop) use($class)
{
return $prop->getDeclaringClass()->name == $class->name;
});
return $properties;
} | return props of a class
@param unknown $class
@return boolean|multitype: | https://github.com/amarcinkowski/hospitalplugin/blob/acdc2be5157abfbdcafb4dcf6c6ba505e291263f/src/Twig/GetPropertiesExtension.php#L22-L33 |
amarcinkowski/hospitalplugin | src/Twig/GetPropertiesExtension.php | GetPropertiesExtension.getPropsFilter | public function getPropsFilter($obj, $exclude, $replace, $titles)
{
// properties of an object, not array
while (is_array($obj)) {
$obj = $obj[0];
}
$parentProperties = GetPropertiesExtension::getProps(get_parent_class($obj));
$properties = GetPropertiesExtension::getProps($obj);
$propertiesMerged = array_merge($parentProperties, $properties);
$propsArray = GetPropertiesExtension::exludeAndReplace($propertiesMerged, $exclude, $replace, $titles);
return $propsArray;
} | php | public function getPropsFilter($obj, $exclude, $replace, $titles)
{
// properties of an object, not array
while (is_array($obj)) {
$obj = $obj[0];
}
$parentProperties = GetPropertiesExtension::getProps(get_parent_class($obj));
$properties = GetPropertiesExtension::getProps($obj);
$propertiesMerged = array_merge($parentProperties, $properties);
$propsArray = GetPropertiesExtension::exludeAndReplace($propertiesMerged, $exclude, $replace, $titles);
return $propsArray;
} | returns properties of an object excluding those that have name same as in $exclude array
order of returned properties is: first parent class of $obj props then base class props of an $obj
@param unknown $obj
@param unknown $exclude
@return boolean|string | https://github.com/amarcinkowski/hospitalplugin/blob/acdc2be5157abfbdcafb4dcf6c6ba505e291263f/src/Twig/GetPropertiesExtension.php#L69-L80 |
interactivesolutions/honeycomb-scripts | src/app/commands/HCNewService.php | HCNewService.handle | public function handle()
{
$this->loadConfiguration();
foreach ( $this->configurationData as $serviceData ) {
$this->createdFiles = [];
$this->createService($serviceData);
$this->finalizeFile($serviceData->file);
}
$this->call('hc:routes');
$this->call('hc:forms');
$this->call('hc:admin-menu');
} | php | public function handle()
{
$this->loadConfiguration();
foreach ( $this->configurationData as $serviceData ) {
$this->createdFiles = [];
$this->createService($serviceData);
$this->finalizeFile($serviceData->file);
}
$this->call('hc:routes');
$this->call('hc:forms');
$this->call('hc:admin-menu');
} | Execute the console command.
@return this | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/HCNewService.php#L59-L72 |
interactivesolutions/honeycomb-scripts | src/app/commands/HCNewService.php | HCNewService.createService | private function createService(stdClass $serviceData)
{
$this->comment('');
$this->comment('*************************************');
$this->comment('* Service creation *');
$this->comment('*************************************');
$this->comment($serviceData->serviceName);
$this->comment('*************************************');
$helpersList = [
'controller' => new HCServiceController(),
'translations' => new HCServiceTranslations(),
'models' => new HCServiceModels(),
'form-validators' => new HCServiceFormValidators(),
'forms' => new HCServiceForms(),
'routes' => new HCServiceRoutes(),
];
foreach ( $helpersList as $helper )
$serviceData = $helper->optimize($serviceData);
// finalizing destination
$serviceData->controllerDestination .= '/' . $serviceData->controllerName . '.php';
foreach ( $helpersList as $helper ) {
$files = $helper->generate($serviceData);
if( is_array($files) )
$this->createdFiles = array_merge($this->createdFiles, $files);
else
$this->createdFiles[] = $files;
}
if( $serviceData->rootDirectory != './' )
$this->call('hc:routes', ["directory" => $serviceData->rootDirectory]);
else
$this->call('hc:routes');
if( isset($serviceData->generateMigrations) && $serviceData->generateMigrations )
$this->call('migrate:generate', ["--path" => $serviceData->rootDirectory . 'database/migrations', "tables" => implode(",", $helpersList['models']->getTables())]);
$this->updateConfiguration($serviceData);
} | php | private function createService(stdClass $serviceData)
{
$this->comment('');
$this->comment('*************************************');
$this->comment('* Service creation *');
$this->comment('*************************************');
$this->comment($serviceData->serviceName);
$this->comment('*************************************');
$helpersList = [
'controller' => new HCServiceController(),
'translations' => new HCServiceTranslations(),
'models' => new HCServiceModels(),
'form-validators' => new HCServiceFormValidators(),
'forms' => new HCServiceForms(),
'routes' => new HCServiceRoutes(),
];
foreach ( $helpersList as $helper )
$serviceData = $helper->optimize($serviceData);
// finalizing destination
$serviceData->controllerDestination .= '/' . $serviceData->controllerName . '.php';
foreach ( $helpersList as $helper ) {
$files = $helper->generate($serviceData);
if( is_array($files) )
$this->createdFiles = array_merge($this->createdFiles, $files);
else
$this->createdFiles[] = $files;
}
if( $serviceData->rootDirectory != './' )
$this->call('hc:routes', ["directory" => $serviceData->rootDirectory]);
else
$this->call('hc:routes');
if( isset($serviceData->generateMigrations) && $serviceData->generateMigrations )
$this->call('migrate:generate', ["--path" => $serviceData->rootDirectory . 'database/migrations', "tables" => implode(",", $helpersList['models']->getTables())]);
$this->updateConfiguration($serviceData);
} | Generating service information
@param $serviceData | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/HCNewService.php#L79-L121 |
interactivesolutions/honeycomb-scripts | src/app/commands/HCNewService.php | HCNewService.loadConfiguration | private function loadConfiguration()
{
$allFiles = File::allFiles('_automate');
foreach ( $allFiles as $file )
if( strpos((string)$file, '.done') === false )
$this->configurationData[] = $this->optimizeData($file);
} | php | private function loadConfiguration()
{
$allFiles = File::allFiles('_automate');
foreach ( $allFiles as $file )
if( strpos((string)$file, '.done') === false )
$this->configurationData[] = $this->optimizeData($file);
} | Loading configuration files
@return this | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/HCNewService.php#L128-L136 |
interactivesolutions/honeycomb-scripts | src/app/commands/HCNewService.php | HCNewService.optimizeData | function optimizeData(string $file)
{
$item = json_decode(file_get_contents($file));
$item->file = $file;
if( $item == null )
$this->abort($file->getFilename() . ' has Invalid JSON format.');
if( $item->directory == '' ) {
$item->directory = '';
$item->rootDirectory = './';
$item->pacakgeService = false;
} else {
$item->directory .= '/';
$item->rootDirectory = './packages/' . $item->directory . 'src/';
$item->pacakgeService = true;
$this->checkPackage($item);
}
return $item;
} | php | function optimizeData(string $file)
{
$item = json_decode(file_get_contents($file));
$item->file = $file;
if( $item == null )
$this->abort($file->getFilename() . ' has Invalid JSON format.');
if( $item->directory == '' ) {
$item->directory = '';
$item->rootDirectory = './';
$item->pacakgeService = false;
} else {
$item->directory .= '/';
$item->rootDirectory = './packages/' . $item->directory . 'src/';
$item->pacakgeService = true;
$this->checkPackage($item);
}
return $item;
} | Optimizing files
@param $file
@return mixed | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/HCNewService.php#L143-L163 |
interactivesolutions/honeycomb-scripts | src/app/commands/HCNewService.php | HCNewService.checkPackage | private function checkPackage(stdClass $item)
{
if( ! file_exists($item->rootDirectory) )
$this->abort('Package ' . $item->directory . ' not existing, please create a repository and launch "php artisan hc:new-package" command');
} | php | private function checkPackage(stdClass $item)
{
if( ! file_exists($item->rootDirectory) )
$this->abort('Package ' . $item->directory . ' not existing, please create a repository and launch "php artisan hc:new-package" command');
} | Checking package existence
@param $item | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/HCNewService.php#L169-L173 |
interactivesolutions/honeycomb-scripts | src/app/commands/HCNewService.php | HCNewService.executeAfterAbort | protected function executeAfterAbort()
{
/*foreach ($this->originalFiles as $value)
{
$this->file->put($value['path'], $value['content']);
$this->comment('Restored: ' . $value['path']);
}*/
foreach ( $this->createdFiles as $value ) {
File::delete($value);
$this->error('Deleted: ' . $value);
}
} | php | protected function executeAfterAbort()
{
/*foreach ($this->originalFiles as $value)
{
$this->file->put($value['path'], $value['content']);
$this->comment('Restored: ' . $value['path']);
}*/
foreach ( $this->createdFiles as $value ) {
File::delete($value);
$this->error('Deleted: ' . $value);
}
} | Restoring changed files after the abort
Deleting create files
@return this | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/HCNewService.php#L181-L193 |
interactivesolutions/honeycomb-scripts | src/app/commands/HCNewService.php | HCNewService.updateConfiguration | private function updateConfiguration(stdClass $serviceData)
{
$config = json_decode(file_get_contents($serviceData->rootDirectory . 'app/' . HCNewService::CONFIG_PATH));
$config = $this->updateActions($config, $serviceData);
$config = $this->updateRolesActions($config, $serviceData);
$config = $this->updateMenu($config, $serviceData);
$config = $this->updateFormManager($config, $serviceData);
file_put_contents($serviceData->rootDirectory . 'app/' . HCNewService::CONFIG_PATH, json_encode($config, JSON_PRETTY_PRINT));
} | php | private function updateConfiguration(stdClass $serviceData)
{
$config = json_decode(file_get_contents($serviceData->rootDirectory . 'app/' . HCNewService::CONFIG_PATH));
$config = $this->updateActions($config, $serviceData);
$config = $this->updateRolesActions($config, $serviceData);
$config = $this->updateMenu($config, $serviceData);
$config = $this->updateFormManager($config, $serviceData);
file_put_contents($serviceData->rootDirectory . 'app/' . HCNewService::CONFIG_PATH, json_encode($config, JSON_PRETTY_PRINT));
} | Updating configuration
@param $serviceData
@return null | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/HCNewService.php#L202-L212 |
interactivesolutions/honeycomb-scripts | src/app/commands/HCNewService.php | HCNewService.updateActions | private function updateActions(stdClass $config, stdClass $serviceData)
{
$servicePermissions = [
"name" => "admin." . $serviceData->serviceRouteName,
"controller" => $serviceData->controllerNamespace . '\\' . $serviceData->controllerName,
"actions" => [
$serviceData->aclPrefix . "_list",
$serviceData->aclPrefix . "_create",
$serviceData->aclPrefix . "_update",
$serviceData->aclPrefix . "_delete",
$serviceData->aclPrefix . "_force_delete",
],
];
$contentChanged = false;
foreach ( $config->acl->permissions as &$value ) {
if( $value->name == "admin." . $serviceData->serviceRouteName ) {
if( $this->confirm('Duplicate ACL found ' . "admin." . $serviceData->serviceRouteName . ' Confirm override', 'no') ) {
$contentChanged = true;
$value = $servicePermissions;
break;
} else {
$this->abort('Can not override existing configuration. Aborting...');
return null;
}
}
}
if( ! $contentChanged )
$config->acl->permissions = array_merge($config->acl->permissions, [$servicePermissions]);
return $config;
} | php | private function updateActions(stdClass $config, stdClass $serviceData)
{
$servicePermissions = [
"name" => "admin." . $serviceData->serviceRouteName,
"controller" => $serviceData->controllerNamespace . '\\' . $serviceData->controllerName,
"actions" => [
$serviceData->aclPrefix . "_list",
$serviceData->aclPrefix . "_create",
$serviceData->aclPrefix . "_update",
$serviceData->aclPrefix . "_delete",
$serviceData->aclPrefix . "_force_delete",
],
];
$contentChanged = false;
foreach ( $config->acl->permissions as &$value ) {
if( $value->name == "admin." . $serviceData->serviceRouteName ) {
if( $this->confirm('Duplicate ACL found ' . "admin." . $serviceData->serviceRouteName . ' Confirm override', 'no') ) {
$contentChanged = true;
$value = $servicePermissions;
break;
} else {
$this->abort('Can not override existing configuration. Aborting...');
return null;
}
}
}
if( ! $contentChanged )
$config->acl->permissions = array_merge($config->acl->permissions, [$servicePermissions]);
return $config;
} | Updating service actions
@param $config
@param $serviceData
@return null | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/HCNewService.php#L221-L255 |
interactivesolutions/honeycomb-scripts | src/app/commands/HCNewService.php | HCNewService.updateRolesActions | private function updateRolesActions(stdClass $config, stdClass $serviceData)
{
$rolesActions = [
"project-admin" =>
[$serviceData->aclPrefix . "_list",
$serviceData->aclPrefix . "_create",
$serviceData->aclPrefix . "_update",
$serviceData->aclPrefix . "_delete",
],
];
if( empty($config->acl->rolesActions) )
$config->acl->rolesActions = $rolesActions;
else
$config->acl->rolesActions->{"project-admin"} = array_unique(array_merge($config->acl->rolesActions->{"project-admin"}, $rolesActions['project-admin']));
return $config;
} | php | private function updateRolesActions(stdClass $config, stdClass $serviceData)
{
$rolesActions = [
"project-admin" =>
[$serviceData->aclPrefix . "_list",
$serviceData->aclPrefix . "_create",
$serviceData->aclPrefix . "_update",
$serviceData->aclPrefix . "_delete",
],
];
if( empty($config->acl->rolesActions) )
$config->acl->rolesActions = $rolesActions;
else
$config->acl->rolesActions->{"project-admin"} = array_unique(array_merge($config->acl->rolesActions->{"project-admin"}, $rolesActions['project-admin']));
return $config;
} | Updating roles actions
@param $config
@param $serviceData
@return stdClass | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/HCNewService.php#L264-L281 |
interactivesolutions/honeycomb-scripts | src/app/commands/HCNewService.php | HCNewService.updateMenu | private function updateMenu(stdClass $config, stdClass $serviceData)
{
$menuItem = [
"route" => 'admin.' . $serviceData->serviceRouteName . '.index',
"translation" => $serviceData->translationsLocation . '.page_title',
"icon" => $serviceData->serviceIcon,
"aclPermission" => $serviceData->aclPrefix . "_list",
"priority" => 10,
];
$newMenu = true;
//TODO check if adminMenu exists if not create []
foreach ( $config->adminMenu as &$existingMenuItem ) {
if( $existingMenuItem->route == $menuItem['route'] ) {
if( $this->confirm('Duplicate Menu item found with ' . $existingMenuItem->path . ' path. Confirm override', 'no') ) {
$existingMenuItem = $menuItem;
$newMenu = false;
break;
} else {
$this->abort('Can not override existing configuration. Aborting...');
return null;
}
}
}
if ($newMenu)
$config->adminMenu = array_merge ($config->adminMenu, [$menuItem]);
return $config;
} | php | private function updateMenu(stdClass $config, stdClass $serviceData)
{
$menuItem = [
"route" => 'admin.' . $serviceData->serviceRouteName . '.index',
"translation" => $serviceData->translationsLocation . '.page_title',
"icon" => $serviceData->serviceIcon,
"aclPermission" => $serviceData->aclPrefix . "_list",
"priority" => 10,
];
$newMenu = true;
//TODO check if adminMenu exists if not create []
foreach ( $config->adminMenu as &$existingMenuItem ) {
if( $existingMenuItem->route == $menuItem['route'] ) {
if( $this->confirm('Duplicate Menu item found with ' . $existingMenuItem->path . ' path. Confirm override', 'no') ) {
$existingMenuItem = $menuItem;
$newMenu = false;
break;
} else {
$this->abort('Can not override existing configuration. Aborting...');
return null;
}
}
}
if ($newMenu)
$config->adminMenu = array_merge ($config->adminMenu, [$menuItem]);
return $config;
} | Updating menu parameter
@param $config
@param $serviceData
@return null | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/HCNewService.php#L300-L331 |
interactivesolutions/honeycomb-scripts | src/app/commands/HCNewService.php | HCNewService.updateFormManager | private function updateFormManager(stdClass $config, stdClass $serviceData)
{
$config->formData = json_decode(json_encode($config->formData), true);
if( ! isset($config->formData[$serviceData->formID]) )
$config->formData[$serviceData->formID] = $serviceData->formNameSpace . '\\' . $serviceData->formName;
return $config;
} | php | private function updateFormManager(stdClass $config, stdClass $serviceData)
{
$config->formData = json_decode(json_encode($config->formData), true);
if( ! isset($config->formData[$serviceData->formID]) )
$config->formData[$serviceData->formID] = $serviceData->formNameSpace . '\\' . $serviceData->formName;
return $config;
} | Updating form manager
@param $config
@param $serviceData
@return mixed | https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/HCNewService.php#L341-L349 |
Synapse-Cmf/synapse-cmf | src/Synapse/Cmf/Framework/Theme/Variation/Entity/Variation.php | Variation.getConfiguration | public function getConfiguration($namespace, $element, $key, $default = null)
{
$propertyPath = sprintf('[%s][%s][%s]', $namespace, $element, $key);
if ($value = $this->propertyAccessor->getValue($this->configurations, $propertyPath)) {
return $value;
}
return $default;
} | php | public function getConfiguration($namespace, $element, $key, $default = null)
{
$propertyPath = sprintf('[%s][%s][%s]', $namespace, $element, $key);
if ($value = $this->propertyAccessor->getValue($this->configurations, $propertyPath)) {
return $value;
}
return $default;
} | Return configuration value under given property path into given namespace or default if not readable.
@see PropertyAccessorInterface::getValue()
@param sgring $namespace
@param string $path
@param string $element
@param mixed $default
@return mixed | https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Framework/Theme/Variation/Entity/Variation.php#L46-L55 |
IftekherSunny/Planet-Framework | src/Sun/Session/Session.php | Session.startSession | protected function startSession()
{
if (session_status() == PHP_SESSION_NONE) {
session_start();
if(!$this->expireOnClose) {
setcookie('planet_session', session_id(), time() + ($this->expireTime * 60 ), '/', null, false, false);
}
}
} | php | protected function startSession()
{
if (session_status() == PHP_SESSION_NONE) {
session_start();
if(!$this->expireOnClose) {
setcookie('planet_session', session_id(), time() + ($this->expireTime * 60 ), '/', null, false, false);
}
}
} | To start session | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Session/Session.php#L54-L64 |
IftekherSunny/Planet-Framework | src/Sun/Session/Session.php | Session.create | public function create($name, $value = '')
{
if($this->app->config('session.encryption')) {
$_SESSION[$name] = $this->encrypter->encrypt($value);
} else {
$_SESSION[$name] = $value;
}
if (isset($_SESSION[$name])) {
return true;
}
return false;
} | php | public function create($name, $value = '')
{
if($this->app->config('session.encryption')) {
$_SESSION[$name] = $this->encrypter->encrypt($value);
} else {
$_SESSION[$name] = $value;
}
if (isset($_SESSION[$name])) {
return true;
}
return false;
} | To store session data
@param string $name
@param string $value
@return bool | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Session/Session.php#L74-L87 |
IftekherSunny/Planet-Framework | src/Sun/Session/Session.php | Session.get | public function get($name, $value = '')
{
if ($this->has($name)) {
if($this->app->config('session.encryption')) {
return $_SESSION[$name] ? $this->encrypter->decrypt($_SESSION[$name]) : $value;
} else {
return $_SESSION[$name] ? $_SESSION[$name] : $value;
}
}
if (!empty($value)) {
return $value;
}
return null;
} | php | public function get($name, $value = '')
{
if ($this->has($name)) {
if($this->app->config('session.encryption')) {
return $_SESSION[$name] ? $this->encrypter->decrypt($_SESSION[$name]) : $value;
} else {
return $_SESSION[$name] ? $_SESSION[$name] : $value;
}
}
if (!empty($value)) {
return $value;
}
return null;
} | To get session data
@param string $name
@param string $value
@return mixed | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Session/Session.php#L97-L112 |
IftekherSunny/Planet-Framework | src/Sun/Session/Session.php | Session.pull | public function pull($name, $value = '')
{
$value = $this->get($name, $value);
$this->delete($name);
return $value;
} | php | public function pull($name, $value = '')
{
$value = $this->get($name, $value);
$this->delete($name);
return $value;
} | To pull session data
@param string $name
@param string $value
@return mixed | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Session/Session.php#L156-L162 |
IftekherSunny/Planet-Framework | src/Sun/Session/Session.php | Session.push | public function push($name, $value)
{
$previousValue = $this->get($name, []);
$previousValue[] = $value;
return $this->create($name, $previousValue);
} | php | public function push($name, $value)
{
$previousValue = $this->get($name, []);
$previousValue[] = $value;
return $this->create($name, $previousValue);
} | To push session data into session array
@param string $name
@param string $value
@return bool | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Session/Session.php#L172-L179 |
IftekherSunny/Planet-Framework | src/Sun/Session/Session.php | Session.pop | public function pop($name)
{
$previousValue = $this->get($name);
$value = array_pop($previousValue);
$this->create($name, $previousValue);
return $value;
} | php | public function pop($name)
{
$previousValue = $this->get($name);
$value = array_pop($previousValue);
$this->create($name, $previousValue);
return $value;
} | To pop session data from session array
@param string $name
@return string | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Session/Session.php#L188-L197 |
IftekherSunny/Planet-Framework | src/Sun/Session/Session.php | Session.shift | public function shift($name)
{
$previousValue = $this->get($name);
$value = array_shift($previousValue);
$this->create($name, $previousValue);
return $value;
} | php | public function shift($name)
{
$previousValue = $this->get($name);
$value = array_shift($previousValue);
$this->create($name, $previousValue);
return $value;
} | To shift session data from session array
@param string $name
@return string | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Session/Session.php#L206-L215 |
pinguo/php-i18n | src/PhpMessageSource.php | PhpMessageSource.getMessageFilePath | protected function getMessageFilePath($category, $language)
{
$suffix = explode('.', $category)[1];
$messageFile = $this->basePath . "/$language/";
if (isset($this->fileMap[$suffix])) {
$messageFile .= $this->fileMap[$suffix];
} else {
$messageFile .= str_replace('\\', '/', $suffix) . '.php';
}
return $messageFile;
} | php | protected function getMessageFilePath($category, $language)
{
$suffix = explode('.', $category)[1];
$messageFile = $this->basePath . "/$language/";
if (isset($this->fileMap[$suffix])) {
$messageFile .= $this->fileMap[$suffix];
} else {
$messageFile .= str_replace('\\', '/', $suffix) . '.php';
}
return $messageFile;
} | 获取文件路径
@param string $category 分类
@param string $language 语言
@return string | https://github.com/pinguo/php-i18n/blob/2fc7c563dd3c8781d374c9e30f62bdb13d33dde8/src/PhpMessageSource.php#L90-L101 |
DBRisinajumi/d2company | controllers/CccfCustomFieldController.php | CccfCustomFieldController.actionCreate | public function actionCreate()
{
$model=new BaseCccfCustomField;
$scheme = get_class(Yii::app()->db->schema);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['BaseCccfCustomField']))
{
$model->attributes=$_POST['BaseCccfCustomField'];
if($model->validate()) {
$sql = 'ALTER TABLE '.BaseCccdCompanyData::model()->tableName().' ADD `'.$model->varname.'` ';
$sql .= $this->fieldType($model->field_type);
if (
$model->field_type!='TEXT'
&& $model->field_type!='DATE'
&& $model->field_type!='BOOL'
&& $model->field_type!='BLOB'
&& $model->field_type!='BINARY'
)
$sql .= '('.$model->field_size.')';
$sql .= ' NOT NULL ';
if ($model->field_type!='TEXT'&&$model->field_type!='BLOB'||$scheme!='CMysqlSchema') {
if ($model->default)
$sql .= " DEFAULT '".$model->default."'";
else
$sql .= ((
$model->field_type=='TEXT'
||$model->field_type=='VARCHAR'
||$model->field_type=='BLOB'
||$model->field_type=='BINARY'
)?" DEFAULT ''":(($model->field_type=='DATE')?" DEFAULT '0000-00-00'":" DEFAULT 0"));
}
$model->dbConnection->createCommand($sql)->execute();
$model->save();
$this->redirect(array('view','id'=>$model->id));
}
}
$this->render('create',array(
'model'=>$model,
));
} | php | public function actionCreate()
{
$model=new BaseCccfCustomField;
$scheme = get_class(Yii::app()->db->schema);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['BaseCccfCustomField']))
{
$model->attributes=$_POST['BaseCccfCustomField'];
if($model->validate()) {
$sql = 'ALTER TABLE '.BaseCccdCompanyData::model()->tableName().' ADD `'.$model->varname.'` ';
$sql .= $this->fieldType($model->field_type);
if (
$model->field_type!='TEXT'
&& $model->field_type!='DATE'
&& $model->field_type!='BOOL'
&& $model->field_type!='BLOB'
&& $model->field_type!='BINARY'
)
$sql .= '('.$model->field_size.')';
$sql .= ' NOT NULL ';
if ($model->field_type!='TEXT'&&$model->field_type!='BLOB'||$scheme!='CMysqlSchema') {
if ($model->default)
$sql .= " DEFAULT '".$model->default."'";
else
$sql .= ((
$model->field_type=='TEXT'
||$model->field_type=='VARCHAR'
||$model->field_type=='BLOB'
||$model->field_type=='BINARY'
)?" DEFAULT ''":(($model->field_type=='DATE')?" DEFAULT '0000-00-00'":" DEFAULT 0"));
}
$model->dbConnection->createCommand($sql)->execute();
$model->save();
$this->redirect(array('view','id'=>$model->id));
}
}
$this->render('create',array(
'model'=>$model,
));
} | Creates a new model.
If creation is successful, the browser will be redirected to the 'view' page. | https://github.com/DBRisinajumi/d2company/blob/20df0db96ac2c8e73471c4bab7d487b67ef4ed0a/controllers/CccfCustomFieldController.php#L63-L108 |
DBRisinajumi/d2company | controllers/CccfCustomFieldController.php | CccfCustomFieldController.actionUpdate | public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['BaseCccfCustomField']))
{
$model->attributes=$_POST['BaseCccfCustomField'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
} | php | public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['BaseCccfCustomField']))
{
$model->attributes=$_POST['BaseCccfCustomField'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
} | Updates a particular model.
If update is successful, the browser will be redirected to the 'view' page.
@param integer $id the ID of the model to be updated | https://github.com/DBRisinajumi/d2company/blob/20df0db96ac2c8e73471c4bab7d487b67ef4ed0a/controllers/CccfCustomFieldController.php#L115-L132 |
DBRisinajumi/d2company | controllers/CccfCustomFieldController.php | CccfCustomFieldController.actionDelete | public function actionDelete($id)
{
//$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
//if(!isset($_GET['ajax']))
// $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
$model = $this->loadModel($id);
$sql = 'ALTER TABLE '.BaseCccdCompanyData::model()->tableName().' DROP `'.$model->varname.'`';
if ($model->dbConnection->createCommand($sql)->execute()) {
$model->delete();
}
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_POST['ajax']))
$this->redirect(array('admin'));
else
throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
} | php | public function actionDelete($id)
{
//$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
//if(!isset($_GET['ajax']))
// $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
$model = $this->loadModel($id);
$sql = 'ALTER TABLE '.BaseCccdCompanyData::model()->tableName().' DROP `'.$model->varname.'`';
if ($model->dbConnection->createCommand($sql)->execute()) {
$model->delete();
}
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_POST['ajax']))
$this->redirect(array('admin'));
else
throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
} | Deletes a particular model.
If deletion is successful, the browser will be redirected to the 'admin' page.
@param integer $id the ID of the model to be deleted | https://github.com/DBRisinajumi/d2company/blob/20df0db96ac2c8e73471c4bab7d487b67ef4ed0a/controllers/CccfCustomFieldController.php#L139-L165 |
DBRisinajumi/d2company | controllers/CccfCustomFieldController.php | CccfCustomFieldController.loadModel | public function loadModel($id)
{
$model=BaseCccfCustomField::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
} | php | public function loadModel($id)
{
$model=BaseCccfCustomField::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
} | Returns the data model based on the primary key given in the GET variable.
If the data model is not found, an HTTP exception will be raised.
@param integer $id the ID of the model to be loaded
@return BaseCccfCustomField the loaded model
@throws CHttpException | https://github.com/DBRisinajumi/d2company/blob/20df0db96ac2c8e73471c4bab7d487b67ef4ed0a/controllers/CccfCustomFieldController.php#L200-L206 |
yii2lab/yii2-rbac | src/domain/rules/IsWritableRule.php | IsWritableRule.toArray | private function toArray($params) {
if(is_array($params)) {
return $params;
}
if(is_object($params)) {
return ArrayHelper::toArray($params);
}
throw new InvalidMethodParameterException;
} | php | private function toArray($params) {
if(is_array($params)) {
return $params;
}
if(is_object($params)) {
return ArrayHelper::toArray($params);
}
throw new InvalidMethodParameterException;
} | @param array|BaseEntity $params
@return array
@throws InvalidMethodParameterException | https://github.com/yii2lab/yii2-rbac/blob/e72ac0359af660690c161451f864208b2d20919d/src/domain/rules/IsWritableRule.php#L41-L49 |
io-digital/repo | src/Models/Concrete/_AbstractEloquentRepository.php | AbstractEloquentRepository.findBy | public function findBy($attribute, $value, $columns = ['*'])
{
return $this->model->where($attribute, '=', $value)->first($columns);
} | php | public function findBy($attribute, $value, $columns = ['*'])
{
return $this->model->where($attribute, '=', $value)->first($columns);
} | $this->model->findBy('title', $title); | https://github.com/io-digital/repo/blob/5c3ec535265edfb963ce6fcdeacb8c69e4d6267c/src/Models/Concrete/_AbstractEloquentRepository.php#L38-L41 |
io-digital/repo | src/Models/Concrete/_AbstractEloquentRepository.php | AbstractEloquentRepository.findAllBy | public function findAllBy($attribute, $value, $columns = ['*'])
{
return $this->model->where($attribute, '=', $value)->get($columns);
} | php | public function findAllBy($attribute, $value, $columns = ['*'])
{
return $this->model->where($attribute, '=', $value)->get($columns);
} | $this->model->findAllBy('author_id', $author_id); | https://github.com/io-digital/repo/blob/5c3ec535265edfb963ce6fcdeacb8c69e4d6267c/src/Models/Concrete/_AbstractEloquentRepository.php#L47-L50 |
php-comp/lock | src/MemcacheLock.php | MemcacheLock.lock | public function lock($key, $timeout = self::EXPIRE): bool
{
$wait = 20000;
$totalWait = 0;
$time = $timeout * 1000000;
$key = self::PREFIX . $key;
while ($totalWait < $time && false === $this->mem->add($key, 1, $timeout)) {
usleep($wait);
$totalWait += $wait;
}
if ($totalWait >= $time) {
throw new \RuntimeException('cannot get lock for waiting ' . $timeout . 's.', __LINE__);
}
return true;
} | php | public function lock($key, $timeout = self::EXPIRE): bool
{
$wait = 20000;
$totalWait = 0;
$time = $timeout * 1000000;
$key = self::PREFIX . $key;
while ($totalWait < $time && false === $this->mem->add($key, 1, $timeout)) {
usleep($wait);
$totalWait += $wait;
}
if ($totalWait >= $time) {
throw new \RuntimeException('cannot get lock for waiting ' . $timeout . 's.', __LINE__);
}
return true;
} | {@inheritdoc}
@throws \RuntimeException | https://github.com/php-comp/lock/blob/fe84c9795006201adc2723e31e20a79c1d0515b6/src/MemcacheLock.php#L43-L60 |
Elephant418/Staq | src/Staq/Autoloader.php | Autoloader.autoload | public function autoload($class)
{
if (!static::$initialized) {
$this->initialize();
if ($this->classExists($class)) {
return TRUE;
}
}
if (\Staq\Util::isStack($class)) {
$this->loadStackClass($class);
} else if (\Staq\Util::isParentStack($class)) {
$this->loadStackParentClass($class);
}
} | php | public function autoload($class)
{
if (!static::$initialized) {
$this->initialize();
if ($this->classExists($class)) {
return TRUE;
}
}
if (\Staq\Util::isStack($class)) {
$this->loadStackClass($class);
} else if (\Staq\Util::isParentStack($class)) {
$this->loadStackParentClass($class);
}
} | /* TOP-LEVEL AUTOLOAD
*********************************************************************** | https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Autoloader.php#L41-L54 |
Elephant418/Staq | src/Staq/Autoloader.php | Autoloader.loadStackClass | protected function loadStackClass($class)
{
$stackQuery = \Staq\Util::getStackQuery($class);
while ($stackQuery) {
foreach (array_keys($this->extensions) as $extensionNamespace) {
if ($realClass = $this->getRealClass($stackQuery, $extensionNamespace)) {
$this->createClassAlias($class, $realClass);
return TRUE;
}
}
$stackQuery = \Staq\Util::popStackQuery($stackQuery);
}
$this->createClassEmpty($class);
} | php | protected function loadStackClass($class)
{
$stackQuery = \Staq\Util::getStackQuery($class);
while ($stackQuery) {
foreach (array_keys($this->extensions) as $extensionNamespace) {
if ($realClass = $this->getRealClass($stackQuery, $extensionNamespace)) {
$this->createClassAlias($class, $realClass);
return TRUE;
}
}
$stackQuery = \Staq\Util::popStackQuery($stackQuery);
}
$this->createClassEmpty($class);
} | /* FILE CLASS MANAGEMENT
*********************************************************************** | https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Autoloader.php#L59-L73 |
Elephant418/Staq | src/Staq/Autoloader.php | Autoloader.getRealClass | protected function getRealClass($stack, $extensionNamespace)
{
$stackPath = \Staq\Util::convertNamespaceToPath($stack);
$absolutePath = realpath($this->extensions[$extensionNamespace] . '/Stack/' . $stackPath . '.php');
if (is_file($absolutePath)) {
$realClass = $extensionNamespace . '\\Stack\\' . $stack;
return $realClass;
}
} | php | protected function getRealClass($stack, $extensionNamespace)
{
$stackPath = \Staq\Util::convertNamespaceToPath($stack);
$absolutePath = realpath($this->extensions[$extensionNamespace] . '/Stack/' . $stackPath . '.php');
if (is_file($absolutePath)) {
$realClass = $extensionNamespace . '\\Stack\\' . $stack;
return $realClass;
}
} | "stack" is now a part of the namespace, there is no burgers left at my bakery | https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Autoloader.php#L76-L84 |
schpill/thin | src/Filter/Striptags.php | Striptags.filter | public function filter($value)
{
// start by stripping the comments, if necessary
if(!$this->allowComments) {
$value = preg_replace('/<!\-\-.*\-\->/U', '', $value);
}
// strip unallowed tags
$allowed = '';
foreach($this->allowedTags as $tag) {
$allowed .= "<{$tag}>";
}
$value = strip_tags($value, $allowed);
// strip unallowed attributes - only if there are allowed tags,
// otherwise all attributes have already been removed with the tags
if(!empty($this->allowedTags)) {
$allowed = $this->allowedAttributes;
do {
$old = $value;
$value = preg_replace_callback('/<[a-zA-Z]+ *(([a-zA-Z_:][\-a-zA-Z0-9_:\.]+) *=.*["\'].*["\']).*>/U', function($matches) use($allowed) {
if(in_array($matches[2], $allowed)) {
return $matches[0];
} else {
return repl(' ' . $matches[1], '', $matches[0]);
}
}, $value);
} while($old != $value);
}
// we're left with the filtered value
return $value;
} | php | public function filter($value)
{
// start by stripping the comments, if necessary
if(!$this->allowComments) {
$value = preg_replace('/<!\-\-.*\-\->/U', '', $value);
}
// strip unallowed tags
$allowed = '';
foreach($this->allowedTags as $tag) {
$allowed .= "<{$tag}>";
}
$value = strip_tags($value, $allowed);
// strip unallowed attributes - only if there are allowed tags,
// otherwise all attributes have already been removed with the tags
if(!empty($this->allowedTags)) {
$allowed = $this->allowedAttributes;
do {
$old = $value;
$value = preg_replace_callback('/<[a-zA-Z]+ *(([a-zA-Z_:][\-a-zA-Z0-9_:\.]+) *=.*["\'].*["\']).*>/U', function($matches) use($allowed) {
if(in_array($matches[2], $allowed)) {
return $matches[0];
} else {
return repl(' ' . $matches[1], '', $matches[0]);
}
}, $value);
} while($old != $value);
}
// we're left with the filtered value
return $value;
} | Strip the undesired HTML markup
@param string $value The input string with HTML markup
@return string Filtered string | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Filter/Striptags.php#L33-L65 |
schpill/thin | src/Filter/Striptags.php | Striptags.setAllowedTags | public function setAllowedTags($tags)
{
if(!is_array($tags)) {
$tags = [$tags];
}
$this->allowedTags = $tags;
return $this;
} | php | public function setAllowedTags($tags)
{
if(!is_array($tags)) {
$tags = [$tags];
}
$this->allowedTags = $tags;
return $this;
} | Set the HTML tags that should be left in the input string
@param array|string $tags The allowed tags: either an array or a string with a single tag.
@return \Thin\Filter\StripTags Provides a fluent interface | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Filter/Striptags.php#L76-L83 |
schpill/thin | src/Filter/Striptags.php | Striptags.setAllowedAttributes | public function setAllowedAttributes($attributes)
{
if(!is_array($attributes)) {
$attributes = [$attributes];
}
$this->allowedAttributes = $attributes;
return $this;
} | php | public function setAllowedAttributes($attributes)
{
if(!is_array($attributes)) {
$attributes = [$attributes];
}
$this->allowedAttributes = $attributes;
return $this;
} | Set the HTML attributes that should be left in the unstripped tags in the input string
@param array $attributes The allowed attributes: either an array or a string with a single attribute.
@return \Thin\Filter\StripTags Provides a fluent interface | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Filter/Striptags.php#L94-L101 |
pinguo/php-i18n | src/I18N.php | I18N.getInstance | public static function getInstance(array $config)
{
if (empty($config)) {
throw new \Exception('i18n configuration can not be empty.');
}
if (self::$i18n === null) {
self::$i18n = new self($config);
}
return self::$i18n;
} | php | public static function getInstance(array $config)
{
if (empty($config)) {
throw new \Exception('i18n configuration can not be empty.');
}
if (self::$i18n === null) {
self::$i18n = new self($config);
}
return self::$i18n;
} | 实例化
@param array $config 配置,如:
[
'class' => 'PhpMessageSource',
'sourceLanguage' => 'en_us',
'basePath' => '<DIR>/Languages', // 翻译配置文件路径
'fileMap' => [
'common' => 'common.php',
'error' => 'error.php'
]
] | https://github.com/pinguo/php-i18n/blob/2fc7c563dd3c8781d374c9e30f62bdb13d33dde8/src/I18N.php#L38-L48 |
pinguo/php-i18n | src/I18N.php | I18N.t | public static function t($category, $message, $params = [], $language = null)
{
if (self::$i18n === null) {
throw new \Exception('Has not instantiated i18n.');
}
if (strpos($category, '.') === false) {
$category = 'app.' . $category;
}
return self::$i18n->translate($category, $message, $params, $language ?: 'en_us');
} | php | public static function t($category, $message, $params = [], $language = null)
{
if (self::$i18n === null) {
throw new \Exception('Has not instantiated i18n.');
}
if (strpos($category, '.') === false) {
$category = 'app.' . $category;
}
return self::$i18n->translate($category, $message, $params, $language ?: 'en_us');
} | 多语言翻译,使用方法如:
1) I18N::t('common', 'hot', [], 'zh_cn'); // 默认为 app.common
2) I18N::t('app.common', 'hot', [], 'zh_cn'); // 结果同 1)
3) I18N::t('msg.a', 'hello', ['{foo}' => 'bar', '{key}' => 'val'], 'ja_jp');
@param string $category
@param string $message
@param array $params
@param null | string $language
@return mixed | https://github.com/pinguo/php-i18n/blob/2fc7c563dd3c8781d374c9e30f62bdb13d33dde8/src/I18N.php#L69-L78 |
pinguo/php-i18n | src/I18N.php | I18N.format | public function format($message, $params, $language)
{
$params = (array)$params;
if ($params === []) {
return $message;
}
if (preg_match('~{\s*[\d\w]+\s*,~u', $message)) {
$formatter = $this->getMessageFormatter();
$result = $formatter->format($message, $params, $language);
if ($result === false) {
// $errorMessage = $formatter->getErrorMessage();
return $message;
} else {
return $result;
}
}
$p = [];
foreach ($params as $name => $value) {
$p['{' . $name . '}'] = $value;
}
return strtr($message, $p);
} | php | public function format($message, $params, $language)
{
$params = (array)$params;
if ($params === []) {
return $message;
}
if (preg_match('~{\s*[\d\w]+\s*,~u', $message)) {
$formatter = $this->getMessageFormatter();
$result = $formatter->format($message, $params, $language);
if ($result === false) {
// $errorMessage = $formatter->getErrorMessage();
return $message;
} else {
return $result;
}
}
$p = [];
foreach ($params as $name => $value) {
$p['{' . $name . '}'] = $value;
}
return strtr($message, $p);
} | Formats a message using [[MessageFormatter]].
@param string $message the message to be formatted.
@param array $params the parameters that will be used to replace the corresponding placeholders in the message.
@param string $language the language code (e.g. `en-US`, `en`).
@return string the formatted message. | https://github.com/pinguo/php-i18n/blob/2fc7c563dd3c8781d374c9e30f62bdb13d33dde8/src/I18N.php#L137-L161 |
pinguo/php-i18n | src/I18N.php | I18N.getMessageSource | public function getMessageSource($category)
{
$prefix = explode('.', $category)[0];
if (isset($this->translations[$prefix])) {
$source = $this->translations[$prefix];
if ($source instanceof MessageSource) {
return $source;
} else {
return $this->translations[$prefix] = static::createObject($source);
}
}
throw new \Exception("Unable to locate message source for category '$category'.");
} | php | public function getMessageSource($category)
{
$prefix = explode('.', $category)[0];
if (isset($this->translations[$prefix])) {
$source = $this->translations[$prefix];
if ($source instanceof MessageSource) {
return $source;
} else {
return $this->translations[$prefix] = static::createObject($source);
}
}
throw new \Exception("Unable to locate message source for category '$category'.");
} | Returns the message source for the given category.
@param string $category the category name, eg. app.errno
@return MessageSource the message source for the given category.
@throws InvalidConfigException if there is no message source available for the specified category. | https://github.com/pinguo/php-i18n/blob/2fc7c563dd3c8781d374c9e30f62bdb13d33dde8/src/I18N.php#L199-L212 |
pinguo/php-i18n | src/I18N.php | I18N.createObject | public static function createObject($type, array $params = [])
{
if (is_string($type)) {
return new $type;
} elseif (is_array($type)) {
$class = '\\PG\\I18N\\' . ($type['class'] ?? 'PhpMessageSource');
unset($type['class']);
$clazz = new $class;
foreach ($type as $prop => $val) {
$clazz->$prop = $val;
}
return $clazz;
}
throw new \Exception('Unsupported configuration type: ' . gettype($type));
} | php | public static function createObject($type, array $params = [])
{
if (is_string($type)) {
return new $type;
} elseif (is_array($type)) {
$class = '\\PG\\I18N\\' . ($type['class'] ?? 'PhpMessageSource');
unset($type['class']);
$clazz = new $class;
foreach ($type as $prop => $val) {
$clazz->$prop = $val;
}
return $clazz;
}
throw new \Exception('Unsupported configuration type: ' . gettype($type));
} | 创建对象
@param mixed $type
@param array $params
@return mixed
@throws \Exception | https://github.com/pinguo/php-i18n/blob/2fc7c563dd3c8781d374c9e30f62bdb13d33dde8/src/I18N.php#L221-L236 |
phPoirot/Stream | Streamable.php | Streamable.pipeTo | function pipeTo(iStreamable $destStream, $maxByte = null, $offset = null)
{
$this->_assertStreamAlive();
$maxByte = ($maxByte === null)
?
(
($this->getBuffer() === null) ? -1 : $this->getBuffer()
)
: $maxByte;
if ($offset !== null)
$this->seek($offset);
## copy data
#
$data = $this->read($maxByte);
$destStream->write($data);
$this->_resetTransCount($destStream->getTransCount());
return $this;
/*
$buffBytes = 8192; $totalBytes = 0;
while ('' !== $data = $this->read($buffBytes))
{
$destStream->write($data);
$readBytes = $this->getTransCount();
$totalBytes+=$readBytes;
if ($maxByte > 0)
$buffBytes = ($maxByte - $readBytes < 1024)
? $maxByte - $readBytes
: 1024;
}
$this->_resetTransCount($totalBytes);
return $this;
*/
} | php | function pipeTo(iStreamable $destStream, $maxByte = null, $offset = null)
{
$this->_assertStreamAlive();
$maxByte = ($maxByte === null)
?
(
($this->getBuffer() === null) ? -1 : $this->getBuffer()
)
: $maxByte;
if ($offset !== null)
$this->seek($offset);
## copy data
#
$data = $this->read($maxByte);
$destStream->write($data);
$this->_resetTransCount($destStream->getTransCount());
return $this;
/*
$buffBytes = 8192; $totalBytes = 0;
while ('' !== $data = $this->read($buffBytes))
{
$destStream->write($data);
$readBytes = $this->getTransCount();
$totalBytes+=$readBytes;
if ($maxByte > 0)
$buffBytes = ($maxByte - $readBytes < 1024)
? $maxByte - $readBytes
: 1024;
}
$this->_resetTransCount($totalBytes);
return $this;
*/
} | Copies Data From One Stream To Another
- If maxlength is not specified,
all remaining content in source will be copied
@param iStreamable $destStream The destination stream
@param null $maxByte Maximum bytes to copy
@param int $offset The offset where to start to copy data, null mean current
@return $this | https://github.com/phPoirot/Stream/blob/db448ee0528c2a5b07c594b8a30e2543fbc15f57/Streamable.php#L100-L144 |
phPoirot/Stream | Streamable.php | Streamable.read | function read($inByte = null)
{
$this->_assertReadable();
$inByte = ($inByte === null)
?
(
($this->getBuffer() === null) ? -1 : $this->getBuffer()
)
: $inByte;
$stream = $this->resource()->getRHandler();
$data = stream_get_contents($stream, $inByte);
if (false === $data)
throw new \RuntimeException('Cannot read stream.');
if (function_exists('mb_strlen'))
$transCount = mb_strlen($data, '8bit');
else
$transCount = strlen($data);
$this->_resetTransCount($transCount);
return $data;
} | php | function read($inByte = null)
{
$this->_assertReadable();
$inByte = ($inByte === null)
?
(
($this->getBuffer() === null) ? -1 : $this->getBuffer()
)
: $inByte;
$stream = $this->resource()->getRHandler();
$data = stream_get_contents($stream, $inByte);
if (false === $data)
throw new \RuntimeException('Cannot read stream.');
if (function_exists('mb_strlen'))
$transCount = mb_strlen($data, '8bit');
else
$transCount = strlen($data);
$this->_resetTransCount($transCount);
return $data;
} | Read Data From Stream
- if $inByte argument not set, read entire stream
@param int $inByte Read Data in byte
@throws \Exception Error On Read Data
@return string | https://github.com/phPoirot/Stream/blob/db448ee0528c2a5b07c594b8a30e2543fbc15f57/Streamable.php#L156-L180 |
phPoirot/Stream | Streamable.php | Streamable.readLine | function readLine($ending = "\n", $inByte = null)
{
$this->_assertReadable();
$inByte = ($inByte === null)
?
(
// buffer must be greater than zero
(!$this->getBuffer()) ? 1024 : $this->getBuffer()
)
: $inByte;
$stream = $this->resource()->getRHandler();
if ($ending == "\r" || $ending == "\n" || $ending == "\r\n") {
// php7 stream_get_line is too slow!!!! so i use default fgets instead in this case
$data = fgets($stream, $inByte);
if (false !== $i = strpos($data, $ending))
## found ending in string
$data = substr($data, 0, $i);
}
else
// does not return the delimiter itself
$data = stream_get_line($stream, $inByte, $ending);
if (false === $data)
return null;
if (function_exists('mb_strlen'))
$transCount = mb_strlen($data, '8bit');
else
$transCount = strlen($data);
$this->_resetTransCount($transCount);
return $data;
} | php | function readLine($ending = "\n", $inByte = null)
{
$this->_assertReadable();
$inByte = ($inByte === null)
?
(
// buffer must be greater than zero
(!$this->getBuffer()) ? 1024 : $this->getBuffer()
)
: $inByte;
$stream = $this->resource()->getRHandler();
if ($ending == "\r" || $ending == "\n" || $ending == "\r\n") {
// php7 stream_get_line is too slow!!!! so i use default fgets instead in this case
$data = fgets($stream, $inByte);
if (false !== $i = strpos($data, $ending))
## found ending in string
$data = substr($data, 0, $i);
}
else
// does not return the delimiter itself
$data = stream_get_line($stream, $inByte, $ending);
if (false === $data)
return null;
if (function_exists('mb_strlen'))
$transCount = mb_strlen($data, '8bit');
else
$transCount = strlen($data);
$this->_resetTransCount($transCount);
return $data;
} | Gets line from stream resource up to a given delimiter
Reading ends when length bytes have been read,
when the string specified by ending is found
(which is not included in the return value),
or on EOF (whichever comes first)
! does not return the ending delimiter itself
@param string $ending
@param int $inByte
@return string|null | https://github.com/phPoirot/Stream/blob/db448ee0528c2a5b07c594b8a30e2543fbc15f57/Streamable.php#L197-L232 |
phPoirot/Stream | Streamable.php | Streamable.write | function write($content, $inByte = null)
{
$this->_assertWritable();
$stream = $this->resource()->getRHandler();
$inByte = ($inByte === null)
? $this->getBuffer()
: $inByte;
$content = (string) $content;
if (null === $inByte)
$ret = fwrite($stream, $content);
else
$ret = fwrite($stream, $content, $inByte);
if (false === $ret)
throw new \RuntimeException('Cannot write on stream.');
$transCount = $inByte;
if ($transCount === null) {
if (function_exists('mb_strlen'))
$transCount = mb_strlen($content, '8bit');
else
$transCount = strlen($content);
}
$this->_resetTransCount($transCount);
return $this;
} | php | function write($content, $inByte = null)
{
$this->_assertWritable();
$stream = $this->resource()->getRHandler();
$inByte = ($inByte === null)
? $this->getBuffer()
: $inByte;
$content = (string) $content;
if (null === $inByte)
$ret = fwrite($stream, $content);
else
$ret = fwrite($stream, $content, $inByte);
if (false === $ret)
throw new \RuntimeException('Cannot write on stream.');
$transCount = $inByte;
if ($transCount === null) {
if (function_exists('mb_strlen'))
$transCount = mb_strlen($content, '8bit');
else
$transCount = strlen($content);
}
$this->_resetTransCount($transCount);
return $this;
} | Writes the contents of string to the file stream
@param string $content The string that is to be written
@param int $inByte Writing will stop after length bytes
have been written or the end of string
is reached
@return $this | https://github.com/phPoirot/Stream/blob/db448ee0528c2a5b07c594b8a30e2543fbc15f57/Streamable.php#L244-L274 |
phPoirot/Stream | Streamable.php | Streamable.__write_stream | protected function __write_stream($rHandler, $content)
{
for ($written = 0; $written < strlen($content); $written += $fwrite) {
$fwrite = fwrite($rHandler, substr($content, $written));
if ($fwrite === false)
return $written;
}
return $written;
} | php | protected function __write_stream($rHandler, $content)
{
for ($written = 0; $written < strlen($content); $written += $fwrite) {
$fwrite = fwrite($rHandler, substr($content, $written));
if ($fwrite === false)
return $written;
}
return $written;
} | Note: Writing to a network stream may end before the whole string
is written. Return value of fwrite() may be checked. | https://github.com/phPoirot/Stream/blob/db448ee0528c2a5b07c594b8a30e2543fbc15f57/Streamable.php#L280-L289 |
phPoirot/Stream | Streamable.php | Streamable.sendData | function sendData($data, $flags = null)
{
$rHandler = $this->resource()->getRHandler();
if ($flags === null) {
if ($this->resource()->meta()->getStreamType() == 'udp_socket')
// STREAM_OOB data not provided on udp sockets
$flags = STREAM_PEEK;
else
$flags = STREAM_SOCK_RDM;
}
$ret = @stream_socket_sendto($rHandler, $data, $flags);
if ($ret == -1) {
$lerror = error_get_last();
throw new \RuntimeException(sprintf(
'Cannot send data on stream, %s.',
$lerror['message']
));
}
$this->_resetTransCount($ret);
return $this;
} | php | function sendData($data, $flags = null)
{
$rHandler = $this->resource()->getRHandler();
if ($flags === null) {
if ($this->resource()->meta()->getStreamType() == 'udp_socket')
// STREAM_OOB data not provided on udp sockets
$flags = STREAM_PEEK;
else
$flags = STREAM_SOCK_RDM;
}
$ret = @stream_socket_sendto($rHandler, $data, $flags);
if ($ret == -1) {
$lerror = error_get_last();
throw new \RuntimeException(sprintf(
'Cannot send data on stream, %s.',
$lerror['message']
));
}
$this->_resetTransCount($ret);
return $this;
} | Sends the specified data through the socket,
whether it is connected or not
@param string $data The data to be sent
@param int|null $flags Provides a RDM (Reliably-delivered messages) socket
The value of flags can be any combination of the following:
- STREAM_SOCK_RDM
- STREAM_PEEK
- STREAM_OOB process OOB (out-of-band) data
- null auto choose the value
@return $this | https://github.com/phPoirot/Stream/blob/db448ee0528c2a5b07c594b8a30e2543fbc15f57/Streamable.php#L305-L331 |
phPoirot/Stream | Streamable.php | Streamable.seek | function seek($offset, $whence = SEEK_SET)
{
$this->_assertSeekable();
$stream = $this->resource()->getRHandler();
if (-1 === fseek($stream, $offset, $whence))
throw new \RuntimeException('Cannot seek on stream');
return $this;
} | php | function seek($offset, $whence = SEEK_SET)
{
$this->_assertSeekable();
$stream = $this->resource()->getRHandler();
if (-1 === fseek($stream, $offset, $whence))
throw new \RuntimeException('Cannot seek on stream');
return $this;
} | Move the file pointer to a new position
- The new position, measured in bytes from the beginning of the file,
is obtained by adding $offset to the position specified by $whence.
! php doesn't support seek/rewind on non-local streams
we can using temp/cache piped stream.
! If you have opened the file in append ("a" or "a+") mode,
any data you write to the file will always be appended,
regardless of the file position.
@param int $offset
@param int $whence Accepted values are:
- SEEK_SET - Set position equal to $offset bytes.
- SEEK_CUR - Set position to current location plus $offset.
- SEEK_END - Set position to end-of-file plus $offset.
@return $this | https://github.com/phPoirot/Stream/blob/db448ee0528c2a5b07c594b8a30e2543fbc15f57/Streamable.php#L391-L401 |
phPoirot/Stream | Streamable.php | Streamable.rewind | function rewind()
{
$this->_assertSeekable();
$stream = $this->resource()->getRHandler();
if (false === rewind($stream))
throw new \RuntimeException('Cannot rewind stream');
return $this;
} | php | function rewind()
{
$this->_assertSeekable();
$stream = $this->resource()->getRHandler();
if (false === rewind($stream))
throw new \RuntimeException('Cannot rewind stream');
return $this;
} | Move the file pointer to the beginning of the stream
! php doesn't support seek/rewind on non-local streams
we can using temp/cache piped stream.
! If you have opened the file in append ("a" or "a+") mode,
any data you write to the file will always be appended,
regardless of the file position.
@return $this | https://github.com/phPoirot/Stream/blob/db448ee0528c2a5b07c594b8a30e2543fbc15f57/Streamable.php#L429-L439 |
phPoirot/Stream | Streamable.php | Streamable.isEOF | function isEOF()
{
if ($this->resource()->meta()->getWrapperType())
// Wrapper Stream ...
return $this->resource()->meta()->isReachedEnd();
return feof($this->resource()->getRHandler());
} | php | function isEOF()
{
if ($this->resource()->meta()->getWrapperType())
// Wrapper Stream ...
return $this->resource()->meta()->isReachedEnd();
return feof($this->resource()->getRHandler());
} | Is Stream Positioned At The End?
@return boolean | https://github.com/phPoirot/Stream/blob/db448ee0528c2a5b07c594b8a30e2543fbc15f57/Streamable.php#L446-L453 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.