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
|
---|---|---|---|---|---|---|---|
IftekherSunny/Planet-Framework | src/Sun/Filesystem/Filesystem.php | Filesystem.files | public function files($directoryName)
{
if (!$this->isDir($directoryName)) {
throw new FileNotFoundException('Directory not found in the path [ ' . $directoryName . ' ].');
}
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($directoryName,
RecursiveDirectoryIterator::SKIP_DOTS
)
);
return array_filter(iterator_to_array($files), 'is_file');
} | php | public function files($directoryName)
{
if (!$this->isDir($directoryName)) {
throw new FileNotFoundException('Directory not found in the path [ ' . $directoryName . ' ].');
}
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($directoryName,
RecursiveDirectoryIterator::SKIP_DOTS
)
);
return array_filter(iterator_to_array($files), 'is_file');
} | To get all files in a directory
@param string $directoryName
@return array
@throws FileNotFoundException | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Filesystem/Filesystem.php#L165-L178 |
IftekherSunny/Planet-Framework | src/Sun/Filesystem/Filesystem.php | Filesystem.directories | public function directories($directoryName)
{
if (!$this->isDir($directoryName)) {
throw new FileNotFoundException('Directory not found in the path [ ' . $directoryName . ' ].');
}
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($directoryName,
RecursiveDirectoryIterator::CURRENT_AS_FILEINFO)
);
$directories = [];
foreach($iterator as $file) {
if($file->isDir()) {
if( !(substr($file,-2) === '..')) {
$directories[] = trim($file,'.');
}
}
}
array_shift($directories);
return $directories;
} | php | public function directories($directoryName)
{
if (!$this->isDir($directoryName)) {
throw new FileNotFoundException('Directory not found in the path [ ' . $directoryName . ' ].');
}
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($directoryName,
RecursiveDirectoryIterator::CURRENT_AS_FILEINFO)
);
$directories = [];
foreach($iterator as $file) {
if($file->isDir()) {
if( !(substr($file,-2) === '..')) {
$directories[] = trim($file,'.');
}
}
}
array_shift($directories);
return $directories;
} | To get all directories in a directory
@param string $directoryName
@return array
@throws FileNotFoundException | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Filesystem/Filesystem.php#L188-L212 |
IftekherSunny/Planet-Framework | src/Sun/Filesystem/Filesystem.php | Filesystem.cleanDirectory | public function cleanDirectory($directoryName, $deleteRootDirectory = false)
{
if(is_dir($directoryName)){
$files = glob( $directoryName . '/*', GLOB_NOSORT );
foreach( $files as $file )
{
$this->cleanDirectory( $file, true );
}
if(file_exists($directoryName) && ($deleteRootDirectory == true)) {
@rmdir( $directoryName );
}
} elseif(is_file($directoryName)) {
@unlink( $directoryName );
}
if(file_exists($directoryName)) {
return true;
}
return false;
} | php | public function cleanDirectory($directoryName, $deleteRootDirectory = false)
{
if(is_dir($directoryName)){
$files = glob( $directoryName . '/*', GLOB_NOSORT );
foreach( $files as $file )
{
$this->cleanDirectory( $file, true );
}
if(file_exists($directoryName) && ($deleteRootDirectory == true)) {
@rmdir( $directoryName );
}
} elseif(is_file($directoryName)) {
@unlink( $directoryName );
}
if(file_exists($directoryName)) {
return true;
}
return false;
} | To clean a directory
@param string $directoryName
@param bool $deleteRootDirectory
@return bool | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Filesystem/Filesystem.php#L250-L272 |
K-Phoen/gaufrette-extras-bundle | DependencyInjection/Factory/PrefixResolverFactory.php | PrefixResolverFactory.create | public function create(ContainerBuilder $container, $id, array $config)
{
$definition = new Definition('%gaufrette.resolver.prefix.class%', array($config['path']));
$definition->setPublic(false);
$container->setDefinition($id, $definition);
} | php | public function create(ContainerBuilder $container, $id, array $config)
{
$definition = new Definition('%gaufrette.resolver.prefix.class%', array($config['path']));
$definition->setPublic(false);
$container->setDefinition($id, $definition);
} | {@inheritDoc} | https://github.com/K-Phoen/gaufrette-extras-bundle/blob/3f05779179117d5649184164544e1f22de28d706/DependencyInjection/Factory/PrefixResolverFactory.php#L15-L21 |
phpalchemy/phpalchemy | Alchemy/Component/DiContainer/DiContainer.php | DiContainer.offsetSet | public function offsetSet($id, $value)
{
if (in_array($id, $this->protected)) {
//TODO need implements a logger to store this modifications attempts
return;
}
$this->container[$id] = $value;
} | php | public function offsetSet($id, $value)
{
if (in_array($id, $this->protected)) {
//TODO need implements a logger to store this modifications attempts
return;
}
$this->container[$id] = $value;
} | Sets a parameter or an object.
Objects must be defined as Closures.
Allowing any PHP callable leads to difficult to debug problems
as public function names (strings) are callable (creating a public function with
the same a name as an existing parameter would break your container).
@param string $id The unique identifier for the parameter or object
@param mixed $value The value of the parameter or a closure to defined an object | https://github.com/phpalchemy/phpalchemy/blob/5b7e9b13acfda38c61b2da2639e8a56f298dc32e/Alchemy/Component/DiContainer/DiContainer.php#L49-L57 |
phpalchemy/phpalchemy | Alchemy/Component/DiContainer/DiContainer.php | DiContainer.offsetGet | public function offsetGet($id)
{
if (!array_key_exists($id, $this->container)) {
throw new InvalidArgumentException(sprintf('Identifier "%s" is not defined.', $id));
}
return $this->container[$id] instanceof Closure ? $this->container[$id]($this) : $this->container[$id];
} | php | public function offsetGet($id)
{
if (!array_key_exists($id, $this->container)) {
throw new InvalidArgumentException(sprintf('Identifier "%s" is not defined.', $id));
}
return $this->container[$id] instanceof Closure ? $this->container[$id]($this) : $this->container[$id];
} | Gets a parameter or an object.
@param string $id The unique identifier for the parameter or object
@return mixed The value of the parameter or an object
@throws InvalidArgumentException if the identifier is not defined | https://github.com/phpalchemy/phpalchemy/blob/5b7e9b13acfda38c61b2da2639e8a56f298dc32e/Alchemy/Component/DiContainer/DiContainer.php#L68-L75 |
phpalchemy/phpalchemy | Alchemy/Component/DiContainer/DiContainer.php | DiContainer.raw | public function raw($id)
{
if (!array_key_exists($id, $this->container)) {
throw new InvalidArgumentException(sprintf('Identifier "%s" is not defined.', $id));
}
return $this->container[$id];
} | php | public function raw($id)
{
if (!array_key_exists($id, $this->container)) {
throw new InvalidArgumentException(sprintf('Identifier "%s" is not defined.', $id));
}
return $this->container[$id];
} | Gets a parameter or the closure defining an object.
@param string $id The unique identifier for the parameter or object
@return mixed The value of the parameter or the closure defining an object
@throws InvalidArgumentException if the identifier is not defined | https://github.com/phpalchemy/phpalchemy/blob/5b7e9b13acfda38c61b2da2639e8a56f298dc32e/Alchemy/Component/DiContainer/DiContainer.php#L152-L159 |
fxpio/fxp-doctrine-console | Command/View.php | View.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$id = $input->getArgument($this->adapter->getIdentifierArgument());
$instance = $this->adapter->get($id);
$output->writeln([
'',
'<info>Details of '.$this->adapter->getShortName().':</info>',
'',
]);
DetailObjectHelper::display($output, $instance);
$output->writeln('');
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$id = $input->getArgument($this->adapter->getIdentifierArgument());
$instance = $this->adapter->get($id);
$output->writeln([
'',
'<info>Details of '.$this->adapter->getShortName().':</info>',
'',
]);
DetailObjectHelper::display($output, $instance);
$output->writeln('');
} | {@inheritdoc} | https://github.com/fxpio/fxp-doctrine-console/blob/2fc16d7a4eb0f247075c50de225ec2670ca5479a/Command/View.php#L31-L44 |
ARCANEDEV/Markup | src/Entities/Tag.php | Tag.setParent | private function setParent(&$parent)
{
if (! is_null($parent)) {
$this->parent = $parent;
$this->parent->elements->add($this);
}
return $this;
} | php | private function setParent(&$parent)
{
if (! is_null($parent)) {
$this->parent = $parent;
$this->parent->elements->add($this);
}
return $this;
} | Set Parent
@param Tag|null $parent
@return Tag | https://github.com/ARCANEDEV/Markup/blob/881331df74b27614d025c365daacbae6aa865612/src/Entities/Tag.php#L92-L101 |
ARCANEDEV/Markup | src/Entities/Tag.php | Tag.addElement | public function addElement($tag, array $attributes = [])
{
if ($tag instanceof self) {
$htmlTag = $tag;
$htmlTag->top = $this->top;
$htmlTag->attrs($attributes);
$this->elements->add($htmlTag);
return $htmlTag;
}
return self::make(
$tag,
$attributes,
$this->hasParent() ? $this->parent : $this
);
} | php | public function addElement($tag, array $attributes = [])
{
if ($tag instanceof self) {
$htmlTag = $tag;
$htmlTag->top = $this->top;
$htmlTag->attrs($attributes);
$this->elements->add($htmlTag);
return $htmlTag;
}
return self::make(
$tag,
$attributes,
$this->hasParent() ? $this->parent : $this
);
} | Add element at an existing Markup
@param Tag|string $tag
@param array $attributes
@return Tag | https://github.com/ARCANEDEV/Markup/blob/881331df74b27614d025c365daacbae6aa865612/src/Entities/Tag.php#L187-L203 |
ARCANEDEV/Markup | src/Entities/Tag.php | Tag.getFirst | public function getFirst()
{
$element = null;
if (
$this->hasParent() and
$this->parent->hasElements()
) {
$element = $this->parent->elements[0];
}
return $element;
} | php | public function getFirst()
{
$element = null;
if (
$this->hasParent() and
$this->parent->hasElements()
) {
$element = $this->parent->elements[0];
}
return $element;
} | Return first child of parent of current object
@return Tag|null | https://github.com/ARCANEDEV/Markup/blob/881331df74b27614d025c365daacbae6aa865612/src/Entities/Tag.php#L220-L232 |
ARCANEDEV/Markup | src/Entities/Tag.php | Tag.removeElement | public function removeElement($tag)
{
list($elements, $deleted) = $this->elements->remove($tag);
$this->elements = $elements;
return $deleted ? $this : null;
} | php | public function removeElement($tag)
{
list($elements, $deleted) = $this->elements->remove($tag);
$this->elements = $elements;
return $deleted ? $this : null;
} | Remove an element
@param $tag
@return Tag|null | https://github.com/ARCANEDEV/Markup/blob/881331df74b27614d025c365daacbae6aa865612/src/Entities/Tag.php#L289-L295 |
nasumilu/geometry | src/Serializer/Encoder/Adapter/GeoJsonEncoderAdapter.php | GeoJsonEncoderAdapter.encode | public function encode($data, string $format, array $context = []) {
return json_encode(parent::encode($data, $format, $context), $context['json_options'] ?? 0);
} | php | public function encode($data, string $format, array $context = []) {
return json_encode(parent::encode($data, $format, $context), $context['json_options'] ?? 0);
} | {@inheritDoc} | https://github.com/nasumilu/geometry/blob/000fafe3e61f1d0682952ad236b7486dded65eae/src/Serializer/Encoder/Adapter/GeoJsonEncoderAdapter.php#L40-L42 |
Tuna-CMS/tuna-bundle | src/Tuna/Bundle/FileBundle/Form/UploadedFileType.php | UploadedFileType.buildForm | public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('file', CoreFileType::class, [
'error_bubbling' => true,
'constraints' => [
new File([
'maxSize' => AbstractFileType::getPHPMaxFilesize() * 1048576, // filesize in MB
])
]
]);
} | php | public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('file', CoreFileType::class, [
'error_bubbling' => true,
'constraints' => [
new File([
'maxSize' => AbstractFileType::getPHPMaxFilesize() * 1048576, // filesize in MB
])
]
]);
} | {@inheritdoc} | https://github.com/Tuna-CMS/tuna-bundle/blob/1f999de44e14cbe9f992d46f2e5e74ddc117b04c/src/Tuna/Bundle/FileBundle/Form/UploadedFileType.php#L16-L26 |
YiMAproject/yimaWidgetator | src/yimaWidgetator/Controller/WidgetLoadRestController.php | WidgetLoadRestController.getList | public function getList()
{
$request = $this->getRequest();
// retrive data ...
$data = $request->getQuery()->toArray();
return $this->proccessData($data);
} | php | public function getList()
{
$request = $this->getRequest();
// retrive data ...
$data = $request->getQuery()->toArray();
return $this->proccessData($data);
} | Return list of resources
@return mixed | https://github.com/YiMAproject/yimaWidgetator/blob/332bc9318e6ceaec918147b30317da2f5b3d2636/src/yimaWidgetator/Controller/WidgetLoadRestController.php#L26-L34 |
YiMAproject/yimaWidgetator | src/yimaWidgetator/Controller/WidgetLoadRestController.php | WidgetLoadRestController.getValidateData | protected function getValidateData($data)
{
if (!isset($data['widget'])) {
// : Widget Name
throw new Service\Exceptions\InvalidArgumentException('{widget} param is absent.');
}
if (!isset($data['method'])) {
// : Method must call from widget
throw new Service\Exceptions\InvalidArgumentException('{method} param is absent.');
}
$params = array();
if(isset($data['params'])) {
// : Params that constructed widget
if (is_array($data['params'])) {
// ajaxq send object as array here
$params = $data['params'];
} else {
$params = Json\Json::decode($data['params']);
}
}
$data['params'] = $params;
$data['interfunc'] = isset($data['interfunc']) ? $data['interfunc'] : array();
$interfunc = $data['interfunc'];
$interfunc = explode(';', $interfunc);
$data['interfunc'] = array();
foreach($interfunc as $if) {
// key:value, value returned from (method) will returned as (key) in last result
// call a method and append returned value to result array
$if = explode(':', $if);
if (count($if) > 2 || count($if) < 2)
throw new Service\Exceptions\InvalidArgumentException('{interfunc} param is invalid.');
$data['interfunc'][] = $if;
}
if (!$this->request->isXmlHttpRequest()) {
// No Token Needed for ajax requests
if (!isset($params['request_token'])) {
throw new Service\Exceptions\UnauthorizedException('{request_token} param is absent.');
} else {
// validate token
$token = $params['request_token'];
$sesCont = new SessionContainer(WidgetAjaxy::SESSION_KEY);
if (!$sesCont->offsetGet($token)) {
// invalid token
throw new Service\Exceptions\UnauthorizedException('{request_token} is mismatch.');
}
unset($params['request_token']);
}
}
return $data;
} | php | protected function getValidateData($data)
{
if (!isset($data['widget'])) {
// : Widget Name
throw new Service\Exceptions\InvalidArgumentException('{widget} param is absent.');
}
if (!isset($data['method'])) {
// : Method must call from widget
throw new Service\Exceptions\InvalidArgumentException('{method} param is absent.');
}
$params = array();
if(isset($data['params'])) {
// : Params that constructed widget
if (is_array($data['params'])) {
// ajaxq send object as array here
$params = $data['params'];
} else {
$params = Json\Json::decode($data['params']);
}
}
$data['params'] = $params;
$data['interfunc'] = isset($data['interfunc']) ? $data['interfunc'] : array();
$interfunc = $data['interfunc'];
$interfunc = explode(';', $interfunc);
$data['interfunc'] = array();
foreach($interfunc as $if) {
// key:value, value returned from (method) will returned as (key) in last result
// call a method and append returned value to result array
$if = explode(':', $if);
if (count($if) > 2 || count($if) < 2)
throw new Service\Exceptions\InvalidArgumentException('{interfunc} param is invalid.');
$data['interfunc'][] = $if;
}
if (!$this->request->isXmlHttpRequest()) {
// No Token Needed for ajax requests
if (!isset($params['request_token'])) {
throw new Service\Exceptions\UnauthorizedException('{request_token} param is absent.');
} else {
// validate token
$token = $params['request_token'];
$sesCont = new SessionContainer(WidgetAjaxy::SESSION_KEY);
if (!$sesCont->offsetGet($token)) {
// invalid token
throw new Service\Exceptions\UnauthorizedException('{request_token} is mismatch.');
}
unset($params['request_token']);
}
}
return $data;
} | Validate Data
@param array $data Data
@return array
@throws \yimaWidgetator\Service\Exceptions\UnauthorizedException
@throws \yimaWidgetator\Service\Exceptions\InvalidArgumentException | https://github.com/YiMAproject/yimaWidgetator/blob/332bc9318e6ceaec918147b30317da2f5b3d2636/src/yimaWidgetator/Controller/WidgetLoadRestController.php#L164-L220 |
LoggerEssentials/LoggerEssentials | src/Formatters/MaxLengthFormatter.php | MaxLengthFormatter.log | public function log($level, $message, array $context = array()) {
if($this->maxLength < mb_strlen($message, $this->charset)) {
$ellipses = iconv('UTF-8', $this->charset, $this->ellipsis);
$message = mb_substr($message, 0, $this->maxLength - strlen($this->ellipsis), $this->charset);
$message = $message . $ellipses;
}
$this->logger()->log($level, $message, $context);
} | php | public function log($level, $message, array $context = array()) {
if($this->maxLength < mb_strlen($message, $this->charset)) {
$ellipses = iconv('UTF-8', $this->charset, $this->ellipsis);
$message = mb_substr($message, 0, $this->maxLength - strlen($this->ellipsis), $this->charset);
$message = $message . $ellipses;
}
$this->logger()->log($level, $message, $context);
} | Logs with an arbitrary level.
@param string $level
@param string $message
@param array $context
@return void | https://github.com/LoggerEssentials/LoggerEssentials/blob/f32f9b865eacfccced90697f3eb69dc4ad80dc96/src/Formatters/MaxLengthFormatter.php#L36-L43 |
METANETAG/formHandler | lib/ch/metanet/formHandler/renderer/SelectOptionsFieldRenderer.php | SelectOptionsFieldRenderer.renderOptions | protected function renderOptions(array $options, $selection)
{
$html = '';
foreach($options as $key => $val) {
if(is_array($val) === false) {
$selected = ($key == $selection) ? ' selected' : null;
$html .= '<option value="' . $key . '"' . $selected . '>' . $val . '</option>';
} else {
$html .= '<optgroup label="' . $key . '">' . $this->renderOptions($val, $selection) . '</optgroup>';
}
}
return $html;
} | php | protected function renderOptions(array $options, $selection)
{
$html = '';
foreach($options as $key => $val) {
if(is_array($val) === false) {
$selected = ($key == $selection) ? ' selected' : null;
$html .= '<option value="' . $key . '"' . $selected . '>' . $val . '</option>';
} else {
$html .= '<optgroup label="' . $key . '">' . $this->renderOptions($val, $selection) . '</optgroup>';
}
}
return $html;
} | @param array $options
@param mixed $selection
@return string | https://github.com/METANETAG/formHandler/blob/4f6e556e54e3a683edd7da0d2f72ed64e6bf1580/lib/ch/metanet/formHandler/renderer/SelectOptionsFieldRenderer.php#L40-L54 |
phossa2/storage | src/Storage/Traits/MountableTrait.php | MountableTrait.mount | public function mount(
/*# string */ $mountPoint,
FilesystemInterface $filesystem
)/*# : bool */ {
// normalize mount point
$mp = $this->cleanMountPoint($mountPoint);
// mounted already
if (isset($this->filesystems[$mp])) {
throw new LogicException(
Message::get(Message::STR_MOUNT_EXISTS, $mountPoint),
Message::STR_MOUNT_EXISTS
);
}
$this->filesystems[$mp] = $filesystem;
return true;
} | php | public function mount(
/*# string */ $mountPoint,
FilesystemInterface $filesystem
)/*# : bool */ {
// normalize mount point
$mp = $this->cleanMountPoint($mountPoint);
// mounted already
if (isset($this->filesystems[$mp])) {
throw new LogicException(
Message::get(Message::STR_MOUNT_EXISTS, $mountPoint),
Message::STR_MOUNT_EXISTS
);
}
$this->filesystems[$mp] = $filesystem;
return true;
} | {@inheritDoc} | https://github.com/phossa2/storage/blob/777f174559359deb56e63101c4962750eb15cfde/src/Storage/Traits/MountableTrait.php#L46-L63 |
phossa2/storage | src/Storage/Traits/MountableTrait.php | MountableTrait.umount | public function umount(/*# string */ $mountPoint)/*# : bool */
{
// normalize mount point
$mp = $this->cleanMountPoint($mountPoint);
// not mounted
if (!isset($this->filesystems[$mp])) {
throw new LogicException(
Message::get(Message::STR_MOUNT_NOT_EXISTS, $mountPoint),
Message::STR_MOUNT_NOT_EXISTS
);
}
// umount now
unset($this->filesystems[$mp]);
return true;
} | php | public function umount(/*# string */ $mountPoint)/*# : bool */
{
// normalize mount point
$mp = $this->cleanMountPoint($mountPoint);
// not mounted
if (!isset($this->filesystems[$mp])) {
throw new LogicException(
Message::get(Message::STR_MOUNT_NOT_EXISTS, $mountPoint),
Message::STR_MOUNT_NOT_EXISTS
);
}
// umount now
unset($this->filesystems[$mp]);
return true;
} | {@inheritDoc} | https://github.com/phossa2/storage/blob/777f174559359deb56e63101c4962750eb15cfde/src/Storage/Traits/MountableTrait.php#L68-L85 |
phossa2/storage | src/Storage/Traits/MountableTrait.php | MountableTrait.getMountPoint | protected function getMountPoint(/*# string */ $path)/*# : string */
{
while ($path !== '') {
if (isset($this->filesystems[$path])) {
return $path;
}
$path = substr($path, 0, strrpos($path, '/'));
}
return '/';
} | php | protected function getMountPoint(/*# string */ $path)/*# : string */
{
while ($path !== '') {
if (isset($this->filesystems[$path])) {
return $path;
}
$path = substr($path, 0, strrpos($path, '/'));
}
return '/';
} | Find mount point of the path
@param string $path
@return string
@access protected | https://github.com/phossa2/storage/blob/777f174559359deb56e63101c4962750eb15cfde/src/Storage/Traits/MountableTrait.php#L119-L128 |
schpill/thin | src/Hash.php | Hash.make | public static function make($value, $rounds = 8)
{
$work = str_pad($rounds, 2, '0', STR_PAD_LEFT);
// Bcrypt expects the salt to be 22 base64 encoded characters including
// dots and slashes. We will get rid of the plus signs included in the
// base64 data and replace them with dots.
if (function_exists('openssl_random_pseudo_bytes')) {
$salt = openssl_random_pseudo_bytes(16);
} else {
$salt = Inflector::random(40);
}
$salt = substr(strtr(base64_encode($salt), '+', '.'), 0 , 22);
return crypt($value, '$2a$' . $work . '$' . $salt);
} | php | public static function make($value, $rounds = 8)
{
$work = str_pad($rounds, 2, '0', STR_PAD_LEFT);
// Bcrypt expects the salt to be 22 base64 encoded characters including
// dots and slashes. We will get rid of the plus signs included in the
// base64 data and replace them with dots.
if (function_exists('openssl_random_pseudo_bytes')) {
$salt = openssl_random_pseudo_bytes(16);
} else {
$salt = Inflector::random(40);
}
$salt = substr(strtr(base64_encode($salt), '+', '.'), 0 , 22);
return crypt($value, '$2a$' . $work . '$' . $salt);
} | Hash a password using the Bcrypt hashing scheme.
<code>
// Create a Bcrypt hash of a value
$hash = Hash::make('secret');
// Use a specified number of iterations when creating the hash
$hash = Hash::make('secret', 12);
</code>
@param string $value
@param int $rounds
@return string | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Hash.php#L25-L41 |
CandleLight-Project/Framework | src/Error.php | Error.registerSystemErrors | public static function registerSystemErrors(Slim $app): void{
/** @var Container $c */
$c = $app->getContainer();
// Exception Handler
$c['errorHandler'] = function ($c){
/**
* Custom exception cather for the slim-framework
* @param Request $request Request Object
* @param Response $response Response Object
* @param \Exception $exception Thrown Exception
* @return Response Object
*/
return function (Request $request, Response $response, \Exception $exception) use ($c): Response{
/** @var Response $response */
$response = $c['response'];
return $response
->withStatus(500)
->withJson(new self($exception->getMessage()));
};
};
// 404 Handler
$c['notFoundHandler'] = function ($c){
/**
* Custom 404 handler for the slim-framework
* @param Request $request Request Object
* @param Response $response Response Object
* @return Response Object
*/
return function (Request $request, Response $response) use ($c){
return $c['response']
->withStatus(404)
->withJson(new self('Route not defined'));
};
};
// Method not supported Handler
$c['notAllowedHandler'] = function ($c){
return function ($request, $response, $methods) use ($c){
return $c['response']
->withStatus(405)
->withJson(new self('Method needs to be ' . implode($methods, ', ') . ' for this route.'));
};
};
} | php | public static function registerSystemErrors(Slim $app): void{
/** @var Container $c */
$c = $app->getContainer();
// Exception Handler
$c['errorHandler'] = function ($c){
/**
* Custom exception cather for the slim-framework
* @param Request $request Request Object
* @param Response $response Response Object
* @param \Exception $exception Thrown Exception
* @return Response Object
*/
return function (Request $request, Response $response, \Exception $exception) use ($c): Response{
/** @var Response $response */
$response = $c['response'];
return $response
->withStatus(500)
->withJson(new self($exception->getMessage()));
};
};
// 404 Handler
$c['notFoundHandler'] = function ($c){
/**
* Custom 404 handler for the slim-framework
* @param Request $request Request Object
* @param Response $response Response Object
* @return Response Object
*/
return function (Request $request, Response $response) use ($c){
return $c['response']
->withStatus(404)
->withJson(new self('Route not defined'));
};
};
// Method not supported Handler
$c['notAllowedHandler'] = function ($c){
return function ($request, $response, $methods) use ($c){
return $c['response']
->withStatus(405)
->withJson(new self('Method needs to be ' . implode($methods, ', ') . ' for this route.'));
};
};
} | Injects a custom error handling into the Slim-framework
@param Slim $app Slim Framework instance | https://github.com/CandleLight-Project/Framework/blob/13c5cc34bd1118601406b0129f7b61c7b78d08f4/src/Error.php#L32-L74 |
zbox/UnifiedPush | src/Zbox/UnifiedPush/Message/Type/MPNSBase.php | MPNSBase.validateRecipient | public function validateRecipient($token)
{
if (base64_encode(base64_decode($token)) !== $token) {
throw new InvalidArgumentException(sprintf(
'Device token must be base64 string. Token given: "%s"',
$token
));
}
return true;
} | php | public function validateRecipient($token)
{
if (base64_encode(base64_decode($token)) !== $token) {
throw new InvalidArgumentException(sprintf(
'Device token must be base64 string. Token given: "%s"',
$token
));
}
return true;
} | {@inheritdoc} | https://github.com/zbox/UnifiedPush/blob/47da2d0577b18ac709cd947c68541014001e1866/src/Zbox/UnifiedPush/Message/Type/MPNSBase.php#L93-L102 |
calgamo/middleware | sample/src/WorldMiddleware.php | WorldMiddleware.process | public function process(RequestInterface $request, RequestHandlerInterface $handler)
{
$response = $handler->handle($request);
$response->body()->write('World!');
return $response;
} | php | public function process(RequestInterface $request, RequestHandlerInterface $handler)
{
$response = $handler->handle($request);
$response->body()->write('World!');
return $response;
} | Process middleware
@param RequestInterface $request
@param RequestHandlerInterface $handler
@return ResponseInterface | https://github.com/calgamo/middleware/blob/a577982856a0f1f1ade25d80b66523d5bb4ebd5d/sample/src/WorldMiddleware.php#L19-L26 |
ARCANEDEV/Markup | src/Support/Builder.php | Builder.make | public static function make(TagInterface $tag)
{
if (
$tag->getType() === '' and
$tag->getText() !== ''
) {
return $tag->getText();
}
return self::isAutoClosed($tag->getType())
? self::open($tag, true)
: self::open($tag) . $tag->getText() . $tag->renderElements() . self::close($tag);
} | php | public static function make(TagInterface $tag)
{
if (
$tag->getType() === '' and
$tag->getText() !== ''
) {
return $tag->getText();
}
return self::isAutoClosed($tag->getType())
? self::open($tag, true)
: self::open($tag) . $tag->getText() . $tag->renderElements() . self::close($tag);
} | Render a Tag and its elements
@param TagInterface $tag
@return string | https://github.com/ARCANEDEV/Markup/blob/881331df74b27614d025c365daacbae6aa865612/src/Support/Builder.php#L28-L40 |
ARCANEDEV/Markup | src/Support/Builder.php | Builder.open | private static function open(TagInterface $tag, $autoClosed = false)
{
$output = '<' . $tag->getType();
if ($tag->hasAttributes()) {
$output .= ' ' . $tag->renderAttributes();
}
$output .= ($autoClosed ? '/>' : '>');
return $output;
} | php | private static function open(TagInterface $tag, $autoClosed = false)
{
$output = '<' . $tag->getType();
if ($tag->hasAttributes()) {
$output .= ' ' . $tag->renderAttributes();
}
$output .= ($autoClosed ? '/>' : '>');
return $output;
} | Render open Tag
@param TagInterface $tag
@param bool $autoClosed
@return string | https://github.com/ARCANEDEV/Markup/blob/881331df74b27614d025c365daacbae6aa865612/src/Support/Builder.php#L50-L61 |
chilimatic/chilimatic-framework | lib/database/sql/mysql/Statement.php | Statement.bindParam | public function bindParam($placeholder, &$var, $type = null)
{
$this->param_list[$placeholder] = &$var;
if (!empty($type) && in_array($type, $this->_type_list)) {
$this->type_list[$placeholder] = &$type;
}
return true;
} | php | public function bindParam($placeholder, &$var, $type = null)
{
$this->param_list[$placeholder] = &$var;
if (!empty($type) && in_array($type, $this->_type_list)) {
$this->type_list[$placeholder] = &$type;
}
return true;
} | binds a parameter
@param string $placeholder
@param mixed $var
@param null $type
@return bool | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/database/sql/mysql/Statement.php#L142-L152 |
chilimatic/chilimatic-framework | lib/database/sql/mysql/Statement.php | Statement.execute | public function execute()
{
try {
$sql = $this->prepared_sql;
foreach ($this->param_list as $placeholder => $param) {
if (strpos($this->prepared_sql, $placeholder) === false) {
throw new DatabaseException(__METHOD__ . " missing bound placeholder: $placeholder in sql $this->prepared_sql", MySQL::ERR_CONN, MySQL::SEVERITY_LOG, __FILE__, __LINE__);
}
$t = (isset($this->type_list[$placeholder]) ? $this->type_list[$placeholder] : 999999);
switch ($t) {
case self::TYPE_BLOB:
case self::TYPE_STRING:
$val = "'" . mysql_real_escape_string($param, $this->_db->db) . "'";
break;
case self::TYPE_INT:
case self::TYPE_BOOL:
$val = (int)$param;
break;
case self::TYPE_FLOAT:
$val = (float)$param;
break;
case self::TYPE_NULL:
$val = 'NULL';
break;
default:
$val = "'" . (mysql_real_escape_string($param, $this->_db->db)) . "'";
break;
}
$sql = str_replace($placeholder, $val, $sql);
}
} catch (DatabaseException $e) {
throw $e;
}
unset($t, $val, $param);
/**
* set the sql for debugging purposes
*/
$this->sql = $sql;
/**
* query the database
*/
$this->res = $this->_db->query($sql);
if (!$this->res) return false;
return $this;
} | php | public function execute()
{
try {
$sql = $this->prepared_sql;
foreach ($this->param_list as $placeholder => $param) {
if (strpos($this->prepared_sql, $placeholder) === false) {
throw new DatabaseException(__METHOD__ . " missing bound placeholder: $placeholder in sql $this->prepared_sql", MySQL::ERR_CONN, MySQL::SEVERITY_LOG, __FILE__, __LINE__);
}
$t = (isset($this->type_list[$placeholder]) ? $this->type_list[$placeholder] : 999999);
switch ($t) {
case self::TYPE_BLOB:
case self::TYPE_STRING:
$val = "'" . mysql_real_escape_string($param, $this->_db->db) . "'";
break;
case self::TYPE_INT:
case self::TYPE_BOOL:
$val = (int)$param;
break;
case self::TYPE_FLOAT:
$val = (float)$param;
break;
case self::TYPE_NULL:
$val = 'NULL';
break;
default:
$val = "'" . (mysql_real_escape_string($param, $this->_db->db)) . "'";
break;
}
$sql = str_replace($placeholder, $val, $sql);
}
} catch (DatabaseException $e) {
throw $e;
}
unset($t, $val, $param);
/**
* set the sql for debugging purposes
*/
$this->sql = $sql;
/**
* query the database
*/
$this->res = $this->_db->query($sql);
if (!$this->res) return false;
return $this;
} | execute the query
@throws \chilimatic\lib\exception\DatabaseException
@throws \Exception | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/database/sql/mysql/Statement.php#L161-L214 |
chilimatic/chilimatic-framework | lib/database/sql/mysql/Statement.php | Statement.fetchAll | public function fetchAll($type = null)
{
try {
if ($this->res === false) {
throw new DatabaseException(__METHOD__ . " No ressource has been given", MySQL::NO_RESSOURCE, MySQL::SEVERITY_DEBUG, __FILE__, __LINE__);
}
switch ($type) {
case MySQL::FETCH_ASSOC:
return $this->_db->fetch_assoc_list($this->res);
break;
case MySQL::FETCH_NUM:
return $this->_db->fetch_num_list($this->res);
break;
case MySQL::FETCH_OBJ:
default:
return $this->_db->fetch_object_list($this->res);
break;
}
} catch (DatabaseException $e) {
throw $e;
}
} | php | public function fetchAll($type = null)
{
try {
if ($this->res === false) {
throw new DatabaseException(__METHOD__ . " No ressource has been given", MySQL::NO_RESSOURCE, MySQL::SEVERITY_DEBUG, __FILE__, __LINE__);
}
switch ($type) {
case MySQL::FETCH_ASSOC:
return $this->_db->fetch_assoc_list($this->res);
break;
case MySQL::FETCH_NUM:
return $this->_db->fetch_num_list($this->res);
break;
case MySQL::FETCH_OBJ:
default:
return $this->_db->fetch_object_list($this->res);
break;
}
} catch (DatabaseException $e) {
throw $e;
}
} | fetch all option
@param null $type
@return array
@throws DatabaseException
@throws \Exception | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/database/sql/mysql/Statement.php#L225-L249 |
sellerlabs/php-standard | src/SellerLabs/Standards/Chroma/Sniffs/Functions/OpeningFunctionBraceSniff.php | Chroma_Sniffs_Functions_OpeningFunctionBraceSniff.process | public function process(PHP_CodeSniffer_File $file, $stackPtr)
{
$tokens = $file->getTokens();
if (isset($tokens[$stackPtr]['scope_opener']) === false) {
return;
}
// The end of the function occurs at the end of the argument list. Its
// like this because some people like to break long function
// declarations over multiple lines.
$openingBrace = $tokens[$stackPtr]['scope_opener'];
$parenthesisOpener = $tokens[$stackPtr]['parenthesis_opener'];
$parenthesisCloser = $tokens[$stackPtr]['parenthesis_closer'];
$functionStartLine = $tokens[$parenthesisOpener]['line'];
$functionLine = $tokens[$parenthesisCloser]['line'];
$braceLine = $tokens[$openingBrace]['line'];
$lineDifference = ($braceLine - $functionLine);
$isMultiline = ($functionStartLine != $functionLine);
if ($lineDifference === 0 && !$isMultiline) {
$error = 'Opening brace should be on a new line';
$fix = $file->addFixableError(
$error,
$openingBrace,
'BraceOnSameLine'
);
if ($fix === true) {
$file->fixer->beginChangeset();
$indent = $file->findFirstOnLine([], $openingBrace);
if ($tokens[$indent]['code'] === T_WHITESPACE) {
$file->fixer->addContentBefore(
$openingBrace,
$tokens[$indent]['content']
);
}
$file->fixer->addNewlineBefore($openingBrace);
$file->fixer->endChangeset();
}
$file->recordMetric(
$stackPtr,
'Function opening brace placement',
'same line'
);
} else {
if ($lineDifference > 1) {
$error = 'Opening brace should be on the line after the'
. ' declaration; found %s blank line(s)';
$data = [($lineDifference - 1)];
$fix = $file->addFixableError(
$error,
$openingBrace,
'BraceSpacing',
$data
);
if ($fix === true) {
$afterCloser = $parenthesisCloser + 1;
for ($i = $afterCloser; $i < $openingBrace; $i++) {
if ($tokens[$i]['line'] === $braceLine) {
$file->fixer->addNewLineBefore($i);
break;
}
$file->fixer->replaceToken($i, '');
}
}
}
}
$next = $file->findNext(
T_WHITESPACE,
($openingBrace + 1),
null,
true
);
if ($tokens[$next]['line'] === $tokens[$openingBrace]['line']) {
if ($next === $tokens[$stackPtr]['scope_closer']) {
// Ignore empty functions.
return;
}
$error = 'Opening brace must be the last content on the line';
$fix = $file->addFixableError(
$error,
$openingBrace,
'ContentAfterBrace'
);
if ($fix === true) {
$file->fixer->addNewline($openingBrace);
}
}
// Only continue checking if the opening brace looks good.
if ($lineDifference !== 1) {
return;
}
// We need to actually find the first piece of content on this line,
// as if this is a method with tokens before it (public, static etc)
// or an if with an else before it, then we need to start the scope
// checking from there, rather than the current token.
$lineStart = $stackPtr;
while (
($lineStart = $file->findPrevious(
T_WHITESPACE,
($lineStart - 1),
null,
false)
) !== false) {
$position = strpos(
$tokens[$lineStart]['content'],
$file->eolChar
);
if ($position !== false) {
break;
}
}
// We found a new line, now go forward and find the first
// non-whitespace token.
$lineStart = $file->findNext(T_WHITESPACE, $lineStart, null, true);
// The opening brace is on the correct line, now it needs to be
// checked to be correctly indented.
$startColumn = $tokens[$lineStart]['column'];
$braceIndent = $tokens[$openingBrace]['column'];
if ($braceIndent !== $startColumn) {
$expected = ($startColumn - 1);
$found = ($braceIndent - 1);
$error = 'Opening brace indented incorrectly;'
. ' expected %s spaces, found %s';
$data = [
$expected,
$found,
];
$fix = $file->addFixableError(
$error,
$openingBrace,
'BraceIndent',
$data
);
if ($fix === true) {
$indent = str_repeat(' ', $expected);
if ($found === 0) {
$file->fixer->addContentBefore($openingBrace, $indent);
} else {
$file->fixer->replaceToken(
($openingBrace - 1),
$indent
);
}
}
}
$file->recordMetric(
$stackPtr,
'Function opening brace placement',
'new line'
);
} | php | public function process(PHP_CodeSniffer_File $file, $stackPtr)
{
$tokens = $file->getTokens();
if (isset($tokens[$stackPtr]['scope_opener']) === false) {
return;
}
// The end of the function occurs at the end of the argument list. Its
// like this because some people like to break long function
// declarations over multiple lines.
$openingBrace = $tokens[$stackPtr]['scope_opener'];
$parenthesisOpener = $tokens[$stackPtr]['parenthesis_opener'];
$parenthesisCloser = $tokens[$stackPtr]['parenthesis_closer'];
$functionStartLine = $tokens[$parenthesisOpener]['line'];
$functionLine = $tokens[$parenthesisCloser]['line'];
$braceLine = $tokens[$openingBrace]['line'];
$lineDifference = ($braceLine - $functionLine);
$isMultiline = ($functionStartLine != $functionLine);
if ($lineDifference === 0 && !$isMultiline) {
$error = 'Opening brace should be on a new line';
$fix = $file->addFixableError(
$error,
$openingBrace,
'BraceOnSameLine'
);
if ($fix === true) {
$file->fixer->beginChangeset();
$indent = $file->findFirstOnLine([], $openingBrace);
if ($tokens[$indent]['code'] === T_WHITESPACE) {
$file->fixer->addContentBefore(
$openingBrace,
$tokens[$indent]['content']
);
}
$file->fixer->addNewlineBefore($openingBrace);
$file->fixer->endChangeset();
}
$file->recordMetric(
$stackPtr,
'Function opening brace placement',
'same line'
);
} else {
if ($lineDifference > 1) {
$error = 'Opening brace should be on the line after the'
. ' declaration; found %s blank line(s)';
$data = [($lineDifference - 1)];
$fix = $file->addFixableError(
$error,
$openingBrace,
'BraceSpacing',
$data
);
if ($fix === true) {
$afterCloser = $parenthesisCloser + 1;
for ($i = $afterCloser; $i < $openingBrace; $i++) {
if ($tokens[$i]['line'] === $braceLine) {
$file->fixer->addNewLineBefore($i);
break;
}
$file->fixer->replaceToken($i, '');
}
}
}
}
$next = $file->findNext(
T_WHITESPACE,
($openingBrace + 1),
null,
true
);
if ($tokens[$next]['line'] === $tokens[$openingBrace]['line']) {
if ($next === $tokens[$stackPtr]['scope_closer']) {
// Ignore empty functions.
return;
}
$error = 'Opening brace must be the last content on the line';
$fix = $file->addFixableError(
$error,
$openingBrace,
'ContentAfterBrace'
);
if ($fix === true) {
$file->fixer->addNewline($openingBrace);
}
}
// Only continue checking if the opening brace looks good.
if ($lineDifference !== 1) {
return;
}
// We need to actually find the first piece of content on this line,
// as if this is a method with tokens before it (public, static etc)
// or an if with an else before it, then we need to start the scope
// checking from there, rather than the current token.
$lineStart = $stackPtr;
while (
($lineStart = $file->findPrevious(
T_WHITESPACE,
($lineStart - 1),
null,
false)
) !== false) {
$position = strpos(
$tokens[$lineStart]['content'],
$file->eolChar
);
if ($position !== false) {
break;
}
}
// We found a new line, now go forward and find the first
// non-whitespace token.
$lineStart = $file->findNext(T_WHITESPACE, $lineStart, null, true);
// The opening brace is on the correct line, now it needs to be
// checked to be correctly indented.
$startColumn = $tokens[$lineStart]['column'];
$braceIndent = $tokens[$openingBrace]['column'];
if ($braceIndent !== $startColumn) {
$expected = ($startColumn - 1);
$found = ($braceIndent - 1);
$error = 'Opening brace indented incorrectly;'
. ' expected %s spaces, found %s';
$data = [
$expected,
$found,
];
$fix = $file->addFixableError(
$error,
$openingBrace,
'BraceIndent',
$data
);
if ($fix === true) {
$indent = str_repeat(' ', $expected);
if ($found === 0) {
$file->fixer->addContentBefore($openingBrace, $indent);
} else {
$file->fixer->replaceToken(
($openingBrace - 1),
$indent
);
}
}
}
$file->recordMetric(
$stackPtr,
'Function opening brace placement',
'new line'
);
} | Processes this test, when one of its tokens is encountered.
@param PHP_CodeSniffer_File $file The file being scanned.
@param int $stackPtr The position of the current token in the
stack passed in $tokens. | https://github.com/sellerlabs/php-standard/blob/cd5c919c5aad1aba6f2486a81867172d0eb167f7/src/SellerLabs/Standards/Chroma/Sniffs/Functions/OpeningFunctionBraceSniff.php#L46-L219 |
andyburton/Sonic-Framework | src/Model/Tools/Comment.php | Comment.hasTag | public function hasTag ($tag)
{
foreach ($this->lines as $line)
{
if (strpos ($line, '@' . $tag) === 0)
{
return TRUE;
}
}
return FALSE;
} | php | public function hasTag ($tag)
{
foreach ($this->lines as $line)
{
if (strpos ($line, '@' . $tag) === 0)
{
return TRUE;
}
}
return FALSE;
} | Check if a tag is set in the comment
@param string $tag Tag to check for e.g. ignore = @ignore
@return boolean | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model/Tools/Comment.php#L36-L49 |
andyburton/Sonic-Framework | src/Model/Tools/Comment.php | Comment.getTags | public function getTags ($tag)
{
$tags = array ();
foreach ($this->lines as $line)
{
if (strpos ($line, '@' . $tag) === 0)
{
$tags[] = trim (substr ($line, strlen ('@' . $tag)));
}
}
return $tags;
} | php | public function getTags ($tag)
{
$tags = array ();
foreach ($this->lines as $line)
{
if (strpos ($line, '@' . $tag) === 0)
{
$tags[] = trim (substr ($line, strlen ('@' . $tag)));
}
}
return $tags;
} | Return array of matching tags
@param string $tag Tags to return
@return array | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model/Tools/Comment.php#L57-L72 |
andyburton/Sonic-Framework | src/Model/Tools/Comment.php | Comment.getLongDescription | public function getLongDescription ()
{
$comment = '';
foreach ($this->lines as $key => $line)
{
if ($key == 0 || ($line && $line[0] == '@'))
{
continue;
}
if ($comment)
{
$comment .= "\n";
}
$comment .= $line;
}
return $comment;
} | php | public function getLongDescription ()
{
$comment = '';
foreach ($this->lines as $key => $line)
{
if ($key == 0 || ($line && $line[0] == '@'))
{
continue;
}
if ($comment)
{
$comment .= "\n";
}
$comment .= $line;
}
return $comment;
} | Return long description
This is every other line of a comment besides the first line and any tags
@return string | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model/Tools/Comment.php#L93-L117 |
andyburton/Sonic-Framework | src/Model/Tools/Comment.php | Comment.starComment | public static function starComment ($strComment, $intTabs = 0)
{
// Set return
$strReturn = '';
// Split comment into lines
$arrComment = explode ("\n", $strComment);
// Find the position of the first /
$intFirstSlash = strpos ($arrComment[0], '/');
// Set prefix
$strPrefix = ($intFirstSlash)? substr ($arrComment[0], 0, $intFirstSlash) : NULL;
// Clean comment
$strComment = self::cleanComment ($strComment);
// Split comment into lines
$arrComment = explode ("\n", $strComment);
// Set the high count
$intHigh = 0;
// For each line
foreach ($arrComment as $strLine)
{
// If the length is above the high count
if (strlen ($strLine) > $intHigh)
{
// Set length as high count
$intHigh = strlen ($strLine);
}
}
// For each line
foreach ($arrComment as &$strLine)
{
// Count chars
$strCountChars = count_chars ($strLine, 3);
// If the comment consists of only -'s
if ($strCountChars == '-')
{
// Set the line to be -'s
$strLine = str_repeat ('-', $intHigh);
}
}
// Unset reference
unset ($strLine);
// Set tabs
$strTabs = str_repeat ("\t", $intTabs);
// Add the first lines
$strReturn .= $strTabs . $strPrefix . '/****' . str_repeat ('*', $intHigh) . '*****' . "\n" .
$strTabs . $strPrefix . '* ' . str_repeat (' ', $intHigh) . ' *' . "\n";
// For each line
foreach ($arrComment as $strLine)
{
// Add to return
$strReturn .= $strTabs . $strPrefix . '* ' . str_pad ($strLine, $intHigh) . ' *' . "\n";
}
// Add the last lines
$strReturn .= $strTabs . $strPrefix . '* ' . str_repeat (' ', $intHigh) . ' *' . "\n" .
$strTabs . $strPrefix . '*****' . str_repeat ('*', $intHigh) . '****/';
// Return
return $strReturn;
} | php | public static function starComment ($strComment, $intTabs = 0)
{
// Set return
$strReturn = '';
// Split comment into lines
$arrComment = explode ("\n", $strComment);
// Find the position of the first /
$intFirstSlash = strpos ($arrComment[0], '/');
// Set prefix
$strPrefix = ($intFirstSlash)? substr ($arrComment[0], 0, $intFirstSlash) : NULL;
// Clean comment
$strComment = self::cleanComment ($strComment);
// Split comment into lines
$arrComment = explode ("\n", $strComment);
// Set the high count
$intHigh = 0;
// For each line
foreach ($arrComment as $strLine)
{
// If the length is above the high count
if (strlen ($strLine) > $intHigh)
{
// Set length as high count
$intHigh = strlen ($strLine);
}
}
// For each line
foreach ($arrComment as &$strLine)
{
// Count chars
$strCountChars = count_chars ($strLine, 3);
// If the comment consists of only -'s
if ($strCountChars == '-')
{
// Set the line to be -'s
$strLine = str_repeat ('-', $intHigh);
}
}
// Unset reference
unset ($strLine);
// Set tabs
$strTabs = str_repeat ("\t", $intTabs);
// Add the first lines
$strReturn .= $strTabs . $strPrefix . '/****' . str_repeat ('*', $intHigh) . '*****' . "\n" .
$strTabs . $strPrefix . '* ' . str_repeat (' ', $intHigh) . ' *' . "\n";
// For each line
foreach ($arrComment as $strLine)
{
// Add to return
$strReturn .= $strTabs . $strPrefix . '* ' . str_pad ($strLine, $intHigh) . ' *' . "\n";
}
// Add the last lines
$strReturn .= $strTabs . $strPrefix . '* ' . str_repeat (' ', $intHigh) . ' *' . "\n" .
$strTabs . $strPrefix . '*****' . str_repeat ('*', $intHigh) . '****/';
// Return
return $strReturn;
} | Return a stared comment
@param string $strComment Comment
@param integer $intTabs Tabs before line
@return string | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model/Tools/Comment.php#L127-L231 |
andyburton/Sonic-Framework | src/Model/Tools/Comment.php | Comment.lineComment | public static function lineComment ($strComment, $intTabs = 0)
{
// Set return
$strReturn = '';
// Split comment into lines
$arrComment = explode ("\n", $strComment);
// Find the position of the first /
$intFirstSlash = strpos ($arrComment[0], '/');
// Set prefix
$strPrefix = ($intFirstSlash)? substr ($arrComment[0], 0, $intFirstSlash) : NULL;
// Clean comment
$strComment = self::cleanComment ($strComment);
// Split comment into lines
$arrComment = explode ("\n", $strComment);
// Set tabs
$strTabs = str_repeat ("\t", $intTabs);
// For each line
foreach ($arrComment as $strLine)
{
// Add line
$strReturn .= $strTabs . $strPrefix . '// ' . $strLine . "\n";
}
// Remove last \n
if (substr ($strReturn, -1) == "\n")
{
$strReturn = substr ($strReturn, 0, -1);
}
// Return
return $strReturn;
} | php | public static function lineComment ($strComment, $intTabs = 0)
{
// Set return
$strReturn = '';
// Split comment into lines
$arrComment = explode ("\n", $strComment);
// Find the position of the first /
$intFirstSlash = strpos ($arrComment[0], '/');
// Set prefix
$strPrefix = ($intFirstSlash)? substr ($arrComment[0], 0, $intFirstSlash) : NULL;
// Clean comment
$strComment = self::cleanComment ($strComment);
// Split comment into lines
$arrComment = explode ("\n", $strComment);
// Set tabs
$strTabs = str_repeat ("\t", $intTabs);
// For each line
foreach ($arrComment as $strLine)
{
// Add line
$strReturn .= $strTabs . $strPrefix . '// ' . $strLine . "\n";
}
// Remove last \n
if (substr ($strReturn, -1) == "\n")
{
$strReturn = substr ($strReturn, 0, -1);
}
// Return
return $strReturn;
} | Return a lined comment
@param type $strComment Comment
@param type $intTabs Tabs before line
@return string | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model/Tools/Comment.php#L241-L296 |
andyburton/Sonic-Framework | src/Model/Tools/Comment.php | Comment.cleanComment | public static function cleanComment ($strComment)
{
// Strip /r
$strComment = str_replace ("\r", '', $strComment);
// Set return
$strReturn = $strComment;
// Split lines
$arrLines = explode ("\n", $strComment);
// Find the position of the first /
$intFirstSlash = strpos ($arrLines[0], '/');
// If there is a first slash
if ($intFirstSlash !== FALSE)
{
// Set prefix
$strPrefix = substr ($arrLines[0], 0, $intFirstSlash);
// Switch the next char
switch ($strComment[$intFirstSlash +1])
{
// Star comment
case '*':
// Reset return
$strReturn = '';
// Remove first and last
array_pop ($arrLines);
array_shift ($arrLines);
// For each line
foreach ($arrLines as &$strLine)
{
// Remove prefix and clean whitespace
$strLine = trim (substr ($strLine, $intFirstSlash));
// If the first char is a *
if ($strLine[0] == '*')
{
// Remove *
$strLine = substr ($strLine, 1);
// For the first 4 characters
for ($x = 0; $x < 4; $x++)
{
// If the character is a space
if ($strLine[0] == ' ')
{
// Remove it
$strLine = substr ($strLine, 1);
}
// Otherwise
else
{
// Break
break;
}
}
}
// If the last char is a *
if (substr ($strLine, -1) == '*')
{
// Remove *
$strLine = substr ($strLine, 0, -1);
// For the last 4 characters
for ($x = 0; $x < 4; $x++)
{
// If the character is a space
if ($strLine[strlen ($strLine) -1] == ' ')
{
// Remove it
$strLine = substr ($strLine, 0, -1);
}
// Otherwise
else
{
// Break
break;
}
}
}
}
// Unset reference
unset ($strLine);
// For each line
foreach ($arrLines as $intKey => $strLine)
{
// If the line contains only spaces
if (count_chars ($strLine, 3) == ' ')
{
// Remove
unset ($arrLines[$intKey]);
}
// Else
else
{
// Break
break;
}
}
// For each line in reverse order
foreach (array_reverse ($arrLines, TRUE) as $intKey => $strLine)
{
// If the line contains only spaces
if (count_chars ($strLine, 3) == ' ')
{
// Remove
unset ($arrLines[$intKey]);
}
// Else
else
{
// Break
break;
}
}
// For each line
foreach ($arrLines as $strLine)
{
// If the comment is only -'s
if (count_chars ($strLine, 3) == '-')
{
// Add single - to return
$strReturn .= '-' . "\n";
}
// Else
else
{
// Add to return
$strReturn .= rtrim ($strLine) . "\n";
}
}
// If the last char is \n
if (substr ($strReturn, -1) == "\n")
{
// Remove it
$strReturn = substr ($strReturn, 0, -1);
}
// Break
break;
// Line comment
case '/':
// Reset return
$strReturn = '';
// For each line
foreach ($arrLines as $strLine)
{
// If the line is empty
if ($strLine == '')
{
// Next
continue;
}
// Remove prefix
$strLine = substr ($strLine, $intFirstSlash);
// Remove //
$strLine = str_replace ('// ', '', $strLine);
$strLine = str_replace ('//', '', $strLine);
// Add to return
$strReturn .= $strLine . "\n";
}
// If the last char is \n
if (substr ($strReturn, -1) == "\n")
{
// Remove it
$strReturn = substr ($strReturn, 0, -1);
}
// Break
break;
}
}
// Return
return $strReturn;
} | php | public static function cleanComment ($strComment)
{
// Strip /r
$strComment = str_replace ("\r", '', $strComment);
// Set return
$strReturn = $strComment;
// Split lines
$arrLines = explode ("\n", $strComment);
// Find the position of the first /
$intFirstSlash = strpos ($arrLines[0], '/');
// If there is a first slash
if ($intFirstSlash !== FALSE)
{
// Set prefix
$strPrefix = substr ($arrLines[0], 0, $intFirstSlash);
// Switch the next char
switch ($strComment[$intFirstSlash +1])
{
// Star comment
case '*':
// Reset return
$strReturn = '';
// Remove first and last
array_pop ($arrLines);
array_shift ($arrLines);
// For each line
foreach ($arrLines as &$strLine)
{
// Remove prefix and clean whitespace
$strLine = trim (substr ($strLine, $intFirstSlash));
// If the first char is a *
if ($strLine[0] == '*')
{
// Remove *
$strLine = substr ($strLine, 1);
// For the first 4 characters
for ($x = 0; $x < 4; $x++)
{
// If the character is a space
if ($strLine[0] == ' ')
{
// Remove it
$strLine = substr ($strLine, 1);
}
// Otherwise
else
{
// Break
break;
}
}
}
// If the last char is a *
if (substr ($strLine, -1) == '*')
{
// Remove *
$strLine = substr ($strLine, 0, -1);
// For the last 4 characters
for ($x = 0; $x < 4; $x++)
{
// If the character is a space
if ($strLine[strlen ($strLine) -1] == ' ')
{
// Remove it
$strLine = substr ($strLine, 0, -1);
}
// Otherwise
else
{
// Break
break;
}
}
}
}
// Unset reference
unset ($strLine);
// For each line
foreach ($arrLines as $intKey => $strLine)
{
// If the line contains only spaces
if (count_chars ($strLine, 3) == ' ')
{
// Remove
unset ($arrLines[$intKey]);
}
// Else
else
{
// Break
break;
}
}
// For each line in reverse order
foreach (array_reverse ($arrLines, TRUE) as $intKey => $strLine)
{
// If the line contains only spaces
if (count_chars ($strLine, 3) == ' ')
{
// Remove
unset ($arrLines[$intKey]);
}
// Else
else
{
// Break
break;
}
}
// For each line
foreach ($arrLines as $strLine)
{
// If the comment is only -'s
if (count_chars ($strLine, 3) == '-')
{
// Add single - to return
$strReturn .= '-' . "\n";
}
// Else
else
{
// Add to return
$strReturn .= rtrim ($strLine) . "\n";
}
}
// If the last char is \n
if (substr ($strReturn, -1) == "\n")
{
// Remove it
$strReturn = substr ($strReturn, 0, -1);
}
// Break
break;
// Line comment
case '/':
// Reset return
$strReturn = '';
// For each line
foreach ($arrLines as $strLine)
{
// If the line is empty
if ($strLine == '')
{
// Next
continue;
}
// Remove prefix
$strLine = substr ($strLine, $intFirstSlash);
// Remove //
$strLine = str_replace ('// ', '', $strLine);
$strLine = str_replace ('//', '', $strLine);
// Add to return
$strReturn .= $strLine . "\n";
}
// If the last char is \n
if (substr ($strReturn, -1) == "\n")
{
// Remove it
$strReturn = substr ($strReturn, 0, -1);
}
// Break
break;
}
}
// Return
return $strReturn;
} | Return a comment with all comment chars stripped
@param string $strComment Comment
@return string | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Model/Tools/Comment.php#L369-L677 |
pascalchevrel/vcs | src/VCS/Git.php | Git.getCommits | public function getCommits()
{
$log = $this->execute(
"git log --no-merges --format='changeset: %H%nuser: %aN <%aE>%ndate: %ad%nsummary: %s%n' "
. $this->repository_path
);
$this->repository_type = 'git';
return $this->parseLog($log);
} | php | public function getCommits()
{
$log = $this->execute(
"git log --no-merges --format='changeset: %H%nuser: %aN <%aE>%ndate: %ad%nsummary: %s%n' "
. $this->repository_path
);
$this->repository_type = 'git';
return $this->parseLog($log);
} | Get the list of Git commits for the repository as a structured array
@return array List of commits | https://github.com/pascalchevrel/vcs/blob/23d4827d5f8f44f20cd9a59fdf71ee7dfc895bfa/src/VCS/Git.php#L11-L20 |
YiMAproject/yimaAdminor | src/yimaAdminor/Controller/AccountController.php | AccountController.loginAction | public function loginAction()
{
/** @var AuthService $auth */
$auth = $this->_getAuthService();
if ($auth->identity()->hasAuthenticated()) {
// : User is authorized
$this->redirect()->toRoute(\yimaAdminor\Module::ADMIN_ROUTE_NAME);
return $this->getResponse();
}
/** @var $request \Zend\Http\PhpEnvironment\Request */
$request = $this->getRequest();
// Get redirect-url:
$redirectUrl = $auth->getGuard()->getStoredUrl();
if($request->isPost() && empty($redirectUrl))
$redirectUrl = $this->params()->fromPost('redirect_url');
if ($request->isPost()) {
$user = $this->params()->fromPost('login-username');
$pass = $this->params()->fromPost('login-password');
$rmbr = $this->params()->fromPost('login-remember-me', false);
$authAdabter = $auth->getAuthAdapter();
$authAdabter->credential(['username' => $user, 'password' => $pass]);
try {
$authAdabter->authenticate();
}
catch (WrongCredentialException $e) {
// set error messages
$this->flashMessenger('adminor.auth.message')->addErrorMessage(
$this->_translator()->translate('Invalid Username Or Password')
);
$this->redirect()->refresh();
return $this->getResponse();
}
catch (AuthenticationException $e) {
// set error messages
$this->flashMessenger('adminor.auth.message')->addErrorMessage(
$this->_translator()->translate('Activation Code Was Sent To Your Mail, Please Check Your Mailbox.')
);
$this->redirect()->refresh();
return $this->getResponse();
}
catch (\Exception $e) {
$this->flashMessenger('adminor.auth.message')->addErrorMessage(
$this->_translator()->translate($e->getMessage())
);
$this->redirect()->refresh();
return $this->getResponse();
}
$authAdabter->getIdentity()
->setRemember($rmbr)
->login();
// Successful login redirect user:
if (!empty($redirectUrl))
$this->redirect()->toUrl($redirectUrl);
else
$this->redirect()->toRoute(\yimaAdminor\Module::ADMIN_ROUTE_NAME);
return $this->getResponse();
}
// Build View:
$errMessages = $this->flashMessenger('adminor.auth.message')->getErrorMessages();
return [
'messages' => $errMessages,
'redirect_url' => $redirectUrl,
];
} | php | public function loginAction()
{
/** @var AuthService $auth */
$auth = $this->_getAuthService();
if ($auth->identity()->hasAuthenticated()) {
// : User is authorized
$this->redirect()->toRoute(\yimaAdminor\Module::ADMIN_ROUTE_NAME);
return $this->getResponse();
}
/** @var $request \Zend\Http\PhpEnvironment\Request */
$request = $this->getRequest();
// Get redirect-url:
$redirectUrl = $auth->getGuard()->getStoredUrl();
if($request->isPost() && empty($redirectUrl))
$redirectUrl = $this->params()->fromPost('redirect_url');
if ($request->isPost()) {
$user = $this->params()->fromPost('login-username');
$pass = $this->params()->fromPost('login-password');
$rmbr = $this->params()->fromPost('login-remember-me', false);
$authAdabter = $auth->getAuthAdapter();
$authAdabter->credential(['username' => $user, 'password' => $pass]);
try {
$authAdabter->authenticate();
}
catch (WrongCredentialException $e) {
// set error messages
$this->flashMessenger('adminor.auth.message')->addErrorMessage(
$this->_translator()->translate('Invalid Username Or Password')
);
$this->redirect()->refresh();
return $this->getResponse();
}
catch (AuthenticationException $e) {
// set error messages
$this->flashMessenger('adminor.auth.message')->addErrorMessage(
$this->_translator()->translate('Activation Code Was Sent To Your Mail, Please Check Your Mailbox.')
);
$this->redirect()->refresh();
return $this->getResponse();
}
catch (\Exception $e) {
$this->flashMessenger('adminor.auth.message')->addErrorMessage(
$this->_translator()->translate($e->getMessage())
);
$this->redirect()->refresh();
return $this->getResponse();
}
$authAdabter->getIdentity()
->setRemember($rmbr)
->login();
// Successful login redirect user:
if (!empty($redirectUrl))
$this->redirect()->toUrl($redirectUrl);
else
$this->redirect()->toRoute(\yimaAdminor\Module::ADMIN_ROUTE_NAME);
return $this->getResponse();
}
// Build View:
$errMessages = $this->flashMessenger('adminor.auth.message')->getErrorMessages();
return [
'messages' => $errMessages,
'redirect_url' => $redirectUrl,
];
} | Login | https://github.com/YiMAproject/yimaAdminor/blob/7a6c66e05aedaef8061c8998dfa44ac1ce9cc319/src/yimaAdminor/Controller/AccountController.php#L19-L97 |
YiMAproject/yimaAdminor | src/yimaAdminor/Controller/AccountController.php | AccountController.logoutAction | public function logoutAction()
{
$this->_getAuthService()
->identity()->logout();
$this->redirect()->toRoute('yima_adminor_auth');
return $this->getResponse();
} | php | public function logoutAction()
{
$this->_getAuthService()
->identity()->logout();
$this->redirect()->toRoute('yima_adminor_auth');
return $this->getResponse();
} | Logout | https://github.com/YiMAproject/yimaAdminor/blob/7a6c66e05aedaef8061c8998dfa44ac1ce9cc319/src/yimaAdminor/Controller/AccountController.php#L102-L109 |
schpill/thin | src/Bag.php | Bag.set | public function set($key, $value)
{
$this->values[$this->normalizeKey($key)] = $value;
return $this;
} | php | public function set($key, $value)
{
$this->values[$this->normalizeKey($key)] = $value;
return $this;
} | Set data key to value
@param string $key The data key
@param mixed $value The data value | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Bag.php#L40-L45 |
schpill/thin | src/Bag.php | Bag.get | public function get($key, $default = null)
{
if ($this->has($key)) {
$isInvokable = is_object($this->values[$this->normalizeKey($key)]) && method_exists($this->values[$this->normalizeKey($key)], '__invoke');
return $isInvokable
? $this->values[$this->normalizeKey($key)]($this)
: $this->values[$this->normalizeKey($key)];
}
return $default;
} | php | public function get($key, $default = null)
{
if ($this->has($key)) {
$isInvokable = is_object($this->values[$this->normalizeKey($key)]) && method_exists($this->values[$this->normalizeKey($key)], '__invoke');
return $isInvokable
? $this->values[$this->normalizeKey($key)]($this)
: $this->values[$this->normalizeKey($key)];
}
return $default;
} | Get values value with key
@param string $key The values key
@param mixed $default The value to return if values key does not exist
@return mixed The values value, or the default value | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Bag.php#L53-L64 |
YiMAproject/yimaAdminor | src/yimaAdminor/Auth/AuthService.php | AuthService.isAllowed | function isAllowed(/*iAuthResource*/ $resource = null, /*iIdentity*/ $role = null)
{
$role = ($role) ?: $this->identity();
if (!is_object($resource)
|| (!$resource instanceof PermResource || !method_exists($resource, 'getRouteMatch'))
)
throw new \Exception('Invalid Resource Type, Can`t Check The Permissions.');
$return = true;
$matchedRouteName = $resource->getRouteMatch()->getMatchedRouteName();
// Access Admin Route Need Authorized User
if ($matchedRouteName == \yimaAdminor\Module::ADMIN_ROUTE_NAME)
$return = $return && $role->hasAuthenticated();
return $return;
} | php | function isAllowed(/*iAuthResource*/ $resource = null, /*iIdentity*/ $role = null)
{
$role = ($role) ?: $this->identity();
if (!is_object($resource)
|| (!$resource instanceof PermResource || !method_exists($resource, 'getRouteMatch'))
)
throw new \Exception('Invalid Resource Type, Can`t Check The Permissions.');
$return = true;
$matchedRouteName = $resource->getRouteMatch()->getMatchedRouteName();
// Access Admin Route Need Authorized User
if ($matchedRouteName == \yimaAdminor\Module::ADMIN_ROUTE_NAME)
$return = $return && $role->hasAuthenticated();
return $return;
} | Is allowed to features?
@param null|iAuthResource $resource
@param null|iIdentity $role
@throws \Exception
@return boolean | https://github.com/YiMAproject/yimaAdminor/blob/7a6c66e05aedaef8061c8998dfa44ac1ce9cc319/src/yimaAdminor/Auth/AuthService.php#L39-L57 |
YiMAproject/yimaAdminor | src/yimaAdminor/Auth/AuthService.php | AuthService.identity | function identity()
{
if (!$this->identity)
$this->identity = new BaseIdentity(get_class($this));
return $this->identity;
} | php | function identity()
{
if (!$this->identity)
$this->identity = new BaseIdentity(get_class($this));
return $this->identity;
} | Get Authorized User Identity
- identities must inject into adapter by auth services
@throws \Exception Not Identity Available Or Set
@return BaseIdentity | https://github.com/YiMAproject/yimaAdminor/blob/7a6c66e05aedaef8061c8998dfa44ac1ce9cc319/src/yimaAdminor/Auth/AuthService.php#L67-L73 |
YiMAproject/yimaAdminor | src/yimaAdminor/Auth/AuthService.php | AuthService.getAuthAdapter | function getAuthAdapter()
{
if (!$this->authAdapter)
$this->setAuthAdapter(new DigestFileAuthAdapter);
// always use current identity
$this->authAdapter->setIdentity($this->identity());
return $this->authAdapter;
} | php | function getAuthAdapter()
{
if (!$this->authAdapter)
$this->setAuthAdapter(new DigestFileAuthAdapter);
// always use current identity
$this->authAdapter->setIdentity($this->identity());
return $this->authAdapter;
} | Get Authenticate Adapter
@return iAuthenticateAdapter | https://github.com/YiMAproject/yimaAdminor/blob/7a6c66e05aedaef8061c8998dfa44ac1ce9cc319/src/yimaAdminor/Auth/AuthService.php#L80-L89 |
YiMAproject/yimaAdminor | src/yimaAdminor/Auth/AuthService.php | AuthService.riseException | function riseException(\Exception $exception = null)
{
($exception !== null) ?: $exception = new AccessDeniedException();
throw new AuthException($this, $exception->getCode(), $exception);
} | php | function riseException(\Exception $exception = null)
{
($exception !== null) ?: $exception = new AccessDeniedException();
throw new AuthException($this, $exception->getCode(), $exception);
} | Throw Exception
- usually inject $this Object argument into AuthException Class
on return, so later to handle the error with guards we can
response only for errors that rise from related AuthService
- recommend exception have valid http response code as exception code
@param AccessDeniedException|\Exception $exception
@throws AuthException | https://github.com/YiMAproject/yimaAdminor/blob/7a6c66e05aedaef8061c8998dfa44ac1ce9cc319/src/yimaAdminor/Auth/AuthService.php#L128-L133 |
atelierspierrot/patterns | src/Patterns/Commons/ConfigurationRegistry.php | ConfigurationRegistry.set | public function set($name, $value, $scope = null)
{
if (strpos($name, ':')) {
list($entry, $name) = explode(':', $name);
$cfg = $this->getConfig($entry, array(), $scope);
$cfg[$name] = $value;
return $this->setConfig($entry, $cfg, $scope);
} else {
return $this->setConfig($name, $value, $scope);
}
} | php | public function set($name, $value, $scope = null)
{
if (strpos($name, ':')) {
list($entry, $name) = explode(':', $name);
$cfg = $this->getConfig($entry, array(), $scope);
$cfg[$name] = $value;
return $this->setConfig($entry, $cfg, $scope);
} else {
return $this->setConfig($name, $value, $scope);
}
} | Set the value of a specific option with depth
@param string $name The index of the configuration value to get, with a scope using notation `index:name`
@param mixed $value The value to set for $name
@param string $scope The scope to use in the configuration registry if it is not defined in the `$name` parameter
@return self | https://github.com/atelierspierrot/patterns/blob/b7a8313e98bbfb6525e1672d0a726a1ead6f156e/src/Patterns/Commons/ConfigurationRegistry.php#L62-L72 |
atelierspierrot/patterns | src/Patterns/Commons/ConfigurationRegistry.php | ConfigurationRegistry.get | public function get($name, $default = null, $scope = null)
{
if (strpos($name, ':')) {
list($entry, $name) = explode(':', $name);
$cfg = $this->getConfig($entry, array(), $scope);
return isset($cfg[$name]) ? $cfg[$name] : $default;
} else {
return $this->getConfig($name, $default, $scope);
}
} | php | public function get($name, $default = null, $scope = null)
{
if (strpos($name, ':')) {
list($entry, $name) = explode(':', $name);
$cfg = $this->getConfig($entry, array(), $scope);
return isset($cfg[$name]) ? $cfg[$name] : $default;
} else {
return $this->getConfig($name, $default, $scope);
}
} | Get the value of a specific option with depth
@param string $name The index of the configuration value to get, with a scope using notation `index:name`
@param mixed $default The default value to return if so (`null` by default)
@param string $scope The scope to use in the configuration registry if it is not defined in the `$name` parameter
@return mixed The value retrieved in the registry or the default value otherwise | https://github.com/atelierspierrot/patterns/blob/b7a8313e98bbfb6525e1672d0a726a1ead6f156e/src/Patterns/Commons/ConfigurationRegistry.php#L82-L91 |
atelierspierrot/patterns | src/Patterns/Commons/ConfigurationRegistry.php | ConfigurationRegistry.setConfigs | public function setConfigs(array $options, $scope = null)
{
if (!is_null($scope)) {
$this->registry[$scope] = $options;
} else {
$this->registry = $options;
}
return $this;
} | php | public function setConfigs(array $options, $scope = null)
{
if (!is_null($scope)) {
$this->registry[$scope] = $options;
} else {
$this->registry = $options;
}
return $this;
} | Set an array of options
@param array $options The array of values to set for the configuration entry
@param string $scope The scope to use in the configuration registry (optional)
@return self | https://github.com/atelierspierrot/patterns/blob/b7a8313e98bbfb6525e1672d0a726a1ead6f156e/src/Patterns/Commons/ConfigurationRegistry.php#L100-L109 |
atelierspierrot/patterns | src/Patterns/Commons/ConfigurationRegistry.php | ConfigurationRegistry.setConfig | public function setConfig($name, $value, $scope = null)
{
if (!is_null($scope)) {
if (!isset($this->registry[$scope])) {
$this->registry[$scope] = array();
}
$this->registry[$scope][$name] = $value;
} else {
$this->registry[$name] = $value;
}
return $this;
} | php | public function setConfig($name, $value, $scope = null)
{
if (!is_null($scope)) {
if (!isset($this->registry[$scope])) {
$this->registry[$scope] = array();
}
$this->registry[$scope][$name] = $value;
} else {
$this->registry[$name] = $value;
}
return $this;
} | Set the value of a specific option (no scope notation allowed here)
@param string $name The index of the configuration value
@param mixed $value The value to set for the configuration entry
@param string $scope The scope to use in the configuration registry (optional)
@return self | https://github.com/atelierspierrot/patterns/blob/b7a8313e98bbfb6525e1672d0a726a1ead6f156e/src/Patterns/Commons/ConfigurationRegistry.php#L119-L131 |
atelierspierrot/patterns | src/Patterns/Commons/ConfigurationRegistry.php | ConfigurationRegistry.addConfig | public function addConfig($name, $value, $scope = null)
{
return $this->setConfig($name, $value, $scope);
} | php | public function addConfig($name, $value, $scope = null)
{
return $this->setConfig($name, $value, $scope);
} | Alias of the `setConfig` method
@see self::setConfig() | https://github.com/atelierspierrot/patterns/blob/b7a8313e98bbfb6525e1672d0a726a1ead6f156e/src/Patterns/Commons/ConfigurationRegistry.php#L138-L141 |
atelierspierrot/patterns | src/Patterns/Commons/ConfigurationRegistry.php | ConfigurationRegistry.getConfigs | public function getConfigs($default = null, $scope = null)
{
if (!is_null($scope)) {
return isset($this->registry[$scope]) ? $this->registry[$scope] : $default;
}
return $this->registry;
} | php | public function getConfigs($default = null, $scope = null)
{
if (!is_null($scope)) {
return isset($this->registry[$scope]) ? $this->registry[$scope] : $default;
}
return $this->registry;
} | Get the array of options (from a specific scope if so)
@param mixed $default The default value to return if so (`null` by default)
@param string $scope The scope to use in the configuration registry (optional)
@return array|mixed|null | https://github.com/atelierspierrot/patterns/blob/b7a8313e98bbfb6525e1672d0a726a1ead6f156e/src/Patterns/Commons/ConfigurationRegistry.php#L150-L156 |
atelierspierrot/patterns | src/Patterns/Commons/ConfigurationRegistry.php | ConfigurationRegistry.getConfig | public function getConfig($name, $default = null, $scope = null)
{
if (!is_null($scope)) {
return isset($this->registry[$scope][$name]) ? $this->registry[$scope][$name] : $default;
}
return isset($this->registry[$name]) ? $this->registry[$name] : $default;
} | php | public function getConfig($name, $default = null, $scope = null)
{
if (!is_null($scope)) {
return isset($this->registry[$scope][$name]) ? $this->registry[$scope][$name] : $default;
}
return isset($this->registry[$name]) ? $this->registry[$name] : $default;
} | Get the value of a specific option (no scope notation allowed here)
@param string $name The index of the configuration value to get
@param mixed $default The default value to return if so (`null` by default)
@param string $scope The scope to use in the configuration registry (optional)
@return mixed | https://github.com/atelierspierrot/patterns/blob/b7a8313e98bbfb6525e1672d0a726a1ead6f156e/src/Patterns/Commons/ConfigurationRegistry.php#L166-L172 |
simpleapisecurity/php | src/Entropy.php | Entropy.bytes | static function bytes($bytes = Constants::BYTES)
{
# Test the length for validity.
Helpers::rangeCheck($bytes, Constants::BYTES_MAX, Constants::BYTES_MIN, 'Entropy', 'bytes');
return \Sodium\randombytes_buf($bytes);
} | php | static function bytes($bytes = Constants::BYTES)
{
# Test the length for validity.
Helpers::rangeCheck($bytes, Constants::BYTES_MAX, Constants::BYTES_MIN, 'Entropy', 'bytes');
return \Sodium\randombytes_buf($bytes);
} | Returns a string of random bytes to the client.
@param int $bytes Size of the string of bytes to be generated.
@return string
@throws Exceptions\InvalidTypeException
@throws Exceptions\OutOfRangeException | https://github.com/simpleapisecurity/php/blob/e6cebf3213f4d7be54aa3a188d95a00113e3fda0/src/Entropy.php#L25-L31 |
simpleapisecurity/php | src/Entropy.php | Entropy.integer | static function integer($range = Constants::RANGE)
{
# Test the length for validity.
Helpers::rangeCheck($range, Constants::RANGE_MAX, Constants::RANGE_MIN, 'Entropy', 'integer');
return \Sodium\randombytes_uniform($range) + 1;
} | php | static function integer($range = Constants::RANGE)
{
# Test the length for validity.
Helpers::rangeCheck($range, Constants::RANGE_MAX, Constants::RANGE_MIN, 'Entropy', 'integer');
return \Sodium\randombytes_uniform($range) + 1;
} | Returns a random integer to the client.
@param int $range Upper limit of random numbers to return to the client.
@return int
@throws Exceptions\InvalidTypeException
@throws Exceptions\OutOfRangeException | https://github.com/simpleapisecurity/php/blob/e6cebf3213f4d7be54aa3a188d95a00113e3fda0/src/Entropy.php#L41-L47 |
alekitto/metadata | lib/Loader/Processor/ProcessorFactory.php | ProcessorFactory.registerProcessor | public function registerProcessor(string $class, string $processorClass): void
{
if (! (new \ReflectionClass($processorClass))->implementsInterface(ProcessorInterface::class)) {
throw InvalidArgumentException::create(InvalidArgumentException::INVALID_PROCESSOR_INTERFACE_CLASS, $processorClass);
}
if (! isset($this->processors[$class])) {
$this->processors[$class] = $processorClass;
} elseif (! is_array($this->processors[$class])) {
$this->processors[$class] = [$this->processors[$class], $processorClass];
} else {
$this->processors[$class][] = $processorClass;
}
} | php | public function registerProcessor(string $class, string $processorClass): void
{
if (! (new \ReflectionClass($processorClass))->implementsInterface(ProcessorInterface::class)) {
throw InvalidArgumentException::create(InvalidArgumentException::INVALID_PROCESSOR_INTERFACE_CLASS, $processorClass);
}
if (! isset($this->processors[$class])) {
$this->processors[$class] = $processorClass;
} elseif (! is_array($this->processors[$class])) {
$this->processors[$class] = [$this->processors[$class], $processorClass];
} else {
$this->processors[$class][] = $processorClass;
}
} | Register a processor class for $class.
@param string $class
@param string $processorClass | https://github.com/alekitto/metadata/blob/0422ac8d7fe72d5fa8cc51b6f1e173866e8afb2c/lib/Loader/Processor/ProcessorFactory.php#L25-L38 |
alekitto/metadata | lib/Loader/Processor/ProcessorFactory.php | ProcessorFactory.getProcessor | public function getProcessor($class): ?ProcessorInterface
{
if (is_object($class)) {
$class = get_class($class);
}
if (! isset($this->processors[$class])) {
return null;
}
if (isset($this->instances[$class])) {
return $this->instances[$class];
}
$processor = $this->processors[$class];
if (is_array($processor)) {
return $this->instances[$class] = $this->createComposite($processor);
}
return $this->instances[$class] = new $processor();
} | php | public function getProcessor($class): ?ProcessorInterface
{
if (is_object($class)) {
$class = get_class($class);
}
if (! isset($this->processors[$class])) {
return null;
}
if (isset($this->instances[$class])) {
return $this->instances[$class];
}
$processor = $this->processors[$class];
if (is_array($processor)) {
return $this->instances[$class] = $this->createComposite($processor);
}
return $this->instances[$class] = new $processor();
} | {@inheritdoc} | https://github.com/alekitto/metadata/blob/0422ac8d7fe72d5fa8cc51b6f1e173866e8afb2c/lib/Loader/Processor/ProcessorFactory.php#L43-L63 |
luoxiaojun1992/lb_framework | controllers/console/ServerController.php | ServerController.index | public function index()
{
$argv = \Console_Getopt::readPHPArgv();
$opts = \Console_Getopt::getopt(array_slice($argv, 2, count($argv) - 2), 'h::p::d::r::', null, true);
if (!empty($opts[0]) && is_array($opts[0])) {
foreach ($opts[0] as $val) {
if (!empty($val[0]) && !empty($val[1]) && is_string($val[0]) && is_string($val[1])) {
switch ($val[0]) {
case 'h':
$this->host = $val[1];
break;
case 'p':
$this->port = $val[1];
break;
case 'd':
$this->docroot = $val[1];
break;
case 'r':
$this->router = $val[1];
break;
}
}
}
}
$documentRoot = $this->docroot;
$address = $this->host . ':' . $this->port;
if (!is_dir($documentRoot)) {
Lb::app()->stop("Document root \"$documentRoot\" does not exist.\n", self::EXIT_CODE_NO_DOCUMENT_ROOT);
}
if ($this->isAddressTaken($address)) {
Lb::app()->stop("http://$address is taken by another process.\n", self::EXIT_CODE_ADDRESS_TAKEN_BY_ANOTHER_PROCESS);
}
if ($this->router !== null && !file_exists($this->router)) {
Lb::app()->stop("Routing file \"$this->router\" does not exist.\n", self::EXIT_CODE_NO_ROUTING_FILE);
}
$this->writeln("Server started on http://{$address}/\n");
$this->writeln("Document root is \"{$documentRoot}\"\n");
if ($this->router) {
$this->writeln("Routing file is \"$this->router\"\n");
}
$this->writeln("Quit the server with CTRL-C or COMMAND-C.\n");
passthru('"' . PHP_BINARY . '"' . " -S {$address} -t \"{$documentRoot}\" $this->router");
} | php | public function index()
{
$argv = \Console_Getopt::readPHPArgv();
$opts = \Console_Getopt::getopt(array_slice($argv, 2, count($argv) - 2), 'h::p::d::r::', null, true);
if (!empty($opts[0]) && is_array($opts[0])) {
foreach ($opts[0] as $val) {
if (!empty($val[0]) && !empty($val[1]) && is_string($val[0]) && is_string($val[1])) {
switch ($val[0]) {
case 'h':
$this->host = $val[1];
break;
case 'p':
$this->port = $val[1];
break;
case 'd':
$this->docroot = $val[1];
break;
case 'r':
$this->router = $val[1];
break;
}
}
}
}
$documentRoot = $this->docroot;
$address = $this->host . ':' . $this->port;
if (!is_dir($documentRoot)) {
Lb::app()->stop("Document root \"$documentRoot\" does not exist.\n", self::EXIT_CODE_NO_DOCUMENT_ROOT);
}
if ($this->isAddressTaken($address)) {
Lb::app()->stop("http://$address is taken by another process.\n", self::EXIT_CODE_ADDRESS_TAKEN_BY_ANOTHER_PROCESS);
}
if ($this->router !== null && !file_exists($this->router)) {
Lb::app()->stop("Routing file \"$this->router\" does not exist.\n", self::EXIT_CODE_NO_ROUTING_FILE);
}
$this->writeln("Server started on http://{$address}/\n");
$this->writeln("Document root is \"{$documentRoot}\"\n");
if ($this->router) {
$this->writeln("Routing file is \"$this->router\"\n");
}
$this->writeln("Quit the server with CTRL-C or COMMAND-C.\n");
passthru('"' . PHP_BINARY . '"' . " -S {$address} -t \"{$documentRoot}\" $this->router");
} | Runs PHP built-in web server
@param string $address address to serve on. Either "host" or "host:port".
@return int | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/controllers/console/ServerController.php#L39-L82 |
issei-m/spike-php | src/Model/Factory/CardFactory.php | CardFactory.create | public function create(array $data)
{
$creditCard = new Card();
$creditCard
->setCardNumberLast4($data['last4'])
->setBrand($data['brand'])
->setExpirationMonth(intval($data['exp_month']))
->setExpirationYear(intval($data['exp_year']))
->setHolderName($data['name'])
;
return $creditCard;
} | php | public function create(array $data)
{
$creditCard = new Card();
$creditCard
->setCardNumberLast4($data['last4'])
->setBrand($data['brand'])
->setExpirationMonth(intval($data['exp_month']))
->setExpirationYear(intval($data['exp_year']))
->setHolderName($data['name'])
;
return $creditCard;
} | {@inheritdoc} | https://github.com/issei-m/spike-php/blob/9205b5047a1132bcdca6731feac02fe3d5dc1023/src/Model/Factory/CardFactory.php#L25-L37 |
syzygypl/remote-media-bundle | src/MediaHandler/RemoteFileHandler.php | RemoteFileHandler.saveMedia | public function saveMedia(Media $media)
{
if (!$media->getContent() instanceof File) {
return;
}
$this->uploader->uploadMedia($media);
} | php | public function saveMedia(Media $media)
{
if (!$media->getContent() instanceof File) {
return;
}
$this->uploader->uploadMedia($media);
} | @param Media $media
@return void | https://github.com/syzygypl/remote-media-bundle/blob/2be3284d5baf8a12220ecbaf63043eb105eb87ef/src/MediaHandler/RemoteFileHandler.php#L81-L88 |
phramework/phramework | src/Models/Compress.php | Compress.decompress | public static function decompress(
$compressedFile,
$destinationFolder,
$originalFilename = null,
$format = 'gz',
$allowedExtensions = [
'csv',
'tsv'
]
) {
//TODO ADD tar.gz
$supported_formats = [ 'gz', 'zip', 'tar'];
if (!in_array($format, $supported_formats)) {
throw new \Exception('Unsupported compression format');
}
switch ($format) {
case 'gz':
return self::decompressGz(
$compressedFile,
$destinationFolder,
$originalFilename,
$allowedExtensions
);
case 'zip':
return self::decompressZip(
$compressedFile,
$destinationFolder,
$originalFilename,
$allowedExtensions
);
case 'tar':
return self::decompressTar(
$compressedFile,
$destinationFolder,
$originalFilename,
$allowedExtensions
);
}
} | php | public static function decompress(
$compressedFile,
$destinationFolder,
$originalFilename = null,
$format = 'gz',
$allowedExtensions = [
'csv',
'tsv'
]
) {
//TODO ADD tar.gz
$supported_formats = [ 'gz', 'zip', 'tar'];
if (!in_array($format, $supported_formats)) {
throw new \Exception('Unsupported compression format');
}
switch ($format) {
case 'gz':
return self::decompressGz(
$compressedFile,
$destinationFolder,
$originalFilename,
$allowedExtensions
);
case 'zip':
return self::decompressZip(
$compressedFile,
$destinationFolder,
$originalFilename,
$allowedExtensions
);
case 'tar':
return self::decompressTar(
$compressedFile,
$destinationFolder,
$originalFilename,
$allowedExtensions
);
}
} | decompress a file archive
@param string $compressedFile Archive path
@param string $destinationFolder Destination folder to decompress files
@param string $originalFilename Original file name
@param string $format Select format mode, Default is gz, gz, zip and tar are available.
@param string[] $allowedExtensions
@return array Returns a list with the decompressed files
@throws \Exception | https://github.com/phramework/phramework/blob/40041d1ef23b1f8cdbd26fb112448d6a3dbef012/src/Models/Compress.php#L42-L80 |
SpoonX/SxMail | src/SxMail/Service/SxMailService.php | SxMailService.getConfig | public function getConfig($configKey = null)
{
$default = clone $this->config->configs->default;
if (null !== $configKey) {
$default->merge(clone $this->config->configs->{$configKey});
}
return $default->toArray();
} | php | public function getConfig($configKey = null)
{
$default = clone $this->config->configs->default;
if (null !== $configKey) {
$default->merge(clone $this->config->configs->{$configKey});
}
return $default->toArray();
} | Get the default config, merged with an option overriding config.
@param string $configKey
@return array The merged configuration | https://github.com/SpoonX/SxMail/blob/b0663169cd246ba091f7c84785c69d051a652385/src/SxMail/Service/SxMailService.php#L45-L54 |
cyberspectrum/i18n-contao | src/Mapping/Terminal42ChangeLanguage/PageMap.php | PageMap.buildMap | protected function buildMap(): void
{
$roots = $this->findRootPages();
$this->buildPageMap($roots['main'], $roots['source'], $this->sourceMap, $this->sourceMapInverse);
$this->buildPageMap($roots['main'], $roots['target'], $this->targetMap, $this->targetMapInverse);
$this->combineSourceAndTargetMaps();
} | php | protected function buildMap(): void
{
$roots = $this->findRootPages();
$this->buildPageMap($roots['main'], $roots['source'], $this->sourceMap, $this->sourceMapInverse);
$this->buildPageMap($roots['main'], $roots['target'], $this->targetMap, $this->targetMapInverse);
$this->combineSourceAndTargetMaps();
} | Build the map.
@return void | https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/Mapping/Terminal42ChangeLanguage/PageMap.php#L79-L86 |
cyberspectrum/i18n-contao | src/Mapping/Terminal42ChangeLanguage/PageMap.php | PageMap.findRootPages | private function findRootPages(): array
{
$result = [
'source' => null,
'target' => null,
'main' => null,
];
$this->logger->debug(
'Searching root pages for source "{source}" and target "{target}"',
['source' => $this->sourceLanguage, 'target' => $this->targetLanguage]
);
foreach ($this->database->getRootPages() as $root) {
$language = $root['language'];
if ('1' === $root['fallback']) {
$this->mainLanguage = $language;
$result['main'] = (int) $root['id'];
}
if ($language === $this->sourceLanguage) {
$result['source'] = (int) $root['id'];
}
if ($language === $this->targetLanguage) {
$result['target'] = (int) $root['id'];
}
// Keep type for being able to filter unknown pages in i.e. articles.
$this->types[(int) $root['id']] = 'root';
}
$this->logger->debug(
'Found root pages: source: {source}; target: {target}; main: {main}',
$result
);
if (null === $result['source'] || null === $result['target'] || null === $result['main']) {
throw new \RuntimeException('Not all root pages could be found: ' . var_export($result, true));
}
return $result;
} | php | private function findRootPages(): array
{
$result = [
'source' => null,
'target' => null,
'main' => null,
];
$this->logger->debug(
'Searching root pages for source "{source}" and target "{target}"',
['source' => $this->sourceLanguage, 'target' => $this->targetLanguage]
);
foreach ($this->database->getRootPages() as $root) {
$language = $root['language'];
if ('1' === $root['fallback']) {
$this->mainLanguage = $language;
$result['main'] = (int) $root['id'];
}
if ($language === $this->sourceLanguage) {
$result['source'] = (int) $root['id'];
}
if ($language === $this->targetLanguage) {
$result['target'] = (int) $root['id'];
}
// Keep type for being able to filter unknown pages in i.e. articles.
$this->types[(int) $root['id']] = 'root';
}
$this->logger->debug(
'Found root pages: source: {source}; target: {target}; main: {main}',
$result
);
if (null === $result['source'] || null === $result['target'] || null === $result['main']) {
throw new \RuntimeException('Not all root pages could be found: ' . var_export($result, true));
}
return $result;
} | Determine the root pages.
@return int[]
@throws \RuntimeException When a root page is missing. | https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/Mapping/Terminal42ChangeLanguage/PageMap.php#L95-L136 |
cyberspectrum/i18n-contao | src/Mapping/Terminal42ChangeLanguage/PageMap.php | PageMap.buildPageMap | private function buildPageMap(int $mainRoot, int $otherRoot, array &$map, array &$inverse): array
{
// Root pages are mapped to each other.
$map[$otherRoot] = $mainRoot;
$inverse[$mainRoot] = $otherRoot;
// Now fetch all other.
$isMain = $mainRoot === $otherRoot;
$lookupQueue = [$otherRoot];
do {
// Fetch children of parents in queue.
$children = $this->database->getPagesByPidList($lookupQueue);
// Nothing to do anymore, break it.
if (empty($children)) {
break;
}
// Reset pid list - we have the children.
$lookupQueue = [];
foreach ($children as $index => $child) {
$childId = (int) $child['id'];
$main = $isMain ? $childId : (int) $child['languageMain'];
// Try to determine automatically.
if (!$isMain && empty($main)) {
if (null === ($main = $this->determineMapFor($index, (int) $child['pid'], $map))) {
$this->logger->warning(
'Page {id} has no fallback set and unable to determine automatically. Page skipped.',
['id' => $childId]
);
continue;
}
$this->logger->warning(
'Page {id} (index: {index}) has no fallback set, expect problems, I guess it is {guessed}',
['id' => $childId, 'index' => $index, 'guessed' => $main]
);
}
$map[$childId] = $main;
$inverse[$main] = $childId;
// Keep type for being able to filter unknown pages in i.e. articles.
$this->types[$childId] = $child['type'];
$lookupQueue[] = $childId;
}
} while (true);
return $map;
} | php | private function buildPageMap(int $mainRoot, int $otherRoot, array &$map, array &$inverse): array
{
// Root pages are mapped to each other.
$map[$otherRoot] = $mainRoot;
$inverse[$mainRoot] = $otherRoot;
// Now fetch all other.
$isMain = $mainRoot === $otherRoot;
$lookupQueue = [$otherRoot];
do {
// Fetch children of parents in queue.
$children = $this->database->getPagesByPidList($lookupQueue);
// Nothing to do anymore, break it.
if (empty($children)) {
break;
}
// Reset pid list - we have the children.
$lookupQueue = [];
foreach ($children as $index => $child) {
$childId = (int) $child['id'];
$main = $isMain ? $childId : (int) $child['languageMain'];
// Try to determine automatically.
if (!$isMain && empty($main)) {
if (null === ($main = $this->determineMapFor($index, (int) $child['pid'], $map))) {
$this->logger->warning(
'Page {id} has no fallback set and unable to determine automatically. Page skipped.',
['id' => $childId]
);
continue;
}
$this->logger->warning(
'Page {id} (index: {index}) has no fallback set, expect problems, I guess it is {guessed}',
['id' => $childId, 'index' => $index, 'guessed' => $main]
);
}
$map[$childId] = $main;
$inverse[$main] = $childId;
// Keep type for being able to filter unknown pages in i.e. articles.
$this->types[$childId] = $child['type'];
$lookupQueue[] = $childId;
}
} while (true);
return $map;
} | Build a map for a language and returns the map from source to main.
@param int $mainRoot The main language root page.
@param int $otherRoot The root page of the other language.
@param array $map The mapping array to populate.
@param array $inverse The inverse mapping.
@return int[] | https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/Mapping/Terminal42ChangeLanguage/PageMap.php#L148-L198 |
cyberspectrum/i18n-contao | src/Mapping/Terminal42ChangeLanguage/PageMap.php | PageMap.determineMapFor | private function determineMapFor(int $index, int $parentId, array $inverseList): ?int
{
if (!isset($inverseList[$parentId])) {
throw new \InvalidArgumentException(
'Page id ' . $parentId . ' has not been mapped'
);
}
// Lookup all children of parent page in main language.
$mainSiblings = $this->database->getPagesByPidList([$inverseList[$parentId]]);
return isset($mainSiblings[$index]) ? (int) $mainSiblings[$index]['id'] : null;
} | php | private function determineMapFor(int $index, int $parentId, array $inverseList): ?int
{
if (!isset($inverseList[$parentId])) {
throw new \InvalidArgumentException(
'Page id ' . $parentId . ' has not been mapped'
);
}
// Lookup all children of parent page in main language.
$mainSiblings = $this->database->getPagesByPidList([$inverseList[$parentId]]);
return isset($mainSiblings[$index]) ? (int) $mainSiblings[$index]['id'] : null;
} | Determine the mapping for the passed index.
@param int $index The index to look up.
@param int $parentId The parent id.
@param array $inverseList The reverse lookup list.
@return int|null
@throws \InvalidArgumentException When the parent page has not been mapped. | https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/Mapping/Terminal42ChangeLanguage/PageMap.php#L211-L223 |
Phpillip/phpillip | src/Application.php | Application.registerServiceProviders | public function registerServiceProviders()
{
$this->register(new SilexProvider\HttpFragmentServiceProvider());
$this->register(new SilexProvider\UrlGeneratorServiceProvider());
$this->register(new SilexProvider\ServiceControllerServiceProvider());
$this->register(new PhpillipProvider\InformatorServiceProvider());
$this->register(new PhpillipProvider\PygmentsServiceProvider());
$this->register(new PhpillipProvider\ParsedownServiceProvider());
$this->register(new PhpillipProvider\DecoderServiceProvider());
$this->register(new PhpillipProvider\ContentServiceProvider());
$this->register(new PhpillipProvider\TwigServiceProvider());
$this->register(new PhpillipProvider\SubscriberServiceProvider());
$this->register(new PhpillipProvider\ContentControllerServiceProvider());
} | php | public function registerServiceProviders()
{
$this->register(new SilexProvider\HttpFragmentServiceProvider());
$this->register(new SilexProvider\UrlGeneratorServiceProvider());
$this->register(new SilexProvider\ServiceControllerServiceProvider());
$this->register(new PhpillipProvider\InformatorServiceProvider());
$this->register(new PhpillipProvider\PygmentsServiceProvider());
$this->register(new PhpillipProvider\ParsedownServiceProvider());
$this->register(new PhpillipProvider\DecoderServiceProvider());
$this->register(new PhpillipProvider\ContentServiceProvider());
$this->register(new PhpillipProvider\TwigServiceProvider());
$this->register(new PhpillipProvider\SubscriberServiceProvider());
$this->register(new PhpillipProvider\ContentControllerServiceProvider());
} | Register service providers | https://github.com/Phpillip/phpillip/blob/c37afaafb536361e7e0b564659f1cd5b80b98be9/src/Application.php#L32-L45 |
skck/SbkCronBundle | Cron/Task.php | Task.getCommandToExecute | public function getCommandToExecute()
{
$command = implode(
" ",
array(
$this->bin,
$this->script,
$this->command,
)
);
return trim(preg_replace('/\s+/', ' ', $command));
} | php | public function getCommandToExecute()
{
$command = implode(
" ",
array(
$this->bin,
$this->script,
$this->command,
)
);
return trim(preg_replace('/\s+/', ' ', $command));
} | Returns the executable command for the task instance
@return string | https://github.com/skck/SbkCronBundle/blob/9a3d2bedfcee76587691a19abc7c25e62039d440/Cron/Task.php#L150-L161 |
dpeuscher/DpOpenGis | src/DpOpenGis/Validator/Point.php | Point._isValidByTypes | public function _isValidByTypes($value) {
/**
* @var array $value
*/
extract($value);
/** @var float $lat */
/** @var float $lon */
if (!is_float($lat)) $this->error(self::LATINVALID,var_export($lat,true));
if (!is_float($lon)) $this->error(self::LONINVALID,var_export($lon,true));
if (array() !== ($this->getMessages()))
return false;
return true;
} | php | public function _isValidByTypes($value) {
/**
* @var array $value
*/
extract($value);
/** @var float $lat */
/** @var float $lon */
if (!is_float($lat)) $this->error(self::LATINVALID,var_export($lat,true));
if (!is_float($lon)) $this->error(self::LONINVALID,var_export($lon,true));
if (array() !== ($this->getMessages()))
return false;
return true;
} | Returns true if and only if $value meets the validation requirements
If $value fails validation, then this method returns false, and
getMessages() will return an array of messages that explain why the
validation failed.
@param mixed $value
@return bool
@throws \Zend\Validator\Exception\RuntimeException If validation of $value is impossible | https://github.com/dpeuscher/DpOpenGis/blob/08866014ea05f54d029cc308d269c28779f9eaa9/src/DpOpenGis/Validator/Point.php#L42-L56 |
dpeuscher/DpOpenGis | src/DpOpenGis/Validator/Point.php | Point._isValidByDependencies | public function _isValidByDependencies($value) {
/**
* @var array $value
*/
extract($value);
/** @var float $lat */
/** @var float $lon */
if ($lat < -90 || $lat > 90) $this->error(self::WRONGLAT,var_export($lat,true));
if ($lon < -180 || $lon > 180) $this->error(self::WRONGLON,var_export($lon,true));
if (array() !== $this->getMessages())
return false;
return true;
} | php | public function _isValidByDependencies($value) {
/**
* @var array $value
*/
extract($value);
/** @var float $lat */
/** @var float $lon */
if ($lat < -90 || $lat > 90) $this->error(self::WRONGLAT,var_export($lat,true));
if ($lon < -180 || $lon > 180) $this->error(self::WRONGLON,var_export($lon,true));
if (array() !== $this->getMessages())
return false;
return true;
} | Returns true if and only if $value meets the validation requirements
If $value fails validation, then this method returns false, and
getMessages() will return an array of messages that explain why the
validation failed.
@param mixed $value
@return bool
@throws \Zend\Validator\Exception\RuntimeException If validation of $value is impossible | https://github.com/dpeuscher/DpOpenGis/blob/08866014ea05f54d029cc308d269c28779f9eaa9/src/DpOpenGis/Validator/Point.php#L68-L83 |
jasny/iterator-stream | src/LineOutputStream.php | LineOutputStream.writeElement | protected function writeElement($element): void
{
fwrite($this->stream, (string)$element . $this->endline);
} | php | protected function writeElement($element): void
{
fwrite($this->stream, (string)$element . $this->endline);
} | Write an element to the stream.
@param mixed $element
@return void | https://github.com/jasny/iterator-stream/blob/a4d63eb2825956a879740cc44addd6170f7a481d/src/LineOutputStream.php#L36-L39 |
stonedz/pff2 | src/Core/ViewPHP.php | ViewPHP.preView | public function preView($output) {
/** @var $purifierConfig \HTMLPurifier_Config */
$purifierConfig = \HTMLPurifier_Config::createDefault();
$purifierConfig->set('Core.Encoding', 'UTF-8');
$purifierConfig->set('HTML.TidyLevel', 'medium');
/** @var \HTMLPurifier_Config $purifierConfig */
$purifier = new \HTMLPurifier($purifierConfig);
$output = $purifier->purify($output);
return $output;
} | php | public function preView($output) {
/** @var $purifierConfig \HTMLPurifier_Config */
$purifierConfig = \HTMLPurifier_Config::createDefault();
$purifierConfig->set('Core.Encoding', 'UTF-8');
$purifierConfig->set('HTML.TidyLevel', 'medium');
/** @var \HTMLPurifier_Config $purifierConfig */
$purifier = new \HTMLPurifier($purifierConfig);
$output = $purifier->purify($output);
return $output;
} | Callback method to sanitize HTML output
@param string $output HTML output string
@return string | https://github.com/stonedz/pff2/blob/ec3b087d4d4732816f61ac487f0cb25511e0da88/src/Core/ViewPHP.php#L70-L81 |
prooph/processing | library/Environment/Initializer/WorkflowProcessorBusesProvider.php | WorkflowProcessorBusesProvider.initialize | public function initialize($instance, ServiceLocator $serviceLocator)
{
if ($instance instanceof WorkflowMessageHandler) {
/** @var $env Environment */
$env = $serviceLocator->get(Definition::SERVICE_ENVIRONMENT);
$instance->useWorkflowEngine($env->getWorkflowEngine());
}
} | php | public function initialize($instance, ServiceLocator $serviceLocator)
{
if ($instance instanceof WorkflowMessageHandler) {
/** @var $env Environment */
$env = $serviceLocator->get(Definition::SERVICE_ENVIRONMENT);
$instance->useWorkflowEngine($env->getWorkflowEngine());
}
} | Initialize
@param $instance
@param ServiceLocator $serviceLocator
@return mixed | https://github.com/prooph/processing/blob/a2947bccbffeecc4ca93a15e38ab53814e3e53e5/library/Environment/Initializer/WorkflowProcessorBusesProvider.php#L37-L45 |
phavour/phavour | Phavour/Auth/Service.php | Service.login | public function login()
{
$result = $this->adapter->getResult();
if ($result === self::PHAVOUR_AUTH_SERVICE_SUCCESS) {
$auth = Auth::getInstance();
$auth->login($this->adapter->getIdentity());
$auth->setRoles($this->adapter->getRoles());
return true;
} elseif ($result === self::PHAVOUR_AUTH_SERVICE_INVALID) {
throw new InvalidCredentialsException('Invalid credentials exception');
}
throw new UnrecognisedAuthenticationResultException('Expected 1 or 2');
} | php | public function login()
{
$result = $this->adapter->getResult();
if ($result === self::PHAVOUR_AUTH_SERVICE_SUCCESS) {
$auth = Auth::getInstance();
$auth->login($this->adapter->getIdentity());
$auth->setRoles($this->adapter->getRoles());
return true;
} elseif ($result === self::PHAVOUR_AUTH_SERVICE_INVALID) {
throw new InvalidCredentialsException('Invalid credentials exception');
}
throw new UnrecognisedAuthenticationResultException('Expected 1 or 2');
} | Log a user in using the given adapter from the construct
@throws InvalidCredentialsException
@throws UnrecognisedAuthenticationResultException
@return boolean|throws | https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Auth/Service.php#L77-L92 |
gbprod/doctrine-specification | src/DoctrineSpecification/QueryFactory/OrXFactory.php | OrXFactory.create | public function create(Specification $spec, QueryBuilder $qb)
{
if (!$spec instanceof OrX) {
throw new \InvalidArgumentException();
}
$firstPartFactory = $this->registry->getFactory($spec->getFirstPart());
$secondPartFactory = $this->registry->getFactory($spec->getSecondPart());
return $qb->expr()->orx(
$firstPartFactory->create($spec->getFirstPart(), $qb),
$secondPartFactory->create($spec->getSecondPart(), $qb)
);
} | php | public function create(Specification $spec, QueryBuilder $qb)
{
if (!$spec instanceof OrX) {
throw new \InvalidArgumentException();
}
$firstPartFactory = $this->registry->getFactory($spec->getFirstPart());
$secondPartFactory = $this->registry->getFactory($spec->getSecondPart());
return $qb->expr()->orx(
$firstPartFactory->create($spec->getFirstPart(), $qb),
$secondPartFactory->create($spec->getSecondPart(), $qb)
);
} | {inheritdoc} | https://github.com/gbprod/doctrine-specification/blob/348e8ec31547f4949a193d21b3a1d5cdb48b23cb/src/DoctrineSpecification/QueryFactory/OrXFactory.php#L35-L48 |
bavix/laravel-helpers | src/Illuminate/Support/Facades/Schema.php | Schema.schemaBuilder | protected static function schemaBuilder($name = null)
{
/**
* @var $db \Illuminate\Database\DatabaseManager
*/
$db = static::$app['db'];
$builder = $db->connection($name)->getSchemaBuilder();
$builder->blueprintResolver(function ($table, $callback) {
return new Blueprint($table, $callback);
});
return $builder;
} | php | protected static function schemaBuilder($name = null)
{
/**
* @var $db \Illuminate\Database\DatabaseManager
*/
$db = static::$app['db'];
$builder = $db->connection($name)->getSchemaBuilder();
$builder->blueprintResolver(function ($table, $callback) {
return new Blueprint($table, $callback);
});
return $builder;
} | @param string|null $name
@return \Illuminate\Database\Schema\Builder | https://github.com/bavix/laravel-helpers/blob/a713460d2647a58b3eb8279d2a2726034ca79876/src/Illuminate/Support/Facades/Schema.php#L24-L38 |
makinacorpus/drupal-calista | src/Action/CoreNodeActionProvider.php | CoreNodeActionProvider.getActions | public function getActions($item, $primaryOnly = false, array $groups = [])
{
$ret = [];
/** @var \Drupal\node\NodeInterface $item */
if (node_access('view', $item)) {
$ret[] = Action::create([
'title' => $this->t("View"),
'route' => 'node/' . $item->id(),
'options' => [],
'icon' => 'eye-open',
'priority' => -100,
]);
}
if (node_access('update', $item)) {
$ret[] = Action::create([
'title' => $this->t("Edit"),
'route' => 'node/' . $item->id() . '/edit',
'options' => [],
'redirect' => true,
'icon' => 'pencil',
]);
}
if (node_access('delete', $item)) {
$ret[] = Action::create([
'title' => $this->t("Delete"),
'route' => 'node/' . $item->id() . '/delete',
'options' => [],
'icon' => 'trash',
'redirect' => true,
'primary' => false,
'group' => 'danger'
]);
}
return $ret;
} | php | public function getActions($item, $primaryOnly = false, array $groups = [])
{
$ret = [];
/** @var \Drupal\node\NodeInterface $item */
if (node_access('view', $item)) {
$ret[] = Action::create([
'title' => $this->t("View"),
'route' => 'node/' . $item->id(),
'options' => [],
'icon' => 'eye-open',
'priority' => -100,
]);
}
if (node_access('update', $item)) {
$ret[] = Action::create([
'title' => $this->t("Edit"),
'route' => 'node/' . $item->id() . '/edit',
'options' => [],
'redirect' => true,
'icon' => 'pencil',
]);
}
if (node_access('delete', $item)) {
$ret[] = Action::create([
'title' => $this->t("Delete"),
'route' => 'node/' . $item->id() . '/delete',
'options' => [],
'icon' => 'trash',
'redirect' => true,
'primary' => false,
'group' => 'danger'
]);
}
return $ret;
} | {@inheritdoc} | https://github.com/makinacorpus/drupal-calista/blob/cceb6b975fc3e80f0f83c803fc6f6a9ac5852b53/src/Action/CoreNodeActionProvider.php#L21-L59 |
deweller/php-cliopts | src/CLIOpts/Help/HelpGenerator.php | HelpGenerator.build | public function build() {
$options_data = $this->buildOptionsData();
$out_text =
$this->buildUsageLine($this->arguments_spec->getUsage(), $options_data);
$options_text = '';
if ($options_data['lines']) {
foreach($options_data['lines'] as $option_line_data) {
$options_text .= $this->buildOptionLine($option_line_data, $options_data)."\n";
}
$out_text .=
"\n".
ConsoleFormat::applyformatToText('bold','cyan','Options:')."\n".
$options_text;
}
return $out_text;
} | php | public function build() {
$options_data = $this->buildOptionsData();
$out_text =
$this->buildUsageLine($this->arguments_spec->getUsage(), $options_data);
$options_text = '';
if ($options_data['lines']) {
foreach($options_data['lines'] as $option_line_data) {
$options_text .= $this->buildOptionLine($option_line_data, $options_data)."\n";
}
$out_text .=
"\n".
ConsoleFormat::applyformatToText('bold','cyan','Options:')."\n".
$options_text;
}
return $out_text;
} | Builds nicely formatted help text
@return string formatted help text | https://github.com/deweller/php-cliopts/blob/1923f3a7ad24062c6279c725579ff3af15141dec/src/CLIOpts/Help/HelpGenerator.php#L62-L81 |
deweller/php-cliopts | src/CLIOpts/Help/HelpGenerator.php | HelpGenerator.buildUsageLine | protected function buildUsageLine($usage_data, $options_data) {
if ($usage_data['use_argv_self']) {
$self_name = $_SERVER['argv'][0];
} else {
$self_name = $usage_data['self'];
}
$has_options = (count($options_data['lines']) > 0 ? true : false);
$has_named_args = (count($usage_data['named_args_spec']) > 0 ? true : false);
$out =
ConsoleFormat::applyformatToText('bold','cyan',"Usage:")."\n".
" {$self_name}".
($has_options ? ' [options]' : '').
($has_named_args ? ' '.$this->generateValueNamesHelp($usage_data['named_args_spec']) : '').
"\n";
return $out;
} | php | protected function buildUsageLine($usage_data, $options_data) {
if ($usage_data['use_argv_self']) {
$self_name = $_SERVER['argv'][0];
} else {
$self_name = $usage_data['self'];
}
$has_options = (count($options_data['lines']) > 0 ? true : false);
$has_named_args = (count($usage_data['named_args_spec']) > 0 ? true : false);
$out =
ConsoleFormat::applyformatToText('bold','cyan',"Usage:")."\n".
" {$self_name}".
($has_options ? ' [options]' : '').
($has_named_args ? ' '.$this->generateValueNamesHelp($usage_data['named_args_spec']) : '').
"\n";
return $out;
} | builds the usage line
@param array $usage_data Usage line specification data
@param array $options_data Options specification data
@return string formatted usage line text | https://github.com/deweller/php-cliopts/blob/1923f3a7ad24062c6279c725579ff3af15141dec/src/CLIOpts/Help/HelpGenerator.php#L97-L115 |
deweller/php-cliopts | src/CLIOpts/Help/HelpGenerator.php | HelpGenerator.buildOptionLine | protected function buildOptionLine($option_line_data, $options_data) {
$padding = $options_data['padding'];
$required = $option_line_data['spec']['required'];
$out = str_pad($option_line_data['switch_text'], $padding);
$out .= (strlen($option_line_data['spec']['help']) ? ' '.$option_line_data['spec']['help'] : '');
$out .= ($required ? ' (required)' : '');
// surround in bold if required
if ($required) {
$out = ConsoleFormat::applyformatToText('bold','yellow',$out);
}
return ' '.$out;
} | php | protected function buildOptionLine($option_line_data, $options_data) {
$padding = $options_data['padding'];
$required = $option_line_data['spec']['required'];
$out = str_pad($option_line_data['switch_text'], $padding);
$out .= (strlen($option_line_data['spec']['help']) ? ' '.$option_line_data['spec']['help'] : '');
$out .= ($required ? ' (required)' : '');
// surround in bold if required
if ($required) {
$out = ConsoleFormat::applyformatToText('bold','yellow',$out);
}
return ' '.$out;
} | builds an option line
@param array $option_line_data Option line specification data
@param array $options_data All options specification data
@return string formatted option line text | https://github.com/deweller/php-cliopts/blob/1923f3a7ad24062c6279c725579ff3af15141dec/src/CLIOpts/Help/HelpGenerator.php#L125-L140 |
deweller/php-cliopts | src/CLIOpts/Help/HelpGenerator.php | HelpGenerator.generateValueNamesHelp | protected function generateValueNamesHelp($named_args_spec) {
$first = true;
$out = '';
foreach($named_args_spec as $named_arg_spec) {
$out .= ($first ? '' : ' ');
if ($named_arg_spec['required']) {
$out .= ConsoleFormat::applyformatToText('bold','yellow','<'.$named_arg_spec['name'].'>');
} else {
$out .= '[<'.$named_arg_spec['name'].'>]';
}
$first = false;
}
return $out;
} | php | protected function generateValueNamesHelp($named_args_spec) {
$first = true;
$out = '';
foreach($named_args_spec as $named_arg_spec) {
$out .= ($first ? '' : ' ');
if ($named_arg_spec['required']) {
$out .= ConsoleFormat::applyformatToText('bold','yellow','<'.$named_arg_spec['name'].'>');
} else {
$out .= '[<'.$named_arg_spec['name'].'>]';
}
$first = false;
}
return $out;
} | gerenates the value names in the usage line
@param array $named_args_spec value names specifications
@return mixed Value. | https://github.com/deweller/php-cliopts/blob/1923f3a7ad24062c6279c725579ff3af15141dec/src/CLIOpts/Help/HelpGenerator.php#L150-L167 |
deweller/php-cliopts | src/CLIOpts/Help/HelpGenerator.php | HelpGenerator.buildOptionsData | protected function buildOptionsData() {
$options_data = array(
'lines' => array(),
'padding' => 0,
);
// build the lines
foreach($this->arguments_spec as $option_line_spec) {
$options_data['lines'][] = $this->buildOptionLineData($option_line_spec);
}
// calculate padding
$options_data['padding'] = $this->buildSwitchTextPaddingLength($options_data);
return $options_data;
} | php | protected function buildOptionsData() {
$options_data = array(
'lines' => array(),
'padding' => 0,
);
// build the lines
foreach($this->arguments_spec as $option_line_spec) {
$options_data['lines'][] = $this->buildOptionLineData($option_line_spec);
}
// calculate padding
$options_data['padding'] = $this->buildSwitchTextPaddingLength($options_data);
return $options_data;
} | builds options data from the arguments spec
@return array Options data | https://github.com/deweller/php-cliopts/blob/1923f3a7ad24062c6279c725579ff3af15141dec/src/CLIOpts/Help/HelpGenerator.php#L174-L189 |
deweller/php-cliopts | src/CLIOpts/Help/HelpGenerator.php | HelpGenerator.buildOptionLineData | protected function buildOptionLineData($option_line_spec) {
$data = array();
$switch_text = '';
if (strlen($option_line_spec['short'])) {
$switch_text .= "-".$option_line_spec['short'];
}
if (strlen($option_line_spec['long'])) {
$switch_text .= ($switch_text ? ", " : "")."--".$option_line_spec['long'];
}
$data = array(
'switch_text' => $switch_text.(strlen($option_line_spec['value_name']) ? ' <'.$option_line_spec['value_name'].'>' : ''),
'spec' => $option_line_spec,
);
return $data;
} | php | protected function buildOptionLineData($option_line_spec) {
$data = array();
$switch_text = '';
if (strlen($option_line_spec['short'])) {
$switch_text .= "-".$option_line_spec['short'];
}
if (strlen($option_line_spec['long'])) {
$switch_text .= ($switch_text ? ", " : "")."--".$option_line_spec['long'];
}
$data = array(
'switch_text' => $switch_text.(strlen($option_line_spec['value_name']) ? ' <'.$option_line_spec['value_name'].'>' : ''),
'spec' => $option_line_spec,
);
return $data;
} | builds a line of options data from a line of the argument spec
@param array $option_line_spec Data of argument specification representing an options line
@return mixed Value. | https://github.com/deweller/php-cliopts/blob/1923f3a7ad24062c6279c725579ff3af15141dec/src/CLIOpts/Help/HelpGenerator.php#L198-L215 |
deweller/php-cliopts | src/CLIOpts/Help/HelpGenerator.php | HelpGenerator.buildSwitchTextPaddingLength | protected function buildSwitchTextPaddingLength($options_data) {
$padding_len = 0;
foreach($options_data['lines'] as $option_line_data) {
$padding_len = max($padding_len, strlen($option_line_data['switch_text']));
}
return $padding_len;
} | php | protected function buildSwitchTextPaddingLength($options_data) {
$padding_len = 0;
foreach($options_data['lines'] as $option_line_data) {
$padding_len = max($padding_len, strlen($option_line_data['switch_text']));
}
return $padding_len;
} | calculates the maximum padding for all options
@param mixed $options_data Description.
@return int padding length | https://github.com/deweller/php-cliopts/blob/1923f3a7ad24062c6279c725579ff3af15141dec/src/CLIOpts/Help/HelpGenerator.php#L225-L231 |
harp-orm/harp | src/Model/Models.php | Models.addObjects | public function addObjects(SplObjectStorage $models)
{
foreach ($models as $model) {
$this->add($model);
}
return $this;
} | php | public function addObjects(SplObjectStorage $models)
{
foreach ($models as $model) {
$this->add($model);
}
return $this;
} | Link all models from the SplObjectStorage
@param SplObjectStorage $models
@return Models $this | https://github.com/harp-orm/harp/blob/e0751696521164c86ccd0a76d708df490efd8306/src/Model/Models.php#L50-L57 |
harp-orm/harp | src/Model/Models.php | Models.addAll | public function addAll(Models $other)
{
if ($other->count() > 0) {
$this->models->addAll($other->models);
}
return $this;
} | php | public function addAll(Models $other)
{
if ($other->count() > 0) {
$this->models->addAll($other->models);
}
return $this;
} | Add all models from a different Models collection
@param Models $other | https://github.com/harp-orm/harp/blob/e0751696521164c86ccd0a76d708df490efd8306/src/Model/Models.php#L64-L71 |
harp-orm/harp | src/Model/Models.php | Models.filter | public function filter(Closure $filter)
{
$filtered = clone $this;
$filtered->models = Objects::filter($filtered->models, $filter);
return $filtered;
} | php | public function filter(Closure $filter)
{
$filtered = clone $this;
$filtered->models = Objects::filter($filtered->models, $filter);
return $filtered;
} | Return a new Models object with only the models that pass the filter callback
(Filter callback returned true).
@param Closure $filter must return true for each item
@return Models Filtered models | https://github.com/harp-orm/harp/blob/e0751696521164c86ccd0a76d708df490efd8306/src/Model/Models.php#L221-L228 |
harp-orm/harp | src/Model/Models.php | Models.sort | public function sort(Closure $closure)
{
$sorted = clone $this;
$sorted->models = Objects::sort($sorted->models, $closure);
return $sorted;
} | php | public function sort(Closure $closure)
{
$sorted = clone $this;
$sorted->models = Objects::sort($sorted->models, $closure);
return $sorted;
} | Sort the models collection using a comparation closure
@param Closure $closure
@return array | https://github.com/harp-orm/harp/blob/e0751696521164c86ccd0a76d708df490efd8306/src/Model/Models.php#L236-L243 |
harp-orm/harp | src/Model/Models.php | Models.byRepo | public function byRepo(Closure $yield)
{
$repos = Objects::groupBy($this->models, function (AbstractModel $model) {
return $model->getRepo()->getRootRepo();
});
foreach ($repos as $repo) {
$models = new Models();
$models->addObjects($repos->getInfo());
$yield($repo, $models);
}
} | php | public function byRepo(Closure $yield)
{
$repos = Objects::groupBy($this->models, function (AbstractModel $model) {
return $model->getRepo()->getRootRepo();
});
foreach ($repos as $repo) {
$models = new Models();
$models->addObjects($repos->getInfo());
$yield($repo, $models);
}
} | Group models by repo, call yield for each repo
@param Closure $yield Call for each repo ($repo, $models) | https://github.com/harp-orm/harp/blob/e0751696521164c86ccd0a76d708df490efd8306/src/Model/Models.php#L272-L284 |
harp-orm/harp | src/Model/Models.php | Models.pluckProperty | public function pluckProperty($property)
{
$values = [];
foreach ($this->models as $model) {
$values []= $model->$property;
}
return $values;
} | php | public function pluckProperty($property)
{
$values = [];
foreach ($this->models as $model) {
$values []= $model->$property;
}
return $values;
} | Return the value of a property for each model
@param string $property
@return array | https://github.com/harp-orm/harp/blob/e0751696521164c86ccd0a76d708df490efd8306/src/Model/Models.php#L292-L301 |
harp-orm/harp | src/Model/Models.php | Models.isEmptyProperty | public function isEmptyProperty($property)
{
foreach ($this->models as $model) {
if ($model->$property) {
return false;
}
}
return true;
} | php | public function isEmptyProperty($property)
{
foreach ($this->models as $model) {
if ($model->$property) {
return false;
}
}
return true;
} | Return false if there is at least one non-empty property of a model.
@param string $property
@return boolean | https://github.com/harp-orm/harp/blob/e0751696521164c86ccd0a76d708df490efd8306/src/Model/Models.php#L309-L318 |
phPoirot/AuthSystem | Authenticate/RepoIdentityCredential/aIdentityCredentialAdapter.php | aIdentityCredentialAdapter.findIdentityMatch | final function findIdentityMatch()
{
if (!$this->isFulfilled())
return false;
/*throw new \Exception(sprintf(
'Credential Adapter Options Not Fulfilled By Given Options: (%s).'
, serialize(\Poirot\Std\cast($this)->toArray())
));*/
$credential = \Poirot\Std\cast($this)->toArray();
return $this->doFindIdentityMatch($credential);
} | php | final function findIdentityMatch()
{
if (!$this->isFulfilled())
return false;
/*throw new \Exception(sprintf(
'Credential Adapter Options Not Fulfilled By Given Options: (%s).'
, serialize(\Poirot\Std\cast($this)->toArray())
));*/
$credential = \Poirot\Std\cast($this)->toArray();
return $this->doFindIdentityMatch($credential);
} | Get Identity Match By Credential as Options
@return iIdentity|false
@throws \Exception credential not fulfilled | https://github.com/phPoirot/AuthSystem/blob/bb8d02f72a7c2686d7d453021143361fa704a5a6/Authenticate/RepoIdentityCredential/aIdentityCredentialAdapter.php#L53-L64 |
logikostech/http | src/Http/Request/ContentParser/Adapter/Formdata.php | Formdata.parse | public function parse($content) {
$this->resetFd();
foreach ($this->formdataParts($content) as $part) {
if (!$this->isLastPart($part)) {
$this->processFormdataPart($part);
}
}
$this->compileData();
return $this->fd;
} | php | public function parse($content) {
$this->resetFd();
foreach ($this->formdataParts($content) as $part) {
if (!$this->isLastPart($part)) {
$this->processFormdataPart($part);
}
}
$this->compileData();
return $this->fd;
} | Parse multipart/form-data
@return stdClass {post:[], files:[]} | https://github.com/logikostech/http/blob/7eea35e43b2c74b4ccb8747be4fe959e2c5da4ab/src/Http/Request/ContentParser/Adapter/Formdata.php#L18-L27 |
logikostech/http | src/Http/Request/ContentParser/Adapter/Formdata.php | Formdata.appendFile | protected function appendFile($sect) {
$data = $this->filedata($sect);
$multi = substr($sect->disposition->name,-2)=='[]';
if ($multi) {
$key = substr($sect->disposition->name,0,-2);
foreach($data as $k=>$v) {
$value = isset($this->fd->files[$key][$k])
? (array) $this->fd->files[$key][$k]
: [];
array_push($value,$v);
$this->fd->files[$key][$k] = $value;
}
}
else {
$key = $sect->disposition->name;
$this->fd->files[$key] = $data;
}
} | php | protected function appendFile($sect) {
$data = $this->filedata($sect);
$multi = substr($sect->disposition->name,-2)=='[]';
if ($multi) {
$key = substr($sect->disposition->name,0,-2);
foreach($data as $k=>$v) {
$value = isset($this->fd->files[$key][$k])
? (array) $this->fd->files[$key][$k]
: [];
array_push($value,$v);
$this->fd->files[$key][$k] = $value;
}
}
else {
$key = $sect->disposition->name;
$this->fd->files[$key] = $data;
}
} | known issue: fails on deeper arrays such as if name=foo[bar][] | https://github.com/logikostech/http/blob/7eea35e43b2c74b4ccb8747be4fe959e2c5da4ab/src/Http/Request/ContentParser/Adapter/Formdata.php#L108-L126 |
webignition/readable-duration | src/Factory.php | Factory.isApproachingThreshold | private function isApproachingThreshold($value, string $unit): bool
{
return round($value) == round($this->unitThresholds[$unit]);
} | php | private function isApproachingThreshold($value, string $unit): bool
{
return round($value) == round($this->unitThresholds[$unit]);
} | @param float|int $value
@param string $unit
@return bool | https://github.com/webignition/readable-duration/blob/39cb0b8abaa0d68b84a2b77ab75b2b58a07ed922/src/Factory.php#L147-L150 |
phavour/phavour | Phavour/Application/Environment.php | Environment.configureErrorMode | private function configureErrorMode()
{
if (false != ($errorMode = getenv('APPLICATION_ENV'))) {
// @codeCoverageIgnoreStart
$this->errorMode = strtolower($errorMode);
return;
// @codeCoverageIgnoreEnd
}
if (defined('APPLICATION_ENV')) {
// @codeCoverageIgnoreStart
$this->errorMode = strtolower(APPLICATION_ENV);
return;
// @codeCoverageIgnoreEnd
}
return;
} | php | private function configureErrorMode()
{
if (false != ($errorMode = getenv('APPLICATION_ENV'))) {
// @codeCoverageIgnoreStart
$this->errorMode = strtolower($errorMode);
return;
// @codeCoverageIgnoreEnd
}
if (defined('APPLICATION_ENV')) {
// @codeCoverageIgnoreStart
$this->errorMode = strtolower(APPLICATION_ENV);
return;
// @codeCoverageIgnoreEnd
}
return;
} | Establishes the Application Environment, by checking (in this order)
1) getenv('APPLICATION_ENV')
2) defined('APPLICATION_ENV')
@return void | https://github.com/phavour/phavour/blob/2246f78203312eb2e23fdb0f776f790e81b4d20f/Phavour/Application/Environment.php#L95-L112 |
bennybi/yii2-cza-base | components/utils/Naming.php | Naming.toSplit | public function toSplit($name, $splitor = '-', $to = self::LOWER) {
switch ($to) {
case self::UPPER:
return strtoupper(preg_replace("/(.)([A-Z])/", "$1{$splitor}$2", $name));
default:
return strtolower(preg_replace("/(.)([A-Z])/", "$1{$splitor}$2", $name));
}
} | php | public function toSplit($name, $splitor = '-', $to = self::LOWER) {
switch ($to) {
case self::UPPER:
return strtoupper(preg_replace("/(.)([A-Z])/", "$1{$splitor}$2", $name));
default:
return strtolower(preg_replace("/(.)([A-Z])/", "$1{$splitor}$2", $name));
}
} | usage example. CmsPageSort => cms-page-sort
@param type $name
@param type $splitor
@param type $to
@return type | https://github.com/bennybi/yii2-cza-base/blob/8257db8034bd948712fa469062921f210f0ba8da/components/utils/Naming.php#L30-L37 |
pmdevelopment/tool-bundle | Components/Helper/ObjectHelper.php | ObjectHelper.getConstantValuesByPrefix | public static function getConstantValuesByPrefix($className, $prefix)
{
$prefixLength = strlen($prefix);
$result = [];
$reflection = new \ReflectionClass($className);
foreach ($reflection->getConstants() as $constKey => $constValue) {
if ($prefix === substr($constKey, 0, $prefixLength)) {
$result[] = $constValue;
}
}
return $result;
} | php | public static function getConstantValuesByPrefix($className, $prefix)
{
$prefixLength = strlen($prefix);
$result = [];
$reflection = new \ReflectionClass($className);
foreach ($reflection->getConstants() as $constKey => $constValue) {
if ($prefix === substr($constKey, 0, $prefixLength)) {
$result[] = $constValue;
}
}
return $result;
} | Get Contant Values By Prefix
@param string $className
@param string $prefix
@return array | https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Components/Helper/ObjectHelper.php#L27-L40 |
zbox/UnifiedPush | src/Zbox/UnifiedPush/NotificationService/MPNS/ServiceClient.php | ServiceClient.createClient | protected function createClient()
{
$client = new MultiCurl();
$credentials = $this->getCredentials();
$isAuthenticated = $credentials instanceof SSLCertificate;
$client->setVerifyPeer($isAuthenticated);
if ($isAuthenticated) {
$client->setOption(CURLOPT_SSLCERT, $credentials->getCertificatePassPhrase());
$client->setOption(CURLOPT_SSLCERTPASSWD, $credentials->getCertificatePassPhrase());
}
$this->serviceClient = new Browser($client);
return $this;
} | php | protected function createClient()
{
$client = new MultiCurl();
$credentials = $this->getCredentials();
$isAuthenticated = $credentials instanceof SSLCertificate;
$client->setVerifyPeer($isAuthenticated);
if ($isAuthenticated) {
$client->setOption(CURLOPT_SSLCERT, $credentials->getCertificatePassPhrase());
$client->setOption(CURLOPT_SSLCERTPASSWD, $credentials->getCertificatePassPhrase());
}
$this->serviceClient = new Browser($client);
return $this;
} | Initializing HTTP client
@return $this | https://github.com/zbox/UnifiedPush/blob/47da2d0577b18ac709cd947c68541014001e1866/src/Zbox/UnifiedPush/NotificationService/MPNS/ServiceClient.php#L30-L47 |
rackberg/para | src/Loader/ServicesLoader.php | ServicesLoader.loadServices | public function loadServices(array $paths): void
{
// Make sure that not existing paths are removed.
foreach ($paths as $key => $path) {
if (!is_dir($path)) {
if (empty(glob($path, (defined('GLOB_BRACE') ? GLOB_BRACE : 0) | GLOB_ONLYDIR))) {
unset($paths[$key]);
}
}
}
try {
$this->finder
->name('*.yml')
->in($paths);
foreach ($this->finder as $fileInfo) {
$loader = $this->factory->getFileLoader();
// Load the service configurations.
$loader->load($fileInfo->getPathname());
}
} catch (\Exception $e) {
}
} | php | public function loadServices(array $paths): void
{
// Make sure that not existing paths are removed.
foreach ($paths as $key => $path) {
if (!is_dir($path)) {
if (empty(glob($path, (defined('GLOB_BRACE') ? GLOB_BRACE : 0) | GLOB_ONLYDIR))) {
unset($paths[$key]);
}
}
}
try {
$this->finder
->name('*.yml')
->in($paths);
foreach ($this->finder as $fileInfo) {
$loader = $this->factory->getFileLoader();
// Load the service configurations.
$loader->load($fileInfo->getPathname());
}
} catch (\Exception $e) {
}
} | {@inheritdoc} | https://github.com/rackberg/para/blob/e0ef1356ed2979670eb7c670d88921406cade46e/src/Loader/ServicesLoader.php#L45-L69 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.