repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1
value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
czim/file-handling | src/Storage/File/ProcessableFile.php | ProcessableFile.setDerivedFileProperties | protected function setDerivedFileProperties()
{
if ( ! $this->file || ! file_exists($this->file->getRealPath())) {
throw new RuntimeException("Local file not found at {$this->file->getPath()}");
}
$this->size = $this->file->getSize();
if (null === $this->name) {
$this->name = $this->file->getBasename();
}
} | php | protected function setDerivedFileProperties()
{
if ( ! $this->file || ! file_exists($this->file->getRealPath())) {
throw new RuntimeException("Local file not found at {$this->file->getPath()}");
}
$this->size = $this->file->getSize();
if (null === $this->name) {
$this->name = $this->file->getBasename();
}
} | [
"protected",
"function",
"setDerivedFileProperties",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"file",
"||",
"!",
"file_exists",
"(",
"$",
"this",
"->",
"file",
"->",
"getRealPath",
"(",
")",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"("... | Sets properties based on the given data. | [
"Sets",
"properties",
"based",
"on",
"the",
"given",
"data",
"."
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Storage/File/ProcessableFile.php#L46-L57 | train |
czim/file-handling | src/Support/Image/OrientationFixer.php | OrientationFixer.fixFile | public function fixFile(SplFileInfo $file)
{
$filePath = $file->getRealPath();
$image = $this->imagine->open($file->getRealPath());
$image = $this->fixImage($filePath, $image);
$image->save();
return true;
} | php | public function fixFile(SplFileInfo $file)
{
$filePath = $file->getRealPath();
$image = $this->imagine->open($file->getRealPath());
$image = $this->fixImage($filePath, $image);
$image->save();
return true;
} | [
"public",
"function",
"fixFile",
"(",
"SplFileInfo",
"$",
"file",
")",
"{",
"$",
"filePath",
"=",
"$",
"file",
"->",
"getRealPath",
"(",
")",
";",
"$",
"image",
"=",
"$",
"this",
"->",
"imagine",
"->",
"open",
"(",
"$",
"file",
"->",
"getRealPath",
"... | Fixes the orientation in a local file.
This overwrites the current file.
@param SplFileInfo $file
@return bool
@throws ErrorException | [
"Fixes",
"the",
"orientation",
"in",
"a",
"local",
"file",
"."
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Support/Image/OrientationFixer.php#L84-L94 | train |
czim/file-handling | src/Support/Image/OrientationFixer.php | OrientationFixer.fixImage | public function fixImage($path, ImageInterface $image)
{
// @codeCoverageIgnoreStart
if ( ! function_exists('exif_read_data')) {
return $image;
}
// @codeCoverageIgnoreEnd
try {
$exif = exif_read_data($path);
// @codeCoverageIgnoreStart
} catch (ErrorException $e) {
if ($this->quiet) {
return $image;
}
throw $e;
// @codeCoverageIgnoreEnd
}
if ( ! isset($exif['Orientation']) || $exif['Orientation'] == static::ORIENTATION_TOPLEFT) {
return $image;
}
switch ($exif['Orientation']) {
case static::ORIENTATION_TOPRIGHT:
$image->flipHorizontally();
break;
case static::ORIENTATION_BOTTOMRIGHT:
$image->rotate(180);
break;
case static::ORIENTATION_BOTTOMLEFT:
$image->flipVertically();
break;
case static::ORIENTATION_LEFTTOP:
$image->flipVertically()->rotate(90);
break;
case static::ORIENTATION_RIGHTTOP:
$image->rotate(90);
break;
case static::ORIENTATION_RIGHTBOTTOM:
$image->flipHorizontally()->rotate(90);
break;
case static::ORIENTATION_LEFTBOTTOM:
$image->rotate(-90);
break;
}
return $image->strip();
} | php | public function fixImage($path, ImageInterface $image)
{
// @codeCoverageIgnoreStart
if ( ! function_exists('exif_read_data')) {
return $image;
}
// @codeCoverageIgnoreEnd
try {
$exif = exif_read_data($path);
// @codeCoverageIgnoreStart
} catch (ErrorException $e) {
if ($this->quiet) {
return $image;
}
throw $e;
// @codeCoverageIgnoreEnd
}
if ( ! isset($exif['Orientation']) || $exif['Orientation'] == static::ORIENTATION_TOPLEFT) {
return $image;
}
switch ($exif['Orientation']) {
case static::ORIENTATION_TOPRIGHT:
$image->flipHorizontally();
break;
case static::ORIENTATION_BOTTOMRIGHT:
$image->rotate(180);
break;
case static::ORIENTATION_BOTTOMLEFT:
$image->flipVertically();
break;
case static::ORIENTATION_LEFTTOP:
$image->flipVertically()->rotate(90);
break;
case static::ORIENTATION_RIGHTTOP:
$image->rotate(90);
break;
case static::ORIENTATION_RIGHTBOTTOM:
$image->flipHorizontally()->rotate(90);
break;
case static::ORIENTATION_LEFTBOTTOM:
$image->rotate(-90);
break;
}
return $image->strip();
} | [
"public",
"function",
"fixImage",
"(",
"$",
"path",
",",
"ImageInterface",
"$",
"image",
")",
"{",
"// @codeCoverageIgnoreStart",
"if",
"(",
"!",
"function_exists",
"(",
"'exif_read_data'",
")",
")",
"{",
"return",
"$",
"image",
";",
"}",
"// @codeCoverageIgnore... | Re-orient an image using its embedded Exif profile orientation.
1. Attempt to read the embedded exif data inside the image to determine it's orientation.
if there is no exif data (i.e an exeption is thrown when trying to read it) then we'll
just return the image as is.
2. If there is exif data, we'll rotate and flip the image accordingly to re-orient it.
3. Finally, we'll strip the exif data from the image so that there can be no
attempt to 'correct' it again.
@param string $path
@param ImageInterface $image
@return ImageInterface $image
@throws ErrorException | [
"Re",
"-",
"orient",
"an",
"image",
"using",
"its",
"embedded",
"Exif",
"profile",
"orientation",
"."
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Support/Image/OrientationFixer.php#L111-L166 | train |
czim/file-handling | src/Variant/VariantProcessor.php | VariantProcessor.setConfig | public function setConfig(array $config)
{
$this->config = $config;
if (array_key_exists(static::CONFIG_VARIANT_FACTORY, $config)) {
$this->strategyFactory->setConfig(
$config[ static::CONFIG_VARIANT_FACTORY ]
);
}
return $this;
} | php | public function setConfig(array $config)
{
$this->config = $config;
if (array_key_exists(static::CONFIG_VARIANT_FACTORY, $config)) {
$this->strategyFactory->setConfig(
$config[ static::CONFIG_VARIANT_FACTORY ]
);
}
return $this;
} | [
"public",
"function",
"setConfig",
"(",
"array",
"$",
"config",
")",
"{",
"$",
"this",
"->",
"config",
"=",
"$",
"config",
";",
"if",
"(",
"array_key_exists",
"(",
"static",
"::",
"CONFIG_VARIANT_FACTORY",
",",
"$",
"config",
")",
")",
"{",
"$",
"this",
... | Sets configuration for the processor.
@param array $config
@return $this | [
"Sets",
"configuration",
"for",
"the",
"processor",
"."
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Variant/VariantProcessor.php#L60-L71 | train |
czim/file-handling | src/Variant/VariantProcessor.php | VariantProcessor.process | public function process(StorableFileInterface $source, $variant, array $strategies)
{
$file = $this->makeTemporaryCopy($source);
foreach ($strategies as $strategy => $options) {
$instance = $this->strategyFactory->make($strategy)->setOptions($options);
// The file returned by the strategy step may have altered the path,
// name, extension and/or mime type of the file being processed.
// This information is present in the returned ProcessableFile instance.
try {
$newFile = $instance->apply($file);
} catch (VariantStrategyShouldNotBeAppliedException $e) {
if ($this->shouldThrowExceptionForUnappliedStrategy()) {
throw new VariantStrategyNotAppliedException(
"Strategy '{$strategy}' not applied to '{$source->path()}'"
);
}
continue;
}
if (false === $newFile) {
throw new VariantStrategyNotAppliedException(
"Failed to apply '{$strategy}' to '{$source->path()}'"
);
}
$file = $newFile;
}
return $file;
} | php | public function process(StorableFileInterface $source, $variant, array $strategies)
{
$file = $this->makeTemporaryCopy($source);
foreach ($strategies as $strategy => $options) {
$instance = $this->strategyFactory->make($strategy)->setOptions($options);
// The file returned by the strategy step may have altered the path,
// name, extension and/or mime type of the file being processed.
// This information is present in the returned ProcessableFile instance.
try {
$newFile = $instance->apply($file);
} catch (VariantStrategyShouldNotBeAppliedException $e) {
if ($this->shouldThrowExceptionForUnappliedStrategy()) {
throw new VariantStrategyNotAppliedException(
"Strategy '{$strategy}' not applied to '{$source->path()}'"
);
}
continue;
}
if (false === $newFile) {
throw new VariantStrategyNotAppliedException(
"Failed to apply '{$strategy}' to '{$source->path()}'"
);
}
$file = $newFile;
}
return $file;
} | [
"public",
"function",
"process",
"(",
"StorableFileInterface",
"$",
"source",
",",
"$",
"variant",
",",
"array",
"$",
"strategies",
")",
"{",
"$",
"file",
"=",
"$",
"this",
"->",
"makeTemporaryCopy",
"(",
"$",
"source",
")",
";",
"foreach",
"(",
"$",
"st... | Returns a processed variant for a given source file.
@param StorableFileInterface $source
@param string $variant the name/prefix name of the variant
@param array[] $strategies associative, ordered set of strategies to apply
@return StorableFileInterface
@throws VariantStrategyNotAppliedException
@throws CouldNotProcessDataException | [
"Returns",
"a",
"processed",
"variant",
"for",
"a",
"given",
"source",
"file",
"."
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Variant/VariantProcessor.php#L83-L119 | train |
czim/file-handling | src/Variant/VariantProcessor.php | VariantProcessor.shouldThrowExceptionForUnappliedStrategy | protected function shouldThrowExceptionForUnappliedStrategy()
{
if ( ! array_key_exists(static::CONFIG_FORCE_APPLY, $this->config)) {
return false;
}
return (bool) $this->config[ static::CONFIG_FORCE_APPLY ];
} | php | protected function shouldThrowExceptionForUnappliedStrategy()
{
if ( ! array_key_exists(static::CONFIG_FORCE_APPLY, $this->config)) {
return false;
}
return (bool) $this->config[ static::CONFIG_FORCE_APPLY ];
} | [
"protected",
"function",
"shouldThrowExceptionForUnappliedStrategy",
"(",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"static",
"::",
"CONFIG_FORCE_APPLY",
",",
"$",
"this",
"->",
"config",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"(",
"boo... | Returns whether exceptions should be thrown if a strategy was not applied.
@return bool | [
"Returns",
"whether",
"exceptions",
"should",
"be",
"thrown",
"if",
"a",
"strategy",
"was",
"not",
"applied",
"."
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Variant/VariantProcessor.php#L126-L133 | train |
czim/file-handling | src/Variant/VariantProcessor.php | VariantProcessor.makeTemporaryCopy | protected function makeTemporaryCopy(StorableFileInterface $source)
{
$path = $this->makeLocalTemporaryPath($source->extension());
try {
$success = $source->copy($path);
// @codeCoverageIgnoreStart
} catch (Exception $e) {
throw new CouldNotProcessDataException("Failed to make variant copy to '{$path}'", $e->getCode(), $e);
// @codeCoverageIgnoreEnd
}
// @codeCoverageIgnoreStart
if ( ! $success) {
throw new CouldNotProcessDataException("Failed to make variant copy to '{$path}'");
}
// @codeCoverageIgnoreEnd
$file = new ProcessableFile;
$file->setName($source->name());
$file->setMimeType($source->mimeType());
$file->setData($path);
return $file;
} | php | protected function makeTemporaryCopy(StorableFileInterface $source)
{
$path = $this->makeLocalTemporaryPath($source->extension());
try {
$success = $source->copy($path);
// @codeCoverageIgnoreStart
} catch (Exception $e) {
throw new CouldNotProcessDataException("Failed to make variant copy to '{$path}'", $e->getCode(), $e);
// @codeCoverageIgnoreEnd
}
// @codeCoverageIgnoreStart
if ( ! $success) {
throw new CouldNotProcessDataException("Failed to make variant copy to '{$path}'");
}
// @codeCoverageIgnoreEnd
$file = new ProcessableFile;
$file->setName($source->name());
$file->setMimeType($source->mimeType());
$file->setData($path);
return $file;
} | [
"protected",
"function",
"makeTemporaryCopy",
"(",
"StorableFileInterface",
"$",
"source",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"makeLocalTemporaryPath",
"(",
"$",
"source",
"->",
"extension",
"(",
")",
")",
";",
"try",
"{",
"$",
"success",
"=",
... | Makes a copy of the original file info that will be manipulated into the variant.
@param StorableFileInterface $source
@return ProcessableFileInterface
@throws CouldNotProcessDataException | [
"Makes",
"a",
"copy",
"of",
"the",
"original",
"file",
"info",
"that",
"will",
"be",
"manipulated",
"into",
"the",
"variant",
"."
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Variant/VariantProcessor.php#L142-L168 | train |
czim/file-handling | src/Variant/Strategies/AbstractVariantStrategy.php | AbstractVariantStrategy.apply | public function apply(ProcessableFileInterface $file)
{
$this->file = $file;
if ( ! $this->shouldBeApplied()) {
throw new VariantStrategyShouldNotBeAppliedException;
}
$result = $this->perform();
return ($result || null === $result) ? $this->file : false;
} | php | public function apply(ProcessableFileInterface $file)
{
$this->file = $file;
if ( ! $this->shouldBeApplied()) {
throw new VariantStrategyShouldNotBeAppliedException;
}
$result = $this->perform();
return ($result || null === $result) ? $this->file : false;
} | [
"public",
"function",
"apply",
"(",
"ProcessableFileInterface",
"$",
"file",
")",
"{",
"$",
"this",
"->",
"file",
"=",
"$",
"file",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"shouldBeApplied",
"(",
")",
")",
"{",
"throw",
"new",
"VariantStrategyShouldNotBeAp... | Applies strategy to a file.
@param ProcessableFileInterface $file
@return ProcessableFileInterface|false
@throws VariantStrategyShouldNotBeAppliedException | [
"Applies",
"strategy",
"to",
"a",
"file",
"."
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Variant/Strategies/AbstractVariantStrategy.php#L32-L43 | train |
czim/file-handling | src/Handler/FileHandler.php | FileHandler.process | public function process(StorableFileInterface $source, TargetInterface $target, array $options = [])
{
$stored = [
static::ORIGINAL => $this->storage->store($source, $target->original()),
];
if (array_key_exists(static::CONFIG_VARIANTS, $options)) {
foreach ($options[ static::CONFIG_VARIANTS ] as $variant => $variantOptions) {
$stored[ $variant ] = $this->processVariant($source, $target, $variant, $variantOptions);
}
}
return $stored;
} | php | public function process(StorableFileInterface $source, TargetInterface $target, array $options = [])
{
$stored = [
static::ORIGINAL => $this->storage->store($source, $target->original()),
];
if (array_key_exists(static::CONFIG_VARIANTS, $options)) {
foreach ($options[ static::CONFIG_VARIANTS ] as $variant => $variantOptions) {
$stored[ $variant ] = $this->processVariant($source, $target, $variant, $variantOptions);
}
}
return $stored;
} | [
"public",
"function",
"process",
"(",
"StorableFileInterface",
"$",
"source",
",",
"TargetInterface",
"$",
"target",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"stored",
"=",
"[",
"static",
"::",
"ORIGINAL",
"=>",
"$",
"this",
"->",
"sto... | Processes and stores a storable file.
@param StorableFileInterface $source
@param TargetInterface $target
@param array $options
@return StoredFileInterface[] keyed by variant name (or 'original') | [
"Processes",
"and",
"stores",
"a",
"storable",
"file",
"."
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Handler/FileHandler.php#L61-L75 | train |
czim/file-handling | src/Handler/FileHandler.php | FileHandler.processVariant | public function processVariant(StorableFileInterface $source, TargetInterface $target, $variant, array $options = [])
{
$storableVariant = $this->processor->process($source, $variant, $options);
return $this->storage->store($storableVariant, $target->variant($variant));
} | php | public function processVariant(StorableFileInterface $source, TargetInterface $target, $variant, array $options = [])
{
$storableVariant = $this->processor->process($source, $variant, $options);
return $this->storage->store($storableVariant, $target->variant($variant));
} | [
"public",
"function",
"processVariant",
"(",
"StorableFileInterface",
"$",
"source",
",",
"TargetInterface",
"$",
"target",
",",
"$",
"variant",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"storableVariant",
"=",
"$",
"this",
"->",
"processor... | Processes and stores a single variant for a storable file.
@param StorableFileInterface $source
@param TargetInterface $target
@param string $variant
@param array $options
@return StoredFileInterface | [
"Processes",
"and",
"stores",
"a",
"single",
"variant",
"for",
"a",
"storable",
"file",
"."
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Handler/FileHandler.php#L86-L91 | train |
czim/file-handling | src/Handler/FileHandler.php | FileHandler.variantUrlsForTarget | public function variantUrlsForTarget(TargetInterface $target, array $variants = [])
{
$urls = [
static::ORIGINAL => $this->storage->url($target->original()),
];
if (in_array(static::ORIGINAL, $variants)) {
$variants = array_diff($variants, [ static::ORIGINAL ]);
}
foreach ($variants as $variant) {
$urls[ $variant ] = $this->storage->url($target->variant($variant));
}
return $urls;
} | php | public function variantUrlsForTarget(TargetInterface $target, array $variants = [])
{
$urls = [
static::ORIGINAL => $this->storage->url($target->original()),
];
if (in_array(static::ORIGINAL, $variants)) {
$variants = array_diff($variants, [ static::ORIGINAL ]);
}
foreach ($variants as $variant) {
$urls[ $variant ] = $this->storage->url($target->variant($variant));
}
return $urls;
} | [
"public",
"function",
"variantUrlsForTarget",
"(",
"TargetInterface",
"$",
"target",
",",
"array",
"$",
"variants",
"=",
"[",
"]",
")",
"{",
"$",
"urls",
"=",
"[",
"static",
"::",
"ORIGINAL",
"=>",
"$",
"this",
"->",
"storage",
"->",
"url",
"(",
"$",
"... | Returns the URLs keyed by the variant keys requested.
@param TargetInterface $target
@param string[] $variants keys for variants to include
@return string[] | [
"Returns",
"the",
"URLs",
"keyed",
"by",
"the",
"variant",
"keys",
"requested",
"."
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Handler/FileHandler.php#L100-L115 | train |
czim/file-handling | src/Handler/FileHandler.php | FileHandler.delete | public function delete(TargetInterface $target, array $variants = [])
{
$success = true;
if ( ! in_array(static::ORIGINAL, $variants)) {
$variants[] = static::ORIGINAL;
}
foreach ($variants as $variant) {
if ( ! $this->deleteVariant($target, $variant)) {
$success = false;
}
}
return $success;
} | php | public function delete(TargetInterface $target, array $variants = [])
{
$success = true;
if ( ! in_array(static::ORIGINAL, $variants)) {
$variants[] = static::ORIGINAL;
}
foreach ($variants as $variant) {
if ( ! $this->deleteVariant($target, $variant)) {
$success = false;
}
}
return $success;
} | [
"public",
"function",
"delete",
"(",
"TargetInterface",
"$",
"target",
",",
"array",
"$",
"variants",
"=",
"[",
"]",
")",
"{",
"$",
"success",
"=",
"true",
";",
"if",
"(",
"!",
"in_array",
"(",
"static",
"::",
"ORIGINAL",
",",
"$",
"variants",
")",
"... | Deletes a file and all indicated variants.
@param TargetInterface $target
@param string[] $variants variant keys
@return bool | [
"Deletes",
"a",
"file",
"and",
"all",
"indicated",
"variants",
"."
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Handler/FileHandler.php#L124-L139 | train |
czim/file-handling | src/Handler/FileHandler.php | FileHandler.deleteVariant | public function deleteVariant(TargetInterface $target, $variant)
{
if ($variant == static::ORIGINAL) {
$path = $target->original();
} else {
$path = $target->variant($variant);
}
// If the file does not exist, consider 'deletion' a success
if ( ! $this->storage->exists($path)) {
return true;
}
return $this->storage->delete($path);
} | php | public function deleteVariant(TargetInterface $target, $variant)
{
if ($variant == static::ORIGINAL) {
$path = $target->original();
} else {
$path = $target->variant($variant);
}
// If the file does not exist, consider 'deletion' a success
if ( ! $this->storage->exists($path)) {
return true;
}
return $this->storage->delete($path);
} | [
"public",
"function",
"deleteVariant",
"(",
"TargetInterface",
"$",
"target",
",",
"$",
"variant",
")",
"{",
"if",
"(",
"$",
"variant",
"==",
"static",
"::",
"ORIGINAL",
")",
"{",
"$",
"path",
"=",
"$",
"target",
"->",
"original",
"(",
")",
";",
"}",
... | Deletes a single variant.
@param TargetInterface $target may be a full file path, or a base path
@param string $variant 'original' refers to the original file
@return bool | [
"Deletes",
"a",
"single",
"variant",
"."
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Handler/FileHandler.php#L148-L162 | train |
czim/file-handling | src/Support/Image/Resizer.php | Resizer.resize | public function resize(SplFileInfo $file, array $options)
{
$filePath = $file->getRealPath();
list($width, $height, $option) = $this->parseOptionDimensions($options);
$method = 'resize' . ucfirst($option);
// Custom resize (that still expects imagine to be used)
if ($method == 'resizeCustom') {
$callable = $options['dimensions'];
$this
->resizeCustom($file, $callable)
->save($filePath, $this->getConvertOptions($options));
return true;
}
$image = $this->imagine->open($file->getRealPath());
$this->$method($image, $width, $height)
->save($filePath, $this->getConvertOptions($options));
return true;
} | php | public function resize(SplFileInfo $file, array $options)
{
$filePath = $file->getRealPath();
list($width, $height, $option) = $this->parseOptionDimensions($options);
$method = 'resize' . ucfirst($option);
// Custom resize (that still expects imagine to be used)
if ($method == 'resizeCustom') {
$callable = $options['dimensions'];
$this
->resizeCustom($file, $callable)
->save($filePath, $this->getConvertOptions($options));
return true;
}
$image = $this->imagine->open($file->getRealPath());
$this->$method($image, $width, $height)
->save($filePath, $this->getConvertOptions($options));
return true;
} | [
"public",
"function",
"resize",
"(",
"SplFileInfo",
"$",
"file",
",",
"array",
"$",
"options",
")",
"{",
"$",
"filePath",
"=",
"$",
"file",
"->",
"getRealPath",
"(",
")",
";",
"list",
"(",
"$",
"width",
",",
"$",
"height",
",",
"$",
"option",
")",
... | Resize an image using given options.
@param SplFileInfo $file
@param array $options
@return bool | [
"Resize",
"an",
"image",
"using",
"given",
"options",
"."
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Support/Image/Resizer.php#L41-L67 | train |
czim/file-handling | src/Support/Image/Resizer.php | Resizer.getConvertOptions | protected function getConvertOptions(array $options)
{
if ($this->arrHas($options, 'convertOptions')) {
return $this->arrGet($options, 'convertOptions', []);
}
return $this->arrGet($options, 'convert_options', []);
} | php | protected function getConvertOptions(array $options)
{
if ($this->arrHas($options, 'convertOptions')) {
return $this->arrGet($options, 'convertOptions', []);
}
return $this->arrGet($options, 'convert_options', []);
} | [
"protected",
"function",
"getConvertOptions",
"(",
"array",
"$",
"options",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"arrHas",
"(",
"$",
"options",
",",
"'convertOptions'",
")",
")",
"{",
"return",
"$",
"this",
"->",
"arrGet",
"(",
"$",
"options",
",",
... | Returns the convert options for image manipulation.
@param array $options
@return array | [
"Returns",
"the",
"convert",
"options",
"for",
"image",
"manipulation",
"."
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Support/Image/Resizer.php#L76-L83 | train |
czim/file-handling | src/Support/Image/Resizer.php | Resizer.parseOptionDimensions | protected function parseOptionDimensions(array $options)
{
$sourceDimensions = $this->arrGet($options, 'dimensions');
if (is_callable($sourceDimensions)) {
return [null, null, 'custom'];
}
if (strpos($sourceDimensions, 'x') === false) {
// Width given, height automagically selected to preserve aspect ratio (landscape).
$width = $sourceDimensions;
return [$width, null, 'landscape'];
}
$dimensions = explode('x', $sourceDimensions);
$width = $dimensions[0];
$height = $dimensions[1];
if (empty($width)) {
// Height given, width matched to preserve aspect ratio (portrait)
return [null, $height, 'portrait'];
}
$resizingOption = substr($height, -1, 1);
if ($resizingOption == '#') {
// Resize, then crop
$height = rtrim($height, '#');
return [$width, $height, 'crop'];
}
if ($resizingOption == '!') {
// Resize by exact width/height (ignore ratio)
$height = rtrim($height, '!');
return [$width, $height, 'exact'];
}
return [$width, $height, 'auto'];
} | php | protected function parseOptionDimensions(array $options)
{
$sourceDimensions = $this->arrGet($options, 'dimensions');
if (is_callable($sourceDimensions)) {
return [null, null, 'custom'];
}
if (strpos($sourceDimensions, 'x') === false) {
// Width given, height automagically selected to preserve aspect ratio (landscape).
$width = $sourceDimensions;
return [$width, null, 'landscape'];
}
$dimensions = explode('x', $sourceDimensions);
$width = $dimensions[0];
$height = $dimensions[1];
if (empty($width)) {
// Height given, width matched to preserve aspect ratio (portrait)
return [null, $height, 'portrait'];
}
$resizingOption = substr($height, -1, 1);
if ($resizingOption == '#') {
// Resize, then crop
$height = rtrim($height, '#');
return [$width, $height, 'crop'];
}
if ($resizingOption == '!') {
// Resize by exact width/height (ignore ratio)
$height = rtrim($height, '!');
return [$width, $height, 'exact'];
}
return [$width, $height, 'auto'];
} | [
"protected",
"function",
"parseOptionDimensions",
"(",
"array",
"$",
"options",
")",
"{",
"$",
"sourceDimensions",
"=",
"$",
"this",
"->",
"arrGet",
"(",
"$",
"options",
",",
"'dimensions'",
")",
";",
"if",
"(",
"is_callable",
"(",
"$",
"sourceDimensions",
"... | Parses the dimensions given in the options.
Parse the given style dimensions to extract out the file processing options,
perform any necessary image resizing for a given style.
@param array $options
@return array | [
"Parses",
"the",
"dimensions",
"given",
"in",
"the",
"options",
"."
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Support/Image/Resizer.php#L95-L137 | train |
czim/file-handling | src/Support/Image/Resizer.php | Resizer.resizeAuto | protected function resizeAuto(ImageInterface $image, $width, $height)
{
$size = $image->getSize();
$originalWidth = $size->getWidth();
$originalHeight = $size->getHeight();
if ($originalHeight < $originalWidth) {
return $this->resizeLandscape($image, $width, $height);
}
if ($originalHeight > $originalWidth) {
return $this->resizePortrait($image, $width, $height);
}
if ($height < $width) {
return $this->resizeLandscape($image, $width, $height);
}
if ($height > $width) {
return $this->resizePortrait($image, $width, $height);
}
return $this->resizeExact($image, $width, $height);
} | php | protected function resizeAuto(ImageInterface $image, $width, $height)
{
$size = $image->getSize();
$originalWidth = $size->getWidth();
$originalHeight = $size->getHeight();
if ($originalHeight < $originalWidth) {
return $this->resizeLandscape($image, $width, $height);
}
if ($originalHeight > $originalWidth) {
return $this->resizePortrait($image, $width, $height);
}
if ($height < $width) {
return $this->resizeLandscape($image, $width, $height);
}
if ($height > $width) {
return $this->resizePortrait($image, $width, $height);
}
return $this->resizeExact($image, $width, $height);
} | [
"protected",
"function",
"resizeAuto",
"(",
"ImageInterface",
"$",
"image",
",",
"$",
"width",
",",
"$",
"height",
")",
"{",
"$",
"size",
"=",
"$",
"image",
"->",
"getSize",
"(",
")",
";",
"$",
"originalWidth",
"=",
"$",
"size",
"->",
"getWidth",
"(",
... | Resize an image as closely as possible to a given width and height while still maintaining aspect ratio
This method is really just a proxy to other resize methods:.
If the current image is wider than it is tall, we'll resize landscape.
If the current image is taller than it is wide, we'll resize portrait.
If the image is as tall as it is wide (it's a squarey) then we'll
apply the same process using the new dimensions (we'll resize exact if
the new dimensions are both equal since at this point we'll have a square
image being resized to a square).
@param ImageInterface $image
@param string $width new width
@param string $height new height
@return ImageInterface | [
"Resize",
"an",
"image",
"as",
"closely",
"as",
"possible",
"to",
"a",
"given",
"width",
"and",
"height",
"while",
"still",
"maintaining",
"aspect",
"ratio"
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Support/Image/Resizer.php#L157-L180 | train |
czim/file-handling | src/Support/Image/Resizer.php | Resizer.resizeCrop | protected function resizeCrop(ImageInterface $image, $width, $height)
{
list($optimalWidth, $optimalHeight) = $this->getOptimalCrop($image->getSize(), $width, $height);
// Find center - this will be used for the crop
$centerX = ($optimalWidth / 2) - ($width / 2);
$centerY = ($optimalHeight / 2) - ($height / 2);
return $image->resize(new Box($optimalWidth, $optimalHeight))
->crop(new Point($centerX, $centerY), new Box($width, $height));
} | php | protected function resizeCrop(ImageInterface $image, $width, $height)
{
list($optimalWidth, $optimalHeight) = $this->getOptimalCrop($image->getSize(), $width, $height);
// Find center - this will be used for the crop
$centerX = ($optimalWidth / 2) - ($width / 2);
$centerY = ($optimalHeight / 2) - ($height / 2);
return $image->resize(new Box($optimalWidth, $optimalHeight))
->crop(new Point($centerX, $centerY), new Box($width, $height));
} | [
"protected",
"function",
"resizeCrop",
"(",
"ImageInterface",
"$",
"image",
",",
"$",
"width",
",",
"$",
"height",
")",
"{",
"list",
"(",
"$",
"optimalWidth",
",",
"$",
"optimalHeight",
")",
"=",
"$",
"this",
"->",
"getOptimalCrop",
"(",
"$",
"image",
"-... | Resize an image and then center crop it
@param ImageInterface $image
@param string $width new width
@param string $height new height
@return ImageInterface | [
"Resize",
"an",
"image",
"and",
"then",
"center",
"crop",
"it"
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Support/Image/Resizer.php#L248-L258 | train |
czim/file-handling | src/Support/Image/Resizer.php | Resizer.getSizeByFixedHeight | private function getSizeByFixedHeight(ImageInterface $image, $newHeight)
{
$box = $image->getSize();
$ratio = $box->getWidth() / $box->getHeight();
$newWidth = $newHeight * $ratio;
return $newWidth;
} | php | private function getSizeByFixedHeight(ImageInterface $image, $newHeight)
{
$box = $image->getSize();
$ratio = $box->getWidth() / $box->getHeight();
$newWidth = $newHeight * $ratio;
return $newWidth;
} | [
"private",
"function",
"getSizeByFixedHeight",
"(",
"ImageInterface",
"$",
"image",
",",
"$",
"newHeight",
")",
"{",
"$",
"box",
"=",
"$",
"image",
"->",
"getSize",
"(",
")",
";",
"$",
"ratio",
"=",
"$",
"box",
"->",
"getWidth",
"(",
")",
"/",
"$",
"... | Returns the width based on the new image height.
@param ImageInterface $image
@param int $newHeight - The image's new height.
@return int | [
"Returns",
"the",
"width",
"based",
"on",
"the",
"new",
"image",
"height",
"."
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Support/Image/Resizer.php#L293-L301 | train |
czim/file-handling | src/Storage/Laravel/LaravelStorage.php | LaravelStorage.get | public function get($path)
{
$raw = new RawStorableFile;
$raw->setName(pathinfo($path, PATHINFO_BASENAME));
$raw->setData($this->filesystem->get($path));
$stored = new DecoratorStoredFile($raw);
$stored->setUrl($this->prefixBaseUrl($path));
return $stored;
} | php | public function get($path)
{
$raw = new RawStorableFile;
$raw->setName(pathinfo($path, PATHINFO_BASENAME));
$raw->setData($this->filesystem->get($path));
$stored = new DecoratorStoredFile($raw);
$stored->setUrl($this->prefixBaseUrl($path));
return $stored;
} | [
"public",
"function",
"get",
"(",
"$",
"path",
")",
"{",
"$",
"raw",
"=",
"new",
"RawStorableFile",
";",
"$",
"raw",
"->",
"setName",
"(",
"pathinfo",
"(",
"$",
"path",
",",
"PATHINFO_BASENAME",
")",
")",
";",
"$",
"raw",
"->",
"setData",
"(",
"$",
... | Returns the file from storage.
Note that the mimetype is not filled in here. Tackle this manually if it is required.
@param string $path
@return StoredFileInterface | [
"Returns",
"the",
"file",
"from",
"storage",
"."
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Storage/Laravel/LaravelStorage.php#L79-L90 | train |
czim/file-handling | src/Storage/Laravel/LaravelStorage.php | LaravelStorage.store | public function store(StorableFileInterface $file, $path)
{
if ( ! $this->filesystem->put($path, $file->content())) {
throw new FileStorageException("Failed to store '{$file->name()}' to '{$path}'");
}
$stored = new DecoratorStoredFile($file);
$stored->setUrl($this->prefixBaseUrl($path));
return $stored;
} | php | public function store(StorableFileInterface $file, $path)
{
if ( ! $this->filesystem->put($path, $file->content())) {
throw new FileStorageException("Failed to store '{$file->name()}' to '{$path}'");
}
$stored = new DecoratorStoredFile($file);
$stored->setUrl($this->prefixBaseUrl($path));
return $stored;
} | [
"public",
"function",
"store",
"(",
"StorableFileInterface",
"$",
"file",
",",
"$",
"path",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"filesystem",
"->",
"put",
"(",
"$",
"path",
",",
"$",
"file",
"->",
"content",
"(",
")",
")",
")",
"{",
"throw... | Stores a file.
@param StorableFileInterface $file mixed content to store
@param string $path where the file should be stored, including the filename
@return StoredFileInterface
@throws FileStorageException | [
"Stores",
"a",
"file",
"."
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Storage/Laravel/LaravelStorage.php#L100-L110 | train |
czim/file-handling | src/Storage/File/StorableFileFactory.php | StorableFileFactory.makeFromAny | public function makeFromAny($data, $name = null, $mimeType = null)
{
// If the data is already a storable file, return it as-is.
if ($data instanceof StorableFileInterface) {
return $this->getReturnPreparedFile($data);
}
if (null === $name && is_a($data, \Symfony\Component\HttpFoundation\File\UploadedFile::class)) {
/** @var \Symfony\Component\HttpFoundation\File\UploadedFile $data */
$name = $data->getClientOriginalName();
}
if ($data instanceof SplFileInfo) {
return $this->makeFromFileInfo($data, $name, $mimeType);
}
// Fallback: expect raw or string data, and attempt to interpret it.
if (is_string($data)) {
$data = new RawContent($data);
}
if ( ! ($data instanceof RawContentInterface)) {
throw new UnexpectedValueException('Could not interpret given data, string value expected');
}
return $this->interpretFromRawContent($data, $name, $mimeType);
} | php | public function makeFromAny($data, $name = null, $mimeType = null)
{
// If the data is already a storable file, return it as-is.
if ($data instanceof StorableFileInterface) {
return $this->getReturnPreparedFile($data);
}
if (null === $name && is_a($data, \Symfony\Component\HttpFoundation\File\UploadedFile::class)) {
/** @var \Symfony\Component\HttpFoundation\File\UploadedFile $data */
$name = $data->getClientOriginalName();
}
if ($data instanceof SplFileInfo) {
return $this->makeFromFileInfo($data, $name, $mimeType);
}
// Fallback: expect raw or string data, and attempt to interpret it.
if (is_string($data)) {
$data = new RawContent($data);
}
if ( ! ($data instanceof RawContentInterface)) {
throw new UnexpectedValueException('Could not interpret given data, string value expected');
}
return $this->interpretFromRawContent($data, $name, $mimeType);
} | [
"public",
"function",
"makeFromAny",
"(",
"$",
"data",
",",
"$",
"name",
"=",
"null",
",",
"$",
"mimeType",
"=",
"null",
")",
"{",
"// If the data is already a storable file, return it as-is.",
"if",
"(",
"$",
"data",
"instanceof",
"StorableFileInterface",
")",
"{... | Makes a storable file instance from an unknown source type.
@param mixed $data
@param string|null $name
@param string|null $mimeType
@return StorableFileInterface
@throws CouldNotReadDataException
@throws CouldNotRetrieveRemoteFileException | [
"Makes",
"a",
"storable",
"file",
"instance",
"from",
"an",
"unknown",
"source",
"type",
"."
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Storage/File/StorableFileFactory.php#L80-L108 | train |
czim/file-handling | src/Storage/File/StorableFileFactory.php | StorableFileFactory.makeFromFileInfo | public function makeFromFileInfo(SplFileInfo $data, $name = null, $mimeType = null)
{
$file = new SplFileInfoStorableFile;
$file->setData($data);
if (null !== $mimeType) {
$file->setMimeType($mimeType);
} else {
$file->setMimeType(
$this->mimeTypeHelper->guessMimeTypeForPath($data->getRealPath())
);
}
if (empty($name)) {
$name = pathinfo($data->getRealPath(), PATHINFO_BASENAME);
}
if (null !== $name) {
$file->setName($name);
}
return $this->getReturnPreparedFile($file);
} | php | public function makeFromFileInfo(SplFileInfo $data, $name = null, $mimeType = null)
{
$file = new SplFileInfoStorableFile;
$file->setData($data);
if (null !== $mimeType) {
$file->setMimeType($mimeType);
} else {
$file->setMimeType(
$this->mimeTypeHelper->guessMimeTypeForPath($data->getRealPath())
);
}
if (empty($name)) {
$name = pathinfo($data->getRealPath(), PATHINFO_BASENAME);
}
if (null !== $name) {
$file->setName($name);
}
return $this->getReturnPreparedFile($file);
} | [
"public",
"function",
"makeFromFileInfo",
"(",
"SplFileInfo",
"$",
"data",
",",
"$",
"name",
"=",
"null",
",",
"$",
"mimeType",
"=",
"null",
")",
"{",
"$",
"file",
"=",
"new",
"SplFileInfoStorableFile",
";",
"$",
"file",
"->",
"setData",
"(",
"$",
"data"... | Makes a storable file instance from an SplFileInfo instance.
@param SplFileInfo $data
@param string|null $name
@param string|null $mimeType
@return StorableFileInterface | [
"Makes",
"a",
"storable",
"file",
"instance",
"from",
"an",
"SplFileInfo",
"instance",
"."
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Storage/File/StorableFileFactory.php#L118-L140 | train |
czim/file-handling | src/Storage/File/StorableFileFactory.php | StorableFileFactory.makeFromLocalPath | public function makeFromLocalPath($path, $name = null, $mimeType = null)
{
$info = new SplFileInfo($path);
return $this->makeFromFileInfo($info, $name, $mimeType);
} | php | public function makeFromLocalPath($path, $name = null, $mimeType = null)
{
$info = new SplFileInfo($path);
return $this->makeFromFileInfo($info, $name, $mimeType);
} | [
"public",
"function",
"makeFromLocalPath",
"(",
"$",
"path",
",",
"$",
"name",
"=",
"null",
",",
"$",
"mimeType",
"=",
"null",
")",
"{",
"$",
"info",
"=",
"new",
"SplFileInfo",
"(",
"$",
"path",
")",
";",
"return",
"$",
"this",
"->",
"makeFromFileInfo"... | Makes a normalized storable file instance from a local file path.
@param string $path
@param string|null $name
@param string|null $mimeType
@return StorableFileInterface | [
"Makes",
"a",
"normalized",
"storable",
"file",
"instance",
"from",
"a",
"local",
"file",
"path",
"."
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Storage/File/StorableFileFactory.php#L150-L155 | train |
czim/file-handling | src/Storage/File/StorableFileFactory.php | StorableFileFactory.makeFromUrl | public function makeFromUrl($url, $name = null, $mimeType = null)
{
try {
$localPath = $this->downloader->download($url);
} catch (Exception $e) {
throw new CouldNotRetrieveRemoteFileException(
"Could not retrieve file from '{$url}'",
$e->getcode(),
$e
);
}
if (null === $name) {
$name = $this->getBaseNameFromUrl($url);
}
// Always flag as uploaded, since we downloaded to a local path
return $this->uploaded()->makeFromLocalPath($localPath, $name, $mimeType);
} | php | public function makeFromUrl($url, $name = null, $mimeType = null)
{
try {
$localPath = $this->downloader->download($url);
} catch (Exception $e) {
throw new CouldNotRetrieveRemoteFileException(
"Could not retrieve file from '{$url}'",
$e->getcode(),
$e
);
}
if (null === $name) {
$name = $this->getBaseNameFromUrl($url);
}
// Always flag as uploaded, since we downloaded to a local path
return $this->uploaded()->makeFromLocalPath($localPath, $name, $mimeType);
} | [
"public",
"function",
"makeFromUrl",
"(",
"$",
"url",
",",
"$",
"name",
"=",
"null",
",",
"$",
"mimeType",
"=",
"null",
")",
"{",
"try",
"{",
"$",
"localPath",
"=",
"$",
"this",
"->",
"downloader",
"->",
"download",
"(",
"$",
"url",
")",
";",
"}",
... | Makes a normalized storable file instance from a URI.
@param string $url
@param string|null $name
@param string|null $mimeType
@return StorableFileInterface
@throws CouldNotRetrieveRemoteFileException | [
"Makes",
"a",
"normalized",
"storable",
"file",
"instance",
"from",
"a",
"URI",
"."
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Storage/File/StorableFileFactory.php#L166-L186 | train |
czim/file-handling | src/Storage/File/StorableFileFactory.php | StorableFileFactory.makeFromDataUri | public function makeFromDataUri($data, $name = null, $mimeType = null)
{
if ($data instanceof RawContentInterface) {
$data = $data->content();
}
$resource = @fopen($data, 'r');
if ( ! $resource) {
throw new CouldNotReadDataException('Invalid data URI');
}
try {
$meta = stream_get_meta_data($resource);
// @codeCoverageIgnoreStart
} catch (Exception $e) {
throw new CouldNotReadDataException('Failed to interpret Data URI as stream', $e->getCode(), $e);
// @codeCoverageIgnoreEnd
}
if (null === $mimeType) {
$mimeType = $meta['mediatype'];
}
$extension = $this->mimeTypeHelper->guessExtensionForMimeType($mimeType);
$localPath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . md5($meta['uri']) . '.' . $extension;
if (null === $name) {
$name = pathinfo($localPath, PATHINFO_BASENAME);
}
try {
file_put_contents($localPath, stream_get_contents($resource));
// @codeCoverageIgnoreStart
} catch (Exception $e) {
throw new CouldNotReadDataException('Failed to make local file from Data URI', $e->getCode(), $e);
// @codeCoverageIgnoreEnd
}
// Always flag as uploaded, since a temp file was created
return $this->uploaded()->makeFromLocalPath($localPath, $name);
} | php | public function makeFromDataUri($data, $name = null, $mimeType = null)
{
if ($data instanceof RawContentInterface) {
$data = $data->content();
}
$resource = @fopen($data, 'r');
if ( ! $resource) {
throw new CouldNotReadDataException('Invalid data URI');
}
try {
$meta = stream_get_meta_data($resource);
// @codeCoverageIgnoreStart
} catch (Exception $e) {
throw new CouldNotReadDataException('Failed to interpret Data URI as stream', $e->getCode(), $e);
// @codeCoverageIgnoreEnd
}
if (null === $mimeType) {
$mimeType = $meta['mediatype'];
}
$extension = $this->mimeTypeHelper->guessExtensionForMimeType($mimeType);
$localPath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . md5($meta['uri']) . '.' . $extension;
if (null === $name) {
$name = pathinfo($localPath, PATHINFO_BASENAME);
}
try {
file_put_contents($localPath, stream_get_contents($resource));
// @codeCoverageIgnoreStart
} catch (Exception $e) {
throw new CouldNotReadDataException('Failed to make local file from Data URI', $e->getCode(), $e);
// @codeCoverageIgnoreEnd
}
// Always flag as uploaded, since a temp file was created
return $this->uploaded()->makeFromLocalPath($localPath, $name);
} | [
"public",
"function",
"makeFromDataUri",
"(",
"$",
"data",
",",
"$",
"name",
"=",
"null",
",",
"$",
"mimeType",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"data",
"instanceof",
"RawContentInterface",
")",
"{",
"$",
"data",
"=",
"$",
"data",
"->",
"content"... | Makes a normalized storable file instance from a data URI.
@param string|RawContentInterface $data
@param string|null $name
@param string|null $mimeType
@return StorableFileInterface
@throws CouldNotReadDataException | [
"Makes",
"a",
"normalized",
"storable",
"file",
"instance",
"from",
"a",
"data",
"URI",
"."
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Storage/File/StorableFileFactory.php#L197-L238 | train |
czim/file-handling | src/Storage/File/StorableFileFactory.php | StorableFileFactory.makeFromRawData | public function makeFromRawData($data, $name = null, $mimeType = null)
{
$file = new RawStorableFile;
if ($data instanceof RawContentInterface) {
$data = $data->content();
}
// Guess the mimetype directly from the content
if (null === $mimeType) {
$mimeType = $this->mimeTypeHelper->guessMimeTypeForContent($data);
}
if (empty($name)) {
$name = $this->makeRandomName(
$this->mimeTypeHelper->guessExtensionForMimeType($mimeType)
);
}
$file->setName($name);
$file->setData($data);
$file->setMimeType($mimeType);
return $this->getReturnPreparedFile($file);
} | php | public function makeFromRawData($data, $name = null, $mimeType = null)
{
$file = new RawStorableFile;
if ($data instanceof RawContentInterface) {
$data = $data->content();
}
// Guess the mimetype directly from the content
if (null === $mimeType) {
$mimeType = $this->mimeTypeHelper->guessMimeTypeForContent($data);
}
if (empty($name)) {
$name = $this->makeRandomName(
$this->mimeTypeHelper->guessExtensionForMimeType($mimeType)
);
}
$file->setName($name);
$file->setData($data);
$file->setMimeType($mimeType);
return $this->getReturnPreparedFile($file);
} | [
"public",
"function",
"makeFromRawData",
"(",
"$",
"data",
",",
"$",
"name",
"=",
"null",
",",
"$",
"mimeType",
"=",
"null",
")",
"{",
"$",
"file",
"=",
"new",
"RawStorableFile",
";",
"if",
"(",
"$",
"data",
"instanceof",
"RawContentInterface",
")",
"{",... | Makes a normalized storable file instance from raw content data.
@param string|RawContentInterface $data
@param string|null $name
@param string|null $mimeType
@return StorableFileInterface | [
"Makes",
"a",
"normalized",
"storable",
"file",
"instance",
"from",
"raw",
"content",
"data",
"."
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Storage/File/StorableFileFactory.php#L248-L272 | train |
czim/file-handling | src/Storage/File/StorableFileFactory.php | StorableFileFactory.interpretFromRawContent | protected function interpretFromRawContent(RawContentInterface $data, $name, $mimeType)
{
switch ($this->interpreter->interpret($data)) {
case ContentTypes::URI:
return $this->makeFromUrl($data->content(), $name, $mimeType);
case ContentTypes::DATAURI:
return $this->makeFromDataUri($data, $name, $mimeType);
case ContentTypes::RAW:
default:
return $this->makeFromRawData($data, $name, $mimeType);
}
} | php | protected function interpretFromRawContent(RawContentInterface $data, $name, $mimeType)
{
switch ($this->interpreter->interpret($data)) {
case ContentTypes::URI:
return $this->makeFromUrl($data->content(), $name, $mimeType);
case ContentTypes::DATAURI:
return $this->makeFromDataUri($data, $name, $mimeType);
case ContentTypes::RAW:
default:
return $this->makeFromRawData($data, $name, $mimeType);
}
} | [
"protected",
"function",
"interpretFromRawContent",
"(",
"RawContentInterface",
"$",
"data",
",",
"$",
"name",
",",
"$",
"mimeType",
")",
"{",
"switch",
"(",
"$",
"this",
"->",
"interpreter",
"->",
"interpret",
"(",
"$",
"data",
")",
")",
"{",
"case",
"Con... | Interprets given raw content as a storable file.
@param RawContentInterface $data
@param string|null $name
@param string|null $mimeType
@return StorableFileInterface
@throws CouldNotReadDataException
@throws CouldNotRetrieveRemoteFileException | [
"Interprets",
"given",
"raw",
"content",
"as",
"a",
"storable",
"file",
"."
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Storage/File/StorableFileFactory.php#L284-L298 | train |
czim/file-handling | src/Variant/VariantStrategyFactory.php | VariantStrategyFactory.make | public function make($strategy, array $options = [])
{
$instance = $this->instantiateClass(
$this->resolveStrategyClassName($strategy)
);
if ( ! ($instance instanceof VariantStrategyInterface)) {
throw new RuntimeException("Variant strategy created for '{$strategy}' is of incorrect type");
}
return $instance->setOptions($options);
} | php | public function make($strategy, array $options = [])
{
$instance = $this->instantiateClass(
$this->resolveStrategyClassName($strategy)
);
if ( ! ($instance instanceof VariantStrategyInterface)) {
throw new RuntimeException("Variant strategy created for '{$strategy}' is of incorrect type");
}
return $instance->setOptions($options);
} | [
"public",
"function",
"make",
"(",
"$",
"strategy",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"instance",
"=",
"$",
"this",
"->",
"instantiateClass",
"(",
"$",
"this",
"->",
"resolveStrategyClassName",
"(",
"$",
"strategy",
")",
")",
... | Returns strategy instance.
@param string $strategy strategy class or alias
@param array $options options for the strategy
@return VariantStrategyInterface | [
"Returns",
"strategy",
"instance",
"."
] | eeca2954d30fee0122468ed4c74ed74fe6eed27f | https://github.com/czim/file-handling/blob/eeca2954d30fee0122468ed4c74ed74fe6eed27f/src/Variant/VariantStrategyFactory.php#L58-L69 | train |
netgen/NetgenSiteAccessRoutesBundle | bundle/EventListener/RequestListener.php | RequestListener.onKernelRequest | public function onKernelRequest(GetResponseEvent $event)
{
if ($event->getRequestType() !== HttpKernelInterface::MASTER_REQUEST) {
return;
}
$requestAttributes = $event->getRequest()->attributes;
$currentSiteAccess = $requestAttributes->get('siteaccess');
$allowedSiteAccesses = $requestAttributes->get(self::ALLOWED_SITEACCESSES_KEY);
// We allow the route if no current siteaccess is set or
// no allowed siteaccesses (meaning all are allowed) are defined
if (!$currentSiteAccess instanceof SiteAccess || empty($allowedSiteAccesses)) {
return;
}
if (!is_array($allowedSiteAccesses)) {
$allowedSiteAccesses = array($allowedSiteAccesses);
}
if ($this->matcher->isAllowed($currentSiteAccess->name, $allowedSiteAccesses)) {
return;
}
throw new NotFoundHttpException('Route is not allowed in current siteaccess');
} | php | public function onKernelRequest(GetResponseEvent $event)
{
if ($event->getRequestType() !== HttpKernelInterface::MASTER_REQUEST) {
return;
}
$requestAttributes = $event->getRequest()->attributes;
$currentSiteAccess = $requestAttributes->get('siteaccess');
$allowedSiteAccesses = $requestAttributes->get(self::ALLOWED_SITEACCESSES_KEY);
// We allow the route if no current siteaccess is set or
// no allowed siteaccesses (meaning all are allowed) are defined
if (!$currentSiteAccess instanceof SiteAccess || empty($allowedSiteAccesses)) {
return;
}
if (!is_array($allowedSiteAccesses)) {
$allowedSiteAccesses = array($allowedSiteAccesses);
}
if ($this->matcher->isAllowed($currentSiteAccess->name, $allowedSiteAccesses)) {
return;
}
throw new NotFoundHttpException('Route is not allowed in current siteaccess');
} | [
"public",
"function",
"onKernelRequest",
"(",
"GetResponseEvent",
"$",
"event",
")",
"{",
"if",
"(",
"$",
"event",
"->",
"getRequestType",
"(",
")",
"!==",
"HttpKernelInterface",
"::",
"MASTER_REQUEST",
")",
"{",
"return",
";",
"}",
"$",
"requestAttributes",
"... | Throws an exception if current route is not allowed in current siteaccess.
@param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event | [
"Throws",
"an",
"exception",
"if",
"current",
"route",
"is",
"not",
"allowed",
"in",
"current",
"siteaccess",
"."
] | dbc6bec2d7ba06737cc09411c7677fcc1b703c4b | https://github.com/netgen/NetgenSiteAccessRoutesBundle/blob/dbc6bec2d7ba06737cc09411c7677fcc1b703c4b/bundle/EventListener/RequestListener.php#L50-L76 | train |
zofe/burp | src/Burp.php | Burp.fixParams | private static function fixParams($method, $params)
{
if (! in_array(strtolower($method), array('get','post','patch','put','delete','any','head')))
throw new \BadMethodCallException("valid methods are 'get','post','patch','put','delete','any','head'");
//fix closures / controllers
if (is_array($params) && isset($params[2]) && is_array($params[2])) {
//controller@method
if (isset($params[2]['uses']) && is_string($params[2]['uses']) && strpos($params[2]['uses'], '@'))
{
$callback = explode('@', $params[2]['uses']);
$params[2] = array('as'=>$params[2]['as'], 'uses'=> $callback);
}
//closure fix
if (isset($params[2]['as']) && isset($params[2][0]) && ($params[2][0] instanceof \Closure))
{
$params[2] = array('as'=>$params[2]['as'], 'uses'=> $params[2][0]);
}
}
//no route name given, so route_name will be the first parameter
if (is_array($params) && isset($params[2]) && ($params[2] instanceof \Closure)) {
$params[2] = array('as'=>$params[0], 'uses'=>$params[2]);
}
if (count($params)<3 ||
!is_array($params[2]) ||
!array_key_exists('as', $params[2]) ||
!array_key_exists('uses', $params[2]) ||
!($params[2]['uses'] instanceof \Closure || is_array($params[2]['uses'])) )
throw new \InvalidArgumentException('third parameter should be an array containing a
valid callback : array(\'as\'=>\'routename\', function () { }) ');
return $params;
} | php | private static function fixParams($method, $params)
{
if (! in_array(strtolower($method), array('get','post','patch','put','delete','any','head')))
throw new \BadMethodCallException("valid methods are 'get','post','patch','put','delete','any','head'");
//fix closures / controllers
if (is_array($params) && isset($params[2]) && is_array($params[2])) {
//controller@method
if (isset($params[2]['uses']) && is_string($params[2]['uses']) && strpos($params[2]['uses'], '@'))
{
$callback = explode('@', $params[2]['uses']);
$params[2] = array('as'=>$params[2]['as'], 'uses'=> $callback);
}
//closure fix
if (isset($params[2]['as']) && isset($params[2][0]) && ($params[2][0] instanceof \Closure))
{
$params[2] = array('as'=>$params[2]['as'], 'uses'=> $params[2][0]);
}
}
//no route name given, so route_name will be the first parameter
if (is_array($params) && isset($params[2]) && ($params[2] instanceof \Closure)) {
$params[2] = array('as'=>$params[0], 'uses'=>$params[2]);
}
if (count($params)<3 ||
!is_array($params[2]) ||
!array_key_exists('as', $params[2]) ||
!array_key_exists('uses', $params[2]) ||
!($params[2]['uses'] instanceof \Closure || is_array($params[2]['uses'])) )
throw new \InvalidArgumentException('third parameter should be an array containing a
valid callback : array(\'as\'=>\'routename\', function () { }) ');
return $params;
} | [
"private",
"static",
"function",
"fixParams",
"(",
"$",
"method",
",",
"$",
"params",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"strtolower",
"(",
"$",
"method",
")",
",",
"array",
"(",
"'get'",
",",
"'post'",
",",
"'patch'",
",",
"'put'",
",",
"'de... | check if route method call is correct, and try to fix if not
@param $method
@param $params | [
"check",
"if",
"route",
"method",
"call",
"is",
"correct",
"and",
"try",
"to",
"fix",
"if",
"not"
] | 1b2983041d733df1c0633abe5a7c30e3baca1468 | https://github.com/zofe/burp/blob/1b2983041d733df1c0633abe5a7c30e3baca1468/src/Burp.php#L174-L213 | train |
zofe/burp | src/Burp.php | Burp.remove | public function remove()
{
$routes = (is_array(func_get_arg(0))) ? func_get_arg(0) : func_get_args();
end(self::$routes);
self::$remove[key(self::$routes)] = $routes;
return new static();
} | php | public function remove()
{
$routes = (is_array(func_get_arg(0))) ? func_get_arg(0) : func_get_args();
end(self::$routes);
self::$remove[key(self::$routes)] = $routes;
return new static();
} | [
"public",
"function",
"remove",
"(",
")",
"{",
"$",
"routes",
"=",
"(",
"is_array",
"(",
"func_get_arg",
"(",
"0",
")",
")",
")",
"?",
"func_get_arg",
"(",
"0",
")",
":",
"func_get_args",
"(",
")",
";",
"end",
"(",
"self",
"::",
"$",
"routes",
")",... | queque to remove from url one or more named route
@return static | [
"queque",
"to",
"remove",
"from",
"url",
"one",
"or",
"more",
"named",
"route"
] | 1b2983041d733df1c0633abe5a7c30e3baca1468 | https://github.com/zofe/burp/blob/1b2983041d733df1c0633abe5a7c30e3baca1468/src/Burp.php#L220-L227 | train |
zofe/burp | src/Burp.php | Burp.linkUrl | public static function linkUrl($url, $title = null, $attributes = array())
{
$title = ($title) ? $title : $url;
$compiled = '';
if (count($attributes)) {
$compiled = '';
foreach ($attributes as $key => $val) {
$compiled .= ' ' . $key . '="' . htmlspecialchars((string) $val, ENT_QUOTES, "UTF-8", true) . '"';
}
}
return '<a href="'.$url.'"'.$compiled.'>'.$title.'</a>';
} | php | public static function linkUrl($url, $title = null, $attributes = array())
{
$title = ($title) ? $title : $url;
$compiled = '';
if (count($attributes)) {
$compiled = '';
foreach ($attributes as $key => $val) {
$compiled .= ' ' . $key . '="' . htmlspecialchars((string) $val, ENT_QUOTES, "UTF-8", true) . '"';
}
}
return '<a href="'.$url.'"'.$compiled.'>'.$title.'</a>';
} | [
"public",
"static",
"function",
"linkUrl",
"(",
"$",
"url",
",",
"$",
"title",
"=",
"null",
",",
"$",
"attributes",
"=",
"array",
"(",
")",
")",
"{",
"$",
"title",
"=",
"(",
"$",
"title",
")",
"?",
"$",
"title",
":",
"$",
"url",
";",
"$",
"comp... | return a plain html link
@param $url
@param null $title
@param array $attributes
@return string | [
"return",
"a",
"plain",
"html",
"link"
] | 1b2983041d733df1c0633abe5a7c30e3baca1468 | https://github.com/zofe/burp/blob/1b2983041d733df1c0633abe5a7c30e3baca1468/src/Burp.php#L337-L348 | train |
zofe/burp | src/Burp.php | Burp.replacePattern | protected static function replacePattern($pattern, $container, $url, $conditional, $remove_conditional)
{
if (array_key_exists($pattern, $container)) {
$replace = (count(self::$parameters[$pattern]) || $conditional) ? '('.$container[$pattern].')' : $container[$pattern];
if ($conditional) {
$replace = ($remove_conditional) ? '' : $replace.'?';
$url = preg_replace('#\{'.$pattern.'\?\}#', $replace, $url);
} else {
$url = preg_replace('#\{'.$pattern.'\}#', $replace, $url);
}
}
return $url;
} | php | protected static function replacePattern($pattern, $container, $url, $conditional, $remove_conditional)
{
if (array_key_exists($pattern, $container)) {
$replace = (count(self::$parameters[$pattern]) || $conditional) ? '('.$container[$pattern].')' : $container[$pattern];
if ($conditional) {
$replace = ($remove_conditional) ? '' : $replace.'?';
$url = preg_replace('#\{'.$pattern.'\?\}#', $replace, $url);
} else {
$url = preg_replace('#\{'.$pattern.'\}#', $replace, $url);
}
}
return $url;
} | [
"protected",
"static",
"function",
"replacePattern",
"(",
"$",
"pattern",
",",
"$",
"container",
",",
"$",
"url",
",",
"$",
"conditional",
",",
"$",
"remove_conditional",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"pattern",
",",
"$",
"container",
... | replace a pattern in an array of rules
@param $pattern
@param $container
@param $url
@param $conditional
@param $remove_conditional
@return string | [
"replace",
"a",
"pattern",
"in",
"an",
"array",
"of",
"rules"
] | 1b2983041d733df1c0633abe5a7c30e3baca1468 | https://github.com/zofe/burp/blob/1b2983041d733df1c0633abe5a7c30e3baca1468/src/Burp.php#L373-L385 | train |
paragonie/pharaoh | src/Pharaoh/PharDiff.php | PharDiff.printGitDiff | public function printGitDiff(): int
{
// Lazy way; requires git. Will replace with custom implementaiton later.
$argA = \escapeshellarg($this->phars[0]->tmp);
$argB = \escapeshellarg($this->phars[1]->tmp);
/** @var string $diff */
$diff = `git diff --no-index $argA $argB`;
echo $diff;
if (empty($diff) && $this->verbose) {
echo 'No differences encountered.', PHP_EOL;
return 0;
}
return 1;
}
/**
* Prints a GNU diff of the two phars.
*
* @psalm-suppress ForbiddenCode
* @return int
*/
public function printGnuDiff(): int
{
// Lazy way. Will replace with custom implementaiton later.
$argA = \escapeshellarg($this->phars[0]->tmp);
$argB = \escapeshellarg($this->phars[1]->tmp);
/** @var string $diff */
$diff = `diff $argA $argB`;
echo $diff;
if (empty($diff) && $this->verbose) {
echo 'No differences encountered.', PHP_EOL;
return 0;
}
return 1;
} | php | public function printGitDiff(): int
{
// Lazy way; requires git. Will replace with custom implementaiton later.
$argA = \escapeshellarg($this->phars[0]->tmp);
$argB = \escapeshellarg($this->phars[1]->tmp);
/** @var string $diff */
$diff = `git diff --no-index $argA $argB`;
echo $diff;
if (empty($diff) && $this->verbose) {
echo 'No differences encountered.', PHP_EOL;
return 0;
}
return 1;
}
/**
* Prints a GNU diff of the two phars.
*
* @psalm-suppress ForbiddenCode
* @return int
*/
public function printGnuDiff(): int
{
// Lazy way. Will replace with custom implementaiton later.
$argA = \escapeshellarg($this->phars[0]->tmp);
$argB = \escapeshellarg($this->phars[1]->tmp);
/** @var string $diff */
$diff = `diff $argA $argB`;
echo $diff;
if (empty($diff) && $this->verbose) {
echo 'No differences encountered.', PHP_EOL;
return 0;
}
return 1;
} | [
"public",
"function",
"printGitDiff",
"(",
")",
":",
"int",
"{",
"// Lazy way; requires git. Will replace with custom implementaiton later.",
"$",
"argA",
"=",
"\\",
"escapeshellarg",
"(",
"$",
"this",
"->",
"phars",
"[",
"0",
"]",
"->",
"tmp",
")",
";",
"$",
"a... | Prints a git-formatted diff of the two phars.
@psalm-suppress ForbiddenCode
@return int | [
"Prints",
"a",
"git",
"-",
"formatted",
"diff",
"of",
"the",
"two",
"phars",
"."
] | 060418e946de2f39a3618ad70d9b6d0a61437b83 | https://github.com/paragonie/pharaoh/blob/060418e946de2f39a3618ad70d9b6d0a61437b83/src/Pharaoh/PharDiff.php#L48-L83 | train |
paragonie/pharaoh | src/Pharaoh/PharDiff.php | PharDiff.hashChildren | public function hashChildren(string $algo,string $dirA, string $dirB)
{
/**
* @var string $a
* @var string $b
*/
$a = $b = '';
$filesA = $this->listAllFiles($dirA);
$filesB = $this->listAllFiles($dirB);
$numFiles = \max(\count($filesA), \count($filesB));
// Array of two empty arrays
$hashes = [[], []];
for ($i = 0; $i < $numFiles; ++$i) {
$thisFileA = (string) $filesA[$i];
$thisFileB = (string) $filesB[$i];
if (isset($filesA[$i])) {
$a = \preg_replace('#^'.\preg_quote($dirA, '#').'#', '', $thisFileA);
if (isset($filesB[$i])) {
$b = \preg_replace('#^'.\preg_quote($dirB, '#').'#', '', $thisFileB);
} else {
$b = $a;
}
} elseif (isset($filesB[$i])) {
$b = \preg_replace('#^'.\preg_quote($dirB, '#').'#', '', $thisFileB);
$a = $b;
}
if (isset($filesA[$i])) {
// A exists
if (\strtolower($algo) === 'blake2b') {
$hashes[0][$a] = Hex::encode(\ParagonIE_Sodium_File::generichash($thisFileA));
} else {
$hashes[0][$a] = \hash_file($algo, $thisFileA);
}
} elseif (isset($filesB[$i])) {
// A doesn't exist, B does
$hashes[0][$a] = '';
}
if (isset($filesB[$i])) {
// B exists
if (\strtolower($algo) === 'blake2b') {
$hashes[1][$b] = Hex::encode(\ParagonIE_Sodium_File::generichash($thisFileB));
} else {
$hashes[1][$b] = \hash_file($algo, $thisFileB);
}
} elseif (isset($filesA[$i])) {
// B doesn't exist, A does
$hashes[1][$b] = '';
}
}
return $hashes;
} | php | public function hashChildren(string $algo,string $dirA, string $dirB)
{
/**
* @var string $a
* @var string $b
*/
$a = $b = '';
$filesA = $this->listAllFiles($dirA);
$filesB = $this->listAllFiles($dirB);
$numFiles = \max(\count($filesA), \count($filesB));
// Array of two empty arrays
$hashes = [[], []];
for ($i = 0; $i < $numFiles; ++$i) {
$thisFileA = (string) $filesA[$i];
$thisFileB = (string) $filesB[$i];
if (isset($filesA[$i])) {
$a = \preg_replace('#^'.\preg_quote($dirA, '#').'#', '', $thisFileA);
if (isset($filesB[$i])) {
$b = \preg_replace('#^'.\preg_quote($dirB, '#').'#', '', $thisFileB);
} else {
$b = $a;
}
} elseif (isset($filesB[$i])) {
$b = \preg_replace('#^'.\preg_quote($dirB, '#').'#', '', $thisFileB);
$a = $b;
}
if (isset($filesA[$i])) {
// A exists
if (\strtolower($algo) === 'blake2b') {
$hashes[0][$a] = Hex::encode(\ParagonIE_Sodium_File::generichash($thisFileA));
} else {
$hashes[0][$a] = \hash_file($algo, $thisFileA);
}
} elseif (isset($filesB[$i])) {
// A doesn't exist, B does
$hashes[0][$a] = '';
}
if (isset($filesB[$i])) {
// B exists
if (\strtolower($algo) === 'blake2b') {
$hashes[1][$b] = Hex::encode(\ParagonIE_Sodium_File::generichash($thisFileB));
} else {
$hashes[1][$b] = \hash_file($algo, $thisFileB);
}
} elseif (isset($filesA[$i])) {
// B doesn't exist, A does
$hashes[1][$b] = '';
}
}
return $hashes;
} | [
"public",
"function",
"hashChildren",
"(",
"string",
"$",
"algo",
",",
"string",
"$",
"dirA",
",",
"string",
"$",
"dirB",
")",
"{",
"/**\n * @var string $a\n * @var string $b\n */",
"$",
"a",
"=",
"$",
"b",
"=",
"''",
";",
"$",
"filesA",
... | Get hashes of all of the files in the two arrays.
@param string $algo
@param string $dirA
@param string $dirB
@return array<int, array<mixed, string>>
@throws \SodiumException | [
"Get",
"hashes",
"of",
"all",
"of",
"the",
"files",
"in",
"the",
"two",
"arrays",
"."
] | 060418e946de2f39a3618ad70d9b6d0a61437b83 | https://github.com/paragonie/pharaoh/blob/060418e946de2f39a3618ad70d9b6d0a61437b83/src/Pharaoh/PharDiff.php#L94-L147 | train |
paragonie/pharaoh | src/Pharaoh/PharDiff.php | PharDiff.listChecksums | public function listChecksums(string $algo = 'sha384'): int
{
list($pharA, $pharB) = $this->hashChildren(
$algo,
$this->phars[0]->tmp,
$this->phars[1]->tmp
);
$diffs = 0;
/** @var string $i */
foreach (\array_keys($pharA) as $i) {
if (isset($pharA[$i]) && isset($pharB[$i])) {
// We are NOT concerned about local timing attacks.
if ($pharA[$i] !== $pharB[$i]) {
++$diffs;
echo "\t", (string) $i,
"\n\t\t", $this->c['red'], $pharA[$i], $this->c[''],
"\t", $this->c['green'], $pharB[$i], $this->c[''],
"\n";
} elseif (!empty($pharA[$i]) && empty($pharB[$i])) {
++$diffs;
echo "\t", (string) $i,
"\n\t\t", $this->c['red'], $pharA[$i], $this->c[''],
"\t", \str_repeat('-', \strlen($pharA[$i])),
"\n";
} elseif (!empty($pharB[$i]) && empty($pharA[$i])) {
++$diffs;
echo "\t", (string) $i,
"\n\t\t", \str_repeat('-', \strlen($pharB[$i])),
"\t", $this->c['green'], $pharB[$i], $this->c[''],
"\n";
}
}
}
if ($diffs === 0) {
if ($this->verbose) {
echo 'No differences encountered.', PHP_EOL;
}
return 0;
}
return 1;
} | php | public function listChecksums(string $algo = 'sha384'): int
{
list($pharA, $pharB) = $this->hashChildren(
$algo,
$this->phars[0]->tmp,
$this->phars[1]->tmp
);
$diffs = 0;
/** @var string $i */
foreach (\array_keys($pharA) as $i) {
if (isset($pharA[$i]) && isset($pharB[$i])) {
// We are NOT concerned about local timing attacks.
if ($pharA[$i] !== $pharB[$i]) {
++$diffs;
echo "\t", (string) $i,
"\n\t\t", $this->c['red'], $pharA[$i], $this->c[''],
"\t", $this->c['green'], $pharB[$i], $this->c[''],
"\n";
} elseif (!empty($pharA[$i]) && empty($pharB[$i])) {
++$diffs;
echo "\t", (string) $i,
"\n\t\t", $this->c['red'], $pharA[$i], $this->c[''],
"\t", \str_repeat('-', \strlen($pharA[$i])),
"\n";
} elseif (!empty($pharB[$i]) && empty($pharA[$i])) {
++$diffs;
echo "\t", (string) $i,
"\n\t\t", \str_repeat('-', \strlen($pharB[$i])),
"\t", $this->c['green'], $pharB[$i], $this->c[''],
"\n";
}
}
}
if ($diffs === 0) {
if ($this->verbose) {
echo 'No differences encountered.', PHP_EOL;
}
return 0;
}
return 1;
} | [
"public",
"function",
"listChecksums",
"(",
"string",
"$",
"algo",
"=",
"'sha384'",
")",
":",
"int",
"{",
"list",
"(",
"$",
"pharA",
",",
"$",
"pharB",
")",
"=",
"$",
"this",
"->",
"hashChildren",
"(",
"$",
"algo",
",",
"$",
"this",
"->",
"phars",
... | Prints out all of the differences of checksums of the files contained
in both PHP archives.
@param string $algo
@return int
@throws \SodiumException | [
"Prints",
"out",
"all",
"of",
"the",
"differences",
"of",
"checksums",
"of",
"the",
"files",
"contained",
"in",
"both",
"PHP",
"archives",
"."
] | 060418e946de2f39a3618ad70d9b6d0a61437b83 | https://github.com/paragonie/pharaoh/blob/060418e946de2f39a3618ad70d9b6d0a61437b83/src/Pharaoh/PharDiff.php#L205-L246 | train |
younishd/endobox | src/endobox/RendererDecorator.php | RendererDecorator.render | public function render(Renderable $input, array &$data = null, array $shared = null) : string
{
return $this->renderer->render($input, $data, $shared);
} | php | public function render(Renderable $input, array &$data = null, array $shared = null) : string
{
return $this->renderer->render($input, $data, $shared);
} | [
"public",
"function",
"render",
"(",
"Renderable",
"$",
"input",
",",
"array",
"&",
"$",
"data",
"=",
"null",
",",
"array",
"$",
"shared",
"=",
"null",
")",
":",
"string",
"{",
"return",
"$",
"this",
"->",
"renderer",
"->",
"render",
"(",
"$",
"input... | Delegate render functionality to renderer. | [
"Delegate",
"render",
"functionality",
"to",
"renderer",
"."
] | a4b9e6aaf954c53c29d4c4e2c1d7a4f8528d0d69 | https://github.com/younishd/endobox/blob/a4b9e6aaf954c53c29d4c4e2c1d7a4f8528d0d69/src/endobox/RendererDecorator.php#L30-L33 | train |
younishd/endobox | src/endobox/Box.php | Box.render | public function render() : string
{
// assign data if any
if (\func_num_args() > 0) {
// php 7.2.0 is crazy
$args = \func_get_args();
$this->assign($args[0]);
}
$result = '';
$shared = [];
foreach ($this as $box) {
// if box has no shared data
if ($box->child === $box) {
// render, concat, and continue
$result .= $box->renderer->render($box->interior, $box->data);
continue;
}
// cache union sets of shared data arrays using root as key
$root = $box->find();
$key = \spl_object_hash($root);
if (!isset($shared[$key])) {
$shared[$key] = [];
$shared[$key][] = &$root->data;
for ($i = $root->child; $i !== $root; $i = $i->child) {
$shared[$key][] = &$i->data;
}
}
// render with shared data and concat results
$result .= $box->renderer->render($box->interior, $box->data, $shared[$key]);
}
return $result;
} | php | public function render() : string
{
// assign data if any
if (\func_num_args() > 0) {
// php 7.2.0 is crazy
$args = \func_get_args();
$this->assign($args[0]);
}
$result = '';
$shared = [];
foreach ($this as $box) {
// if box has no shared data
if ($box->child === $box) {
// render, concat, and continue
$result .= $box->renderer->render($box->interior, $box->data);
continue;
}
// cache union sets of shared data arrays using root as key
$root = $box->find();
$key = \spl_object_hash($root);
if (!isset($shared[$key])) {
$shared[$key] = [];
$shared[$key][] = &$root->data;
for ($i = $root->child; $i !== $root; $i = $i->child) {
$shared[$key][] = &$i->data;
}
}
// render with shared data and concat results
$result .= $box->renderer->render($box->interior, $box->data, $shared[$key]);
}
return $result;
} | [
"public",
"function",
"render",
"(",
")",
":",
"string",
"{",
"// assign data if any",
"if",
"(",
"\\",
"func_num_args",
"(",
")",
">",
"0",
")",
"{",
"// php 7.2.0 is crazy",
"$",
"args",
"=",
"\\",
"func_get_args",
"(",
")",
";",
"$",
"this",
"->",
"as... | Render the box and everything attached to it then return the result. | [
"Render",
"the",
"box",
"and",
"everything",
"attached",
"to",
"it",
"then",
"return",
"the",
"result",
"."
] | a4b9e6aaf954c53c29d4c4e2c1d7a4f8528d0d69 | https://github.com/younishd/endobox/blob/a4b9e6aaf954c53c29d4c4e2c1d7a4f8528d0d69/src/endobox/Box.php#L136-L172 | train |
younishd/endobox | src/endobox/Box.php | Box.append | public function append(Box $b) : Box
{
if ($this->next === null && $b->prev === null) {
$this->next = $b;
$b->prev = $this;
} else {
$this->tail()->append($b->head());
}
return $this;
} | php | public function append(Box $b) : Box
{
if ($this->next === null && $b->prev === null) {
$this->next = $b;
$b->prev = $this;
} else {
$this->tail()->append($b->head());
}
return $this;
} | [
"public",
"function",
"append",
"(",
"Box",
"$",
"b",
")",
":",
"Box",
"{",
"if",
"(",
"$",
"this",
"->",
"next",
"===",
"null",
"&&",
"$",
"b",
"->",
"prev",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"next",
"=",
"$",
"b",
";",
"$",
"b",
... | Append a Box to the end of the linked list and return this instance. | [
"Append",
"a",
"Box",
"to",
"the",
"end",
"of",
"the",
"linked",
"list",
"and",
"return",
"this",
"instance",
"."
] | a4b9e6aaf954c53c29d4c4e2c1d7a4f8528d0d69 | https://github.com/younishd/endobox/blob/a4b9e6aaf954c53c29d4c4e2c1d7a4f8528d0d69/src/endobox/Box.php#L182-L191 | train |
younishd/endobox | src/endobox/Box.php | Box.entangle | public function entangle(Box $b) : Box
{
$root1 = $this->find();
$root2 = $b->find();
// if already in same set then nothing to do
if ($root1 === $root2) {
return $this;
}
// union by rank
if ($root1->rank > $root2->rank) {
$root2->parent = $root1;
} elseif ($root2->rank > $root1->rank) {
$root1->parent = $root2;
} else {
$root2->parent = $root1;
++$root1->rank;
}
// merge circular linked lists
$tmp = $this->child;
$this->child = $b->child;
$b->child = $tmp;
return $this;
} | php | public function entangle(Box $b) : Box
{
$root1 = $this->find();
$root2 = $b->find();
// if already in same set then nothing to do
if ($root1 === $root2) {
return $this;
}
// union by rank
if ($root1->rank > $root2->rank) {
$root2->parent = $root1;
} elseif ($root2->rank > $root1->rank) {
$root1->parent = $root2;
} else {
$root2->parent = $root1;
++$root1->rank;
}
// merge circular linked lists
$tmp = $this->child;
$this->child = $b->child;
$b->child = $tmp;
return $this;
} | [
"public",
"function",
"entangle",
"(",
"Box",
"$",
"b",
")",
":",
"Box",
"{",
"$",
"root1",
"=",
"$",
"this",
"->",
"find",
"(",
")",
";",
"$",
"root2",
"=",
"$",
"b",
"->",
"find",
"(",
")",
";",
"// if already in same set then nothing to do",
"if",
... | Union by rank. | [
"Union",
"by",
"rank",
"."
] | a4b9e6aaf954c53c29d4c4e2c1d7a4f8528d0d69 | https://github.com/younishd/endobox/blob/a4b9e6aaf954c53c29d4c4e2c1d7a4f8528d0d69/src/endobox/Box.php#L205-L231 | train |
younishd/endobox | src/endobox/Box.php | Box.assign | public function assign(array $data) : Box
{
// Allow passing closures as data.
// The trick is to wrap the closure in an anonymous class instance that takes the closure and calls it
// when it is invoked as a string or as a function.
// We only support real closures (i.e., instance of Closure), not just any callable,
// because there is no way to know if "time" is supposed to be data or a function name.
foreach ($data as $k => &$v) {
if ($v instanceof \Closure) {
$data[$k] = new class($v) {
private $closure;
public function __construct($c) { $this->closure = $c; }
public function __toString() { return \call_user_func($this->closure); }
public function __invoke(...$args) { return \call_user_func_array($this->closure, $args); }
};
}
}
$this->data = \array_merge($this->data, $data);
return $this;
} | php | public function assign(array $data) : Box
{
// Allow passing closures as data.
// The trick is to wrap the closure in an anonymous class instance that takes the closure and calls it
// when it is invoked as a string or as a function.
// We only support real closures (i.e., instance of Closure), not just any callable,
// because there is no way to know if "time" is supposed to be data or a function name.
foreach ($data as $k => &$v) {
if ($v instanceof \Closure) {
$data[$k] = new class($v) {
private $closure;
public function __construct($c) { $this->closure = $c; }
public function __toString() { return \call_user_func($this->closure); }
public function __invoke(...$args) { return \call_user_func_array($this->closure, $args); }
};
}
}
$this->data = \array_merge($this->data, $data);
return $this;
} | [
"public",
"function",
"assign",
"(",
"array",
"$",
"data",
")",
":",
"Box",
"{",
"// Allow passing closures as data.",
"// The trick is to wrap the closure in an anonymous class instance that takes the closure and calls it",
"// when it is invoked as a string or as a function.",
"// We o... | Assign some data to this Box. | [
"Assign",
"some",
"data",
"to",
"this",
"Box",
"."
] | a4b9e6aaf954c53c29d4c4e2c1d7a4f8528d0d69 | https://github.com/younishd/endobox/blob/a4b9e6aaf954c53c29d4c4e2c1d7a4f8528d0d69/src/endobox/Box.php#L236-L257 | train |
younishd/endobox | src/endobox/Box.php | Box.head | public function head() : Box
{
// keep track of visited boxes for cycle detection
$touched = [];
for ($b = $this; $b->prev !== null; $b = $b->visit($touched)->prev);
return $b;
} | php | public function head() : Box
{
// keep track of visited boxes for cycle detection
$touched = [];
for ($b = $this; $b->prev !== null; $b = $b->visit($touched)->prev);
return $b;
} | [
"public",
"function",
"head",
"(",
")",
":",
"Box",
"{",
"// keep track of visited boxes for cycle detection",
"$",
"touched",
"=",
"[",
"]",
";",
"for",
"(",
"$",
"b",
"=",
"$",
"this",
";",
"$",
"b",
"->",
"prev",
"!==",
"null",
";",
"$",
"b",
"=",
... | Return the head of the list. | [
"Return",
"the",
"head",
"of",
"the",
"list",
"."
] | a4b9e6aaf954c53c29d4c4e2c1d7a4f8528d0d69 | https://github.com/younishd/endobox/blob/a4b9e6aaf954c53c29d4c4e2c1d7a4f8528d0d69/src/endobox/Box.php#L278-L284 | train |
younishd/endobox | src/endobox/Box.php | Box.tail | public function tail() : Box
{
// keep track of visited boxes for cycle detection
$touched = [];
for ($b = $this; $b->next !== null; $b = $b->visit($touched)->next);
return $b;
} | php | public function tail() : Box
{
// keep track of visited boxes for cycle detection
$touched = [];
for ($b = $this; $b->next !== null; $b = $b->visit($touched)->next);
return $b;
} | [
"public",
"function",
"tail",
"(",
")",
":",
"Box",
"{",
"// keep track of visited boxes for cycle detection",
"$",
"touched",
"=",
"[",
"]",
";",
"for",
"(",
"$",
"b",
"=",
"$",
"this",
";",
"$",
"b",
"->",
"next",
"!==",
"null",
";",
"$",
"b",
"=",
... | Return the tail of the list. | [
"Return",
"the",
"tail",
"of",
"the",
"list",
"."
] | a4b9e6aaf954c53c29d4c4e2c1d7a4f8528d0d69 | https://github.com/younishd/endobox/blob/a4b9e6aaf954c53c29d4c4e2c1d7a4f8528d0d69/src/endobox/Box.php#L289-L295 | train |
younishd/endobox | src/endobox/Box.php | Box.find | private function find() : Box
{
// path compression
if ($this->parent !== $this) {
$this->parent = $this->parent->find();
}
return $this->parent;
} | php | private function find() : Box
{
// path compression
if ($this->parent !== $this) {
$this->parent = $this->parent->find();
}
return $this->parent;
} | [
"private",
"function",
"find",
"(",
")",
":",
"Box",
"{",
"// path compression",
"if",
"(",
"$",
"this",
"->",
"parent",
"!==",
"$",
"this",
")",
"{",
"$",
"this",
"->",
"parent",
"=",
"$",
"this",
"->",
"parent",
"->",
"find",
"(",
")",
";",
"}",
... | Find with path compression. | [
"Find",
"with",
"path",
"compression",
"."
] | a4b9e6aaf954c53c29d4c4e2c1d7a4f8528d0d69 | https://github.com/younishd/endobox/blob/a4b9e6aaf954c53c29d4c4e2c1d7a4f8528d0d69/src/endobox/Box.php#L308-L315 | train |
younishd/endobox | src/endobox/Box.php | Box.visit | private function visit(&$touched)
{
$key = \spl_object_hash($this);
if (isset($touched[$key])) {
throw new \RuntimeException("Cycle (endless loop) detected in box graph.");
}
$touched[$key] = true;
// just for convenience
return $this;
} | php | private function visit(&$touched)
{
$key = \spl_object_hash($this);
if (isset($touched[$key])) {
throw new \RuntimeException("Cycle (endless loop) detected in box graph.");
}
$touched[$key] = true;
// just for convenience
return $this;
} | [
"private",
"function",
"visit",
"(",
"&",
"$",
"touched",
")",
"{",
"$",
"key",
"=",
"\\",
"spl_object_hash",
"(",
"$",
"this",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"touched",
"[",
"$",
"key",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"Runtime... | Mark this box as visited or throw a RuntimeException if we have detected a cycle in the graph. | [
"Mark",
"this",
"box",
"as",
"visited",
"or",
"throw",
"a",
"RuntimeException",
"if",
"we",
"have",
"detected",
"a",
"cycle",
"in",
"the",
"graph",
"."
] | a4b9e6aaf954c53c29d4c4e2c1d7a4f8528d0d69 | https://github.com/younishd/endobox/blob/a4b9e6aaf954c53c29d4c4e2c1d7a4f8528d0d69/src/endobox/Box.php#L320-L329 | train |
younishd/endobox | src/endobox/BoxFactory.php | BoxFactory.create | public function create(string $template) : Box
{
foreach ($this->paths as &$path) {
// full path to template file without extension
$file = \rtrim($path, '/') . '/' . \trim($template, '/');
if (\file_exists($t = $file . '.php')) {
return (new Box(
new Template($t),
new EvalRendererDecorator(
new NullRenderer())))
->assign([
'markdown' => function($md) {
return new Box(
new Atom($md),
new MarkdownRendererDecorator(
new NullRenderer(), $this->parsedown));
}
]);
}
if (\file_exists($t = $file . '.md.php')) {
return (new Box(
new Template($t),
new MarkdownRendererDecorator(
new EvalRendererDecorator(
new NullRenderer()), $this->parsedown)))
->assign([
'markdown' => function($md) {
return new Box(
new Atom($md),
new MarkdownRendererDecorator(
new NullRenderer(), $this->parsedown));
}
]);
}
if (\file_exists($t = $file . '.md')) {
return new Box(
new Template($t),
new MarkdownRendererDecorator(
new NullRenderer(), $this->parsedown));
}
if (\file_exists($t = $file . '.html')) {
return new Box(
new Template($t),
new NullRenderer());
}
}
throw new \RuntimeException(\sprintf('Template "%s" not found.', $template));
} | php | public function create(string $template) : Box
{
foreach ($this->paths as &$path) {
// full path to template file without extension
$file = \rtrim($path, '/') . '/' . \trim($template, '/');
if (\file_exists($t = $file . '.php')) {
return (new Box(
new Template($t),
new EvalRendererDecorator(
new NullRenderer())))
->assign([
'markdown' => function($md) {
return new Box(
new Atom($md),
new MarkdownRendererDecorator(
new NullRenderer(), $this->parsedown));
}
]);
}
if (\file_exists($t = $file . '.md.php')) {
return (new Box(
new Template($t),
new MarkdownRendererDecorator(
new EvalRendererDecorator(
new NullRenderer()), $this->parsedown)))
->assign([
'markdown' => function($md) {
return new Box(
new Atom($md),
new MarkdownRendererDecorator(
new NullRenderer(), $this->parsedown));
}
]);
}
if (\file_exists($t = $file . '.md')) {
return new Box(
new Template($t),
new MarkdownRendererDecorator(
new NullRenderer(), $this->parsedown));
}
if (\file_exists($t = $file . '.html')) {
return new Box(
new Template($t),
new NullRenderer());
}
}
throw new \RuntimeException(\sprintf('Template "%s" not found.', $template));
} | [
"public",
"function",
"create",
"(",
"string",
"$",
"template",
")",
":",
"Box",
"{",
"foreach",
"(",
"$",
"this",
"->",
"paths",
"as",
"&",
"$",
"path",
")",
"{",
"// full path to template file without extension",
"$",
"file",
"=",
"\\",
"rtrim",
"(",
"$"... | Create a Box based on the given template and return it. | [
"Create",
"a",
"Box",
"based",
"on",
"the",
"given",
"template",
"and",
"return",
"it",
"."
] | a4b9e6aaf954c53c29d4c4e2c1d7a4f8528d0d69 | https://github.com/younishd/endobox/blob/a4b9e6aaf954c53c29d4c4e2c1d7a4f8528d0d69/src/endobox/BoxFactory.php#L44-L96 | train |
younishd/endobox | src/endobox/BoxFactory.php | BoxFactory.addFolder | public function addFolder(string $path)
{
if (!\is_dir($path)) {
throw new \RuntimeException(\sprintf('The path "%s" does not exist or is not a directory.', $path));
}
$this->paths[] = $path;
} | php | public function addFolder(string $path)
{
if (!\is_dir($path)) {
throw new \RuntimeException(\sprintf('The path "%s" does not exist or is not a directory.', $path));
}
$this->paths[] = $path;
} | [
"public",
"function",
"addFolder",
"(",
"string",
"$",
"path",
")",
"{",
"if",
"(",
"!",
"\\",
"is_dir",
"(",
"$",
"path",
")",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"\\",
"sprintf",
"(",
"'The path \"%s\" does not exist or is not a director... | Add another folder to the list of template paths. | [
"Add",
"another",
"folder",
"to",
"the",
"list",
"of",
"template",
"paths",
"."
] | a4b9e6aaf954c53c29d4c4e2c1d7a4f8528d0d69 | https://github.com/younishd/endobox/blob/a4b9e6aaf954c53c29d4c4e2c1d7a4f8528d0d69/src/endobox/BoxFactory.php#L101-L107 | train |
gpslab/cqrs | src/Command/Queue/Pull/PredisUniquePullCommandQueue.php | PredisUniquePullCommandQueue.pull | public function pull()
{
$value = $this->client->lpop($this->queue_name);
if (!$value) {
return null;
}
try {
return $this->serializer->deserialize($value);
} catch (\Exception $e) {
// it's a critical error
// it is necessary to react quickly to it
$this->logger->critical('Failed denormalize a command in the Redis queue', [$value, $e->getMessage()]);
// try denormalize in later
$this->client->rpush($this->queue_name, [$value]);
return null;
}
} | php | public function pull()
{
$value = $this->client->lpop($this->queue_name);
if (!$value) {
return null;
}
try {
return $this->serializer->deserialize($value);
} catch (\Exception $e) {
// it's a critical error
// it is necessary to react quickly to it
$this->logger->critical('Failed denormalize a command in the Redis queue', [$value, $e->getMessage()]);
// try denormalize in later
$this->client->rpush($this->queue_name, [$value]);
return null;
}
} | [
"public",
"function",
"pull",
"(",
")",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"client",
"->",
"lpop",
"(",
"$",
"this",
"->",
"queue_name",
")",
";",
"if",
"(",
"!",
"$",
"value",
")",
"{",
"return",
"null",
";",
"}",
"try",
"{",
"return",
... | Pop command from queue. Return NULL if queue is empty.
@return Command|null | [
"Pop",
"command",
"from",
"queue",
".",
"Return",
"NULL",
"if",
"queue",
"is",
"empty",
"."
] | e0544181aeb5d0d3334a51a1189eaaad5fa3c33b | https://github.com/gpslab/cqrs/blob/e0544181aeb5d0d3334a51a1189eaaad5fa3c33b/src/Command/Queue/Pull/PredisUniquePullCommandQueue.php#L76-L96 | train |
younishd/endobox | src/endobox/MarkdownRendererDecorator.php | MarkdownRendererDecorator.render | public function render(Renderable $input, array &$data = null, array $shared = null) : string
{
return $this->parsedown->text(parent::render($input, $data, $shared));
} | php | public function render(Renderable $input, array &$data = null, array $shared = null) : string
{
return $this->parsedown->text(parent::render($input, $data, $shared));
} | [
"public",
"function",
"render",
"(",
"Renderable",
"$",
"input",
",",
"array",
"&",
"$",
"data",
"=",
"null",
",",
"array",
"$",
"shared",
"=",
"null",
")",
":",
"string",
"{",
"return",
"$",
"this",
"->",
"parsedown",
"->",
"text",
"(",
"parent",
":... | Render by passing the inherited result through Parsedown. | [
"Render",
"by",
"passing",
"the",
"inherited",
"result",
"through",
"Parsedown",
"."
] | a4b9e6aaf954c53c29d4c4e2c1d7a4f8528d0d69 | https://github.com/younishd/endobox/blob/a4b9e6aaf954c53c29d4c4e2c1d7a4f8528d0d69/src/endobox/MarkdownRendererDecorator.php#L31-L34 | train |
Rican7/incoming | src/Incoming/Structure/FixedList.php | FixedList.fromArray | public static function fromArray(array $data): self
{
$fixed_list = new static();
$fixed_list->decorated = SplFixedArray::fromArray($data, false);
return $fixed_list;
} | php | public static function fromArray(array $data): self
{
$fixed_list = new static();
$fixed_list->decorated = SplFixedArray::fromArray($data, false);
return $fixed_list;
} | [
"public",
"static",
"function",
"fromArray",
"(",
"array",
"$",
"data",
")",
":",
"self",
"{",
"$",
"fixed_list",
"=",
"new",
"static",
"(",
")",
";",
"$",
"fixed_list",
"->",
"decorated",
"=",
"SplFixedArray",
"::",
"fromArray",
"(",
"$",
"data",
",",
... | Create from data in an array.
@param array $data The data to create from.
@return static The resulting data-structure. | [
"Create",
"from",
"data",
"in",
"an",
"array",
"."
] | 23d5179f994980d56dd32ae056498dc91e72c1f7 | https://github.com/Rican7/incoming/blob/23d5179f994980d56dd32ae056498dc91e72c1f7/src/Incoming/Structure/FixedList.php#L59-L66 | train |
Rican7/incoming | src/Incoming/Structure/FixedList.php | FixedList.get | public function get(int $index, $default_val = null)
{
if ($this->offsetExists($index)) {
return $this->offsetGet($index);
}
return $default_val;
} | php | public function get(int $index, $default_val = null)
{
if ($this->offsetExists($index)) {
return $this->offsetGet($index);
}
return $default_val;
} | [
"public",
"function",
"get",
"(",
"int",
"$",
"index",
",",
"$",
"default_val",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"offsetExists",
"(",
"$",
"index",
")",
")",
"{",
"return",
"$",
"this",
"->",
"offsetGet",
"(",
"$",
"index",
")",... | Get a value in the list by index.
@param int $index The index to get the value for.
@param mixed $default_val The default value to return if the index does
not exist.
@return mixed The resulting value. | [
"Get",
"a",
"value",
"in",
"the",
"list",
"by",
"index",
"."
] | 23d5179f994980d56dd32ae056498dc91e72c1f7 | https://github.com/Rican7/incoming/blob/23d5179f994980d56dd32ae056498dc91e72c1f7/src/Incoming/Structure/FixedList.php#L100-L107 | train |
Rican7/incoming | src/Incoming/Structure/Exception/InvalidStructuralTypeException.php | InvalidStructuralTypeException.withTypeInfo | public static function withTypeInfo($value, int $code = 0, Throwable $previous = null): self
{
$message = self::DEFAULT_MESSAGE;
$message .= sprintf(
self::MESSAGE_EXTENSION_TYPE_FORMAT,
is_object($value) ? get_class($value) : gettype($value)
);
return new static($message, $code, $previous);
} | php | public static function withTypeInfo($value, int $code = 0, Throwable $previous = null): self
{
$message = self::DEFAULT_MESSAGE;
$message .= sprintf(
self::MESSAGE_EXTENSION_TYPE_FORMAT,
is_object($value) ? get_class($value) : gettype($value)
);
return new static($message, $code, $previous);
} | [
"public",
"static",
"function",
"withTypeInfo",
"(",
"$",
"value",
",",
"int",
"$",
"code",
"=",
"0",
",",
"Throwable",
"$",
"previous",
"=",
"null",
")",
":",
"self",
"{",
"$",
"message",
"=",
"self",
"::",
"DEFAULT_MESSAGE",
";",
"$",
"message",
".="... | Create an exception instance with type information.
The type is automatically inspected based on the passed value.
@param mixed $value The value to inspect type information of.
@param int $code The exception code.
@param Throwable|null $previous A previous exception used for chaining.
@return static The newly created exception. | [
"Create",
"an",
"exception",
"instance",
"with",
"type",
"information",
"."
] | 23d5179f994980d56dd32ae056498dc91e72c1f7 | https://github.com/Rican7/incoming/blob/23d5179f994980d56dd32ae056498dc91e72c1f7/src/Incoming/Structure/Exception/InvalidStructuralTypeException.php#L70-L80 | train |
Rican7/incoming | src/Incoming/Structure/Map.php | Map.fromTraversable | public static function fromTraversable(Traversable $data): self
{
$map = new static();
foreach ($data as $key => $val) {
if (!is_scalar($key)) {
throw new InvalidArgumentException('Map keys must be scalar');
}
$map->decorated->offsetSet($key, $val);
}
return $map;
} | php | public static function fromTraversable(Traversable $data): self
{
$map = new static();
foreach ($data as $key => $val) {
if (!is_scalar($key)) {
throw new InvalidArgumentException('Map keys must be scalar');
}
$map->decorated->offsetSet($key, $val);
}
return $map;
} | [
"public",
"static",
"function",
"fromTraversable",
"(",
"Traversable",
"$",
"data",
")",
":",
"self",
"{",
"$",
"map",
"=",
"new",
"static",
"(",
")",
";",
"foreach",
"(",
"$",
"data",
"as",
"$",
"key",
"=>",
"$",
"val",
")",
"{",
"if",
"(",
"!",
... | Create from data in a Traversable instance.
@param Traversable $data The data to create from.
@return static The resulting data-structure.
@throws InvalidArgumentException If the data contains non-scalar keys. | [
"Create",
"from",
"data",
"in",
"a",
"Traversable",
"instance",
"."
] | 23d5179f994980d56dd32ae056498dc91e72c1f7 | https://github.com/Rican7/incoming/blob/23d5179f994980d56dd32ae056498dc91e72c1f7/src/Incoming/Structure/Map.php#L60-L73 | train |
Rican7/incoming | src/Incoming/Structure/Map.php | Map.get | public function get($key, $default_val = null)
{
if ($this->exists($key)) {
return $this->offsetGet($key);
}
return $default_val;
} | php | public function get($key, $default_val = null)
{
if ($this->exists($key)) {
return $this->offsetGet($key);
}
return $default_val;
} | [
"public",
"function",
"get",
"(",
"$",
"key",
",",
"$",
"default_val",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"exists",
"(",
"$",
"key",
")",
")",
"{",
"return",
"$",
"this",
"->",
"offsetGet",
"(",
"$",
"key",
")",
";",
"}",
"ret... | Get a value in the map by key.
@param mixed $key The key to get the value for.
@param mixed $default_val The default value to return if the key does
not exist.
@return mixed The resulting value. | [
"Get",
"a",
"value",
"in",
"the",
"map",
"by",
"key",
"."
] | 23d5179f994980d56dd32ae056498dc91e72c1f7 | https://github.com/Rican7/incoming/blob/23d5179f994980d56dd32ae056498dc91e72c1f7/src/Incoming/Structure/Map.php#L107-L114 | train |
Rican7/incoming | src/Incoming/Processor.php | Processor.hydrateModel | protected function hydrateModel($input_data, $model, Hydrator $hydrator = null, Map $context = null)
{
$hydrator = $hydrator ?: $this->getHydratorForModel($model);
$this->enforceProcessCompatibility(($hydrator instanceof ContextualHydrator), (null !== $context), $hydrator);
if ($hydrator instanceof ContextualHydrator) {
return $hydrator->hydrate($input_data, $model, $context);
}
return $hydrator->hydrate($input_data, $model);
} | php | protected function hydrateModel($input_data, $model, Hydrator $hydrator = null, Map $context = null)
{
$hydrator = $hydrator ?: $this->getHydratorForModel($model);
$this->enforceProcessCompatibility(($hydrator instanceof ContextualHydrator), (null !== $context), $hydrator);
if ($hydrator instanceof ContextualHydrator) {
return $hydrator->hydrate($input_data, $model, $context);
}
return $hydrator->hydrate($input_data, $model);
} | [
"protected",
"function",
"hydrateModel",
"(",
"$",
"input_data",
",",
"$",
"model",
",",
"Hydrator",
"$",
"hydrator",
"=",
"null",
",",
"Map",
"$",
"context",
"=",
"null",
")",
"{",
"$",
"hydrator",
"=",
"$",
"hydrator",
"?",
":",
"$",
"this",
"->",
... | Hydrate a model from incoming data.
If a hydrator isn't provided, an attempt will be made to automatically
resolve and build an appropriate hydrator from the provided factory.
@param mixed $input_data The input data.
@param mixed $model The model to hydrate.
@param Hydrator|null $hydrator The hydrator to use.
@param Map|null $context An optional generic key-value map, for providing
contextual values during the process.
@return mixed The hydrated model. | [
"Hydrate",
"a",
"model",
"from",
"incoming",
"data",
"."
] | 23d5179f994980d56dd32ae056498dc91e72c1f7 | https://github.com/Rican7/incoming/blob/23d5179f994980d56dd32ae056498dc91e72c1f7/src/Incoming/Processor.php#L321-L332 | train |
Rican7/incoming | src/Incoming/Processor.php | Processor.buildModel | protected function buildModel($input_data, string $type, Builder $builder = null, Map $context = null)
{
$builder = $builder ?: $this->getBuilderForType($type);
$this->enforceProcessCompatibility(($builder instanceof ContextualBuilder), (null !== $context), $builder);
if ($builder instanceof ContextualBuilder) {
return $builder->build($input_data, $context);
}
return $builder->build($input_data);
} | php | protected function buildModel($input_data, string $type, Builder $builder = null, Map $context = null)
{
$builder = $builder ?: $this->getBuilderForType($type);
$this->enforceProcessCompatibility(($builder instanceof ContextualBuilder), (null !== $context), $builder);
if ($builder instanceof ContextualBuilder) {
return $builder->build($input_data, $context);
}
return $builder->build($input_data);
} | [
"protected",
"function",
"buildModel",
"(",
"$",
"input_data",
",",
"string",
"$",
"type",
",",
"Builder",
"$",
"builder",
"=",
"null",
",",
"Map",
"$",
"context",
"=",
"null",
")",
"{",
"$",
"builder",
"=",
"$",
"builder",
"?",
":",
"$",
"this",
"->... | Build a model from incoming data.
If a builder isn't provided, an attempt will be made to automatically
resolve and build an appropriate builder from the provided factory.
@param mixed $input_data The input data.
@param string $type The type to build.
@param Builder|null $builder The builder to use.
@param Map|null $context An optional generic key-value map, for providing
contextual values during the process.
@return mixed The built model. | [
"Build",
"a",
"model",
"from",
"incoming",
"data",
"."
] | 23d5179f994980d56dd32ae056498dc91e72c1f7 | https://github.com/Rican7/incoming/blob/23d5179f994980d56dd32ae056498dc91e72c1f7/src/Incoming/Processor.php#L347-L358 | train |
Rican7/incoming | src/Incoming/Processor.php | Processor.getHydratorForModel | protected function getHydratorForModel($model): Hydrator
{
if (null === $this->hydrator_factory) {
throw UnresolvableHydratorException::forModel($model);
}
return $this->hydrator_factory->buildForModel($model);
} | php | protected function getHydratorForModel($model): Hydrator
{
if (null === $this->hydrator_factory) {
throw UnresolvableHydratorException::forModel($model);
}
return $this->hydrator_factory->buildForModel($model);
} | [
"protected",
"function",
"getHydratorForModel",
"(",
"$",
"model",
")",
":",
"Hydrator",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"hydrator_factory",
")",
"{",
"throw",
"UnresolvableHydratorException",
"::",
"forModel",
"(",
"$",
"model",
")",
";",
... | Get a Hydrator for a given model.
@param mixed $model The model to get a hydrator for.
@throws UnresolvableHydratorException If a hydrator can't be resolved for
the given model.
@return Hydrator The resulting hydrator. | [
"Get",
"a",
"Hydrator",
"for",
"a",
"given",
"model",
"."
] | 23d5179f994980d56dd32ae056498dc91e72c1f7 | https://github.com/Rican7/incoming/blob/23d5179f994980d56dd32ae056498dc91e72c1f7/src/Incoming/Processor.php#L368-L375 | train |
Rican7/incoming | src/Incoming/Processor.php | Processor.getBuilderForType | protected function getBuilderForType(string $type): Builder
{
if (null === $this->builder_factory) {
throw UnresolvableBuilderException::forType($type);
}
return $this->builder_factory->buildForType($type);
} | php | protected function getBuilderForType(string $type): Builder
{
if (null === $this->builder_factory) {
throw UnresolvableBuilderException::forType($type);
}
return $this->builder_factory->buildForType($type);
} | [
"protected",
"function",
"getBuilderForType",
"(",
"string",
"$",
"type",
")",
":",
"Builder",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"builder_factory",
")",
"{",
"throw",
"UnresolvableBuilderException",
"::",
"forType",
"(",
"$",
"type",
")",
";"... | Get a Builder for a given model.
@param string $type The type to get a builder for.
@throws UnresolvableBuilderException If a builder can't be resolved for
the given model.
@return Builder The resulting builder. | [
"Get",
"a",
"Builder",
"for",
"a",
"given",
"model",
"."
] | 23d5179f994980d56dd32ae056498dc91e72c1f7 | https://github.com/Rican7/incoming/blob/23d5179f994980d56dd32ae056498dc91e72c1f7/src/Incoming/Processor.php#L385-L392 | train |
Rican7/incoming | src/Incoming/Hydrator/Exception/UnresolvableBuilderException.php | UnresolvableBuilderException.forType | public static function forType(
string $type,
int $code = self::CODE_FOR_TYPE,
Throwable $previous = null
): self {
$message = self::DEFAULT_MESSAGE . sprintf(self::MESSAGE_EXTENSION_FOR_TYPE, $type);
return new static($message, $code, $previous);
} | php | public static function forType(
string $type,
int $code = self::CODE_FOR_TYPE,
Throwable $previous = null
): self {
$message = self::DEFAULT_MESSAGE . sprintf(self::MESSAGE_EXTENSION_FOR_TYPE, $type);
return new static($message, $code, $previous);
} | [
"public",
"static",
"function",
"forType",
"(",
"string",
"$",
"type",
",",
"int",
"$",
"code",
"=",
"self",
"::",
"CODE_FOR_TYPE",
",",
"Throwable",
"$",
"previous",
"=",
"null",
")",
":",
"self",
"{",
"$",
"message",
"=",
"self",
"::",
"DEFAULT_MESSAGE... | Create an exception instance for a problem resolving a builder for a
given type.
@param string $type The type to build.
@param int $code The exception code.
@param Throwable|null $previous A previous exception used for chaining.
@return static The newly created exception. | [
"Create",
"an",
"exception",
"instance",
"for",
"a",
"problem",
"resolving",
"a",
"builder",
"for",
"a",
"given",
"type",
"."
] | 23d5179f994980d56dd32ae056498dc91e72c1f7 | https://github.com/Rican7/incoming/blob/23d5179f994980d56dd32ae056498dc91e72c1f7/src/Incoming/Hydrator/Exception/UnresolvableBuilderException.php#L77-L85 | train |
Rican7/incoming | src/Incoming/Structure/RecursiveInputStructureFactory.php | RecursiveInputStructureFactory.buildFromTraversableLike | protected static function buildFromTraversableLike($data): Structure
{
if (is_array($data)) {
return static::buildFromArray($data);
} elseif ($data instanceof Traversable) {
return static::buildFromTraversable($data);
}
throw InvalidStructuralTypeException::withTypeInfo($data);
} | php | protected static function buildFromTraversableLike($data): Structure
{
if (is_array($data)) {
return static::buildFromArray($data);
} elseif ($data instanceof Traversable) {
return static::buildFromTraversable($data);
}
throw InvalidStructuralTypeException::withTypeInfo($data);
} | [
"protected",
"static",
"function",
"buildFromTraversableLike",
"(",
"$",
"data",
")",
":",
"Structure",
"{",
"if",
"(",
"is_array",
"(",
"$",
"data",
")",
")",
"{",
"return",
"static",
"::",
"buildFromArray",
"(",
"$",
"data",
")",
";",
"}",
"elseif",
"(... | Build a structure from "Traversable-like" data.
This allows to build from data that is either an array or Traversable, as
PHP's array type works JUST like a Traversable instance but doesn't
actually implement any interfaces.
@param Traversable|array $data The input data.
@throws InvalidStructuralTypeException If the data type isn't supported.
@return Structure The built structure. | [
"Build",
"a",
"structure",
"from",
"Traversable",
"-",
"like",
"data",
"."
] | 23d5179f994980d56dd32ae056498dc91e72c1f7 | https://github.com/Rican7/incoming/blob/23d5179f994980d56dd32ae056498dc91e72c1f7/src/Incoming/Structure/RecursiveInputStructureFactory.php#L48-L57 | train |
Rican7/incoming | src/Incoming/Structure/RecursiveInputStructureFactory.php | RecursiveInputStructureFactory.buildFromTraversable | protected static function buildFromTraversable(Traversable $data): Structure
{
$is_map = false;
// Traverse through the data, but only check the first item's key
foreach ($data as $key => &$val) {
$is_map = $is_map || !is_int($key);
$val = self::attemptBuildTraversableLike($val);
}
if ($is_map) {
return Map::fromTraversable($data);
}
return FixedList::fromTraversable($data);
} | php | protected static function buildFromTraversable(Traversable $data): Structure
{
$is_map = false;
// Traverse through the data, but only check the first item's key
foreach ($data as $key => &$val) {
$is_map = $is_map || !is_int($key);
$val = self::attemptBuildTraversableLike($val);
}
if ($is_map) {
return Map::fromTraversable($data);
}
return FixedList::fromTraversable($data);
} | [
"protected",
"static",
"function",
"buildFromTraversable",
"(",
"Traversable",
"$",
"data",
")",
":",
"Structure",
"{",
"$",
"is_map",
"=",
"false",
";",
"// Traverse through the data, but only check the first item's key",
"foreach",
"(",
"$",
"data",
"as",
"$",
"key"... | Build a structure from data in a Traversable instance.
@param Traversable $data The input data.
@return Structure The built structure. | [
"Build",
"a",
"structure",
"from",
"data",
"in",
"a",
"Traversable",
"instance",
"."
] | 23d5179f994980d56dd32ae056498dc91e72c1f7 | https://github.com/Rican7/incoming/blob/23d5179f994980d56dd32ae056498dc91e72c1f7/src/Incoming/Structure/RecursiveInputStructureFactory.php#L78-L94 | train |
Rican7/incoming | src/Incoming/Structure/RecursiveInputStructureFactory.php | RecursiveInputStructureFactory.attemptBuildTraversableLike | private static function attemptBuildTraversableLike($data)
{
if (is_array($data) || $data instanceof Traversable) {
$data = static::buildFromTraversableLike($data);
}
return $data;
} | php | private static function attemptBuildTraversableLike($data)
{
if (is_array($data) || $data instanceof Traversable) {
$data = static::buildFromTraversableLike($data);
}
return $data;
} | [
"private",
"static",
"function",
"attemptBuildTraversableLike",
"(",
"$",
"data",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"data",
")",
"||",
"$",
"data",
"instanceof",
"Traversable",
")",
"{",
"$",
"data",
"=",
"static",
"::",
"buildFromTraversableLike",
... | Attempt to build a structure from "Traversable-like" data.
If the data type isn't supported, we simply return the original data
untouched. This allows to more easily traverse deeply nested structures.
@param mixed $data The input data.
@return Structure|mixed The built structure or original data. | [
"Attempt",
"to",
"build",
"a",
"structure",
"from",
"Traversable",
"-",
"like",
"data",
"."
] | 23d5179f994980d56dd32ae056498dc91e72c1f7 | https://github.com/Rican7/incoming/blob/23d5179f994980d56dd32ae056498dc91e72c1f7/src/Incoming/Structure/RecursiveInputStructureFactory.php#L105-L112 | train |
Rican7/incoming | src/Incoming/Structure/Exception/ReadOnlyException.php | ReadOnlyException.forAttribute | public static function forAttribute(
$name,
$value = null,
int $code = self::CODE_FOR_ATTRIBUTE,
Throwable $previous = null
): self {
$message = self::DEFAULT_MESSAGE;
if (null !== $value) {
$message .= sprintf(
self::MESSAGE_EXTENSION_FOR_ATTRIBUTE_FORMAT . self::MESSAGE_EXTENSION_FOR_ATTRIBUTE_WITH_VALUE_FORMAT,
$name,
var_export($value, true)
);
} else {
$message .= sprintf(
self::MESSAGE_EXTENSION_FOR_ATTRIBUTE_FORMAT,
$name
);
}
return new static($message, $code, $previous);
} | php | public static function forAttribute(
$name,
$value = null,
int $code = self::CODE_FOR_ATTRIBUTE,
Throwable $previous = null
): self {
$message = self::DEFAULT_MESSAGE;
if (null !== $value) {
$message .= sprintf(
self::MESSAGE_EXTENSION_FOR_ATTRIBUTE_FORMAT . self::MESSAGE_EXTENSION_FOR_ATTRIBUTE_WITH_VALUE_FORMAT,
$name,
var_export($value, true)
);
} else {
$message .= sprintf(
self::MESSAGE_EXTENSION_FOR_ATTRIBUTE_FORMAT,
$name
);
}
return new static($message, $code, $previous);
} | [
"public",
"static",
"function",
"forAttribute",
"(",
"$",
"name",
",",
"$",
"value",
"=",
"null",
",",
"int",
"$",
"code",
"=",
"self",
"::",
"CODE_FOR_ATTRIBUTE",
",",
"Throwable",
"$",
"previous",
"=",
"null",
")",
":",
"self",
"{",
"$",
"message",
"... | Create an exception instance with an attribute's context.
@param mixed $name The name of the attribute attempted to be modified.
@param mixed|null $value The value attempted to be set.
@param int $code The exception code.
@param Throwable|null $previous A previous exception used for chaining.
@return static The newly created exception. | [
"Create",
"an",
"exception",
"instance",
"with",
"an",
"attribute",
"s",
"context",
"."
] | 23d5179f994980d56dd32ae056498dc91e72c1f7 | https://github.com/Rican7/incoming/blob/23d5179f994980d56dd32ae056498dc91e72c1f7/src/Incoming/Structure/Exception/ReadOnlyException.php#L84-L106 | train |
Rican7/incoming | src/Incoming/Hydrator/Exception/InvalidDelegateException.php | InvalidDelegateException.forNonCallable | public static function forNonCallable(
string $name = null,
int $code = self::CODE_FOR_NON_CALLABLE,
Throwable $previous = null
): self {
$message = self::DEFAULT_MESSAGE;
if (null !== $name) {
$message .= sprintf(
self::MESSAGE_EXTENSION_NAME_FORMAT,
$name
);
}
$message .= self::MESSAGE_EXTENSION_FOR_NON_CALLABLE;
return new static($message, $code, $previous);
} | php | public static function forNonCallable(
string $name = null,
int $code = self::CODE_FOR_NON_CALLABLE,
Throwable $previous = null
): self {
$message = self::DEFAULT_MESSAGE;
if (null !== $name) {
$message .= sprintf(
self::MESSAGE_EXTENSION_NAME_FORMAT,
$name
);
}
$message .= self::MESSAGE_EXTENSION_FOR_NON_CALLABLE;
return new static($message, $code, $previous);
} | [
"public",
"static",
"function",
"forNonCallable",
"(",
"string",
"$",
"name",
"=",
"null",
",",
"int",
"$",
"code",
"=",
"self",
"::",
"CODE_FOR_NON_CALLABLE",
",",
"Throwable",
"$",
"previous",
"=",
"null",
")",
":",
"self",
"{",
"$",
"message",
"=",
"s... | Create an exception instance for a delegate that isn't callable.
@param string|null $name The name of the delegate.
@param int $code The exception code.
@param Throwable|null $previous A previous exception used for chaining.
@return static The newly created exception. | [
"Create",
"an",
"exception",
"instance",
"for",
"a",
"delegate",
"that",
"isn",
"t",
"callable",
"."
] | 23d5179f994980d56dd32ae056498dc91e72c1f7 | https://github.com/Rican7/incoming/blob/23d5179f994980d56dd32ae056498dc91e72c1f7/src/Incoming/Hydrator/Exception/InvalidDelegateException.php#L82-L99 | train |
Rican7/incoming | src/Incoming/Hydrator/AbstractDelegateBuilderHydrator.php | AbstractDelegateBuilderHydrator.getDelegateHydrator | protected function getDelegateHydrator(): callable
{
$delegate = [$this, static::DEFAULT_DELEGATE_HYDRATE_METHOD_NAME];
if (!is_callable($delegate, false, $callable_name)) {
throw InvalidDelegateException::forNonCallable($callable_name);
}
return $delegate;
} | php | protected function getDelegateHydrator(): callable
{
$delegate = [$this, static::DEFAULT_DELEGATE_HYDRATE_METHOD_NAME];
if (!is_callable($delegate, false, $callable_name)) {
throw InvalidDelegateException::forNonCallable($callable_name);
}
return $delegate;
} | [
"protected",
"function",
"getDelegateHydrator",
"(",
")",
":",
"callable",
"{",
"$",
"delegate",
"=",
"[",
"$",
"this",
",",
"static",
"::",
"DEFAULT_DELEGATE_HYDRATE_METHOD_NAME",
"]",
";",
"if",
"(",
"!",
"is_callable",
"(",
"$",
"delegate",
",",
"false",
... | Get the delegate hydration callable.
Override this method if a custom delegate is desired.
@return callable The delegate hydrator callable.
@throws InvalidDelegateException If the delegate isn't callable. | [
"Get",
"the",
"delegate",
"hydration",
"callable",
"."
] | 23d5179f994980d56dd32ae056498dc91e72c1f7 | https://github.com/Rican7/incoming/blob/23d5179f994980d56dd32ae056498dc91e72c1f7/src/Incoming/Hydrator/AbstractDelegateBuilderHydrator.php#L105-L114 | train |
Rican7/incoming | src/Incoming/Hydrator/Exception/UnresolvableHydratorException.php | UnresolvableHydratorException.forModel | public static function forModel(
$model,
int $code = self::CODE_FOR_MODEL,
Throwable $previous = null
): self {
$message = self::DEFAULT_MESSAGE . self::MESSAGE_EXTENSION_FOR_MODEL;
$message .= sprintf(
self::MESSAGE_EXTENSION_TYPE_FORMAT,
is_object($model) ? get_class($model) : gettype($model)
);
return new static($message, $code, $previous);
} | php | public static function forModel(
$model,
int $code = self::CODE_FOR_MODEL,
Throwable $previous = null
): self {
$message = self::DEFAULT_MESSAGE . self::MESSAGE_EXTENSION_FOR_MODEL;
$message .= sprintf(
self::MESSAGE_EXTENSION_TYPE_FORMAT,
is_object($model) ? get_class($model) : gettype($model)
);
return new static($message, $code, $previous);
} | [
"public",
"static",
"function",
"forModel",
"(",
"$",
"model",
",",
"int",
"$",
"code",
"=",
"self",
"::",
"CODE_FOR_MODEL",
",",
"Throwable",
"$",
"previous",
"=",
"null",
")",
":",
"self",
"{",
"$",
"message",
"=",
"self",
"::",
"DEFAULT_MESSAGE",
".",... | Create an exception instance for a problem resolving a hydrator for a
given model.
@param mixed $model The model to hydrate.
@param int $code The exception code.
@param Throwable|null $previous A previous exception used for chaining.
@return static The newly created exception. | [
"Create",
"an",
"exception",
"instance",
"for",
"a",
"problem",
"resolving",
"a",
"hydrator",
"for",
"a",
"given",
"model",
"."
] | 23d5179f994980d56dd32ae056498dc91e72c1f7 | https://github.com/Rican7/incoming/blob/23d5179f994980d56dd32ae056498dc91e72c1f7/src/Incoming/Hydrator/Exception/UnresolvableHydratorException.php#L84-L97 | train |
XetaIO/Xetaravel-Mentions | src/Parser/MentionParser.php | MentionParser.parse | public function parse($input)
{
if (is_null($input) || empty($input)) {
return $input;
}
$character = $this->getOption('character');
$regex = strtr($this->getOption('regex'), $this->getOption('regex_replacement'));
preg_match_all($regex, $input, $matches);
$matches = array_map([$this, 'mapper'], $matches[0]);
$matches = $this->removeNullKeys($matches);
$matches = $this->prepareArray($matches);
$output = preg_replace_callback($matches, [$this, 'replace'], $input);
return $output;
} | php | public function parse($input)
{
if (is_null($input) || empty($input)) {
return $input;
}
$character = $this->getOption('character');
$regex = strtr($this->getOption('regex'), $this->getOption('regex_replacement'));
preg_match_all($regex, $input, $matches);
$matches = array_map([$this, 'mapper'], $matches[0]);
$matches = $this->removeNullKeys($matches);
$matches = $this->prepareArray($matches);
$output = preg_replace_callback($matches, [$this, 'replace'], $input);
return $output;
} | [
"public",
"function",
"parse",
"(",
"$",
"input",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"input",
")",
"||",
"empty",
"(",
"$",
"input",
")",
")",
"{",
"return",
"$",
"input",
";",
"}",
"$",
"character",
"=",
"$",
"this",
"->",
"getOption",
"(... | Parse a text and determine if it contains mentions. If it does,
then we transform the mentions to a markdown link and we notify the user.
@param null|string $input The string to parse.
@return null|string | [
"Parse",
"a",
"text",
"and",
"determine",
"if",
"it",
"contains",
"mentions",
".",
"If",
"it",
"does",
"then",
"we",
"transform",
"the",
"mentions",
"to",
"a",
"markdown",
"link",
"and",
"we",
"notify",
"the",
"user",
"."
] | 7e0505fdafc76c310824cfd24f62c18aa5029358 | https://github.com/XetaIO/Xetaravel-Mentions/blob/7e0505fdafc76c310824cfd24f62c18aa5029358/src/Parser/MentionParser.php#L58-L76 | train |
XetaIO/Xetaravel-Mentions | src/Parser/MentionParser.php | MentionParser.replace | protected function replace(array $match): string
{
$character = $this->getOption('character');
$mention = Str::title(str_replace($character, '', trim($match[0])));
$route = config('mentions.pools.' . $this->getOption('pool') . '.route');
$link = $route . $mention;
return " [{$character}{$mention}]($link)";
} | php | protected function replace(array $match): string
{
$character = $this->getOption('character');
$mention = Str::title(str_replace($character, '', trim($match[0])));
$route = config('mentions.pools.' . $this->getOption('pool') . '.route');
$link = $route . $mention;
return " [{$character}{$mention}]($link)";
} | [
"protected",
"function",
"replace",
"(",
"array",
"$",
"match",
")",
":",
"string",
"{",
"$",
"character",
"=",
"$",
"this",
"->",
"getOption",
"(",
"'character'",
")",
";",
"$",
"mention",
"=",
"Str",
"::",
"title",
"(",
"str_replace",
"(",
"$",
"char... | Replace the mention with a markdown link.
@param array $match The mention to replace.
@return string | [
"Replace",
"the",
"mention",
"with",
"a",
"markdown",
"link",
"."
] | 7e0505fdafc76c310824cfd24f62c18aa5029358 | https://github.com/XetaIO/Xetaravel-Mentions/blob/7e0505fdafc76c310824cfd24f62c18aa5029358/src/Parser/MentionParser.php#L85-L95 | train |
XetaIO/Xetaravel-Mentions | src/Parser/MentionParser.php | MentionParser.mapper | protected function mapper(string $key)
{
$character = $this->getOption('character');
$config = config('mentions.pools.' . $this->getOption('pool'));
$mention = str_replace($character, '', trim($key));
$mentionned = $config['model']::whereRaw("LOWER({$config['column']}) = ?", [Str::lower($mention)])->first();
if ($mentionned == false) {
return null;
}
if ($this->getOption('mention') == true && $mentionned->getKey() !== Auth::id()) {
$this->model->mention($mentionned, $this->getOption('notify'));
}
return '/' . preg_quote($key) . '(?!\w)/';
} | php | protected function mapper(string $key)
{
$character = $this->getOption('character');
$config = config('mentions.pools.' . $this->getOption('pool'));
$mention = str_replace($character, '', trim($key));
$mentionned = $config['model']::whereRaw("LOWER({$config['column']}) = ?", [Str::lower($mention)])->first();
if ($mentionned == false) {
return null;
}
if ($this->getOption('mention') == true && $mentionned->getKey() !== Auth::id()) {
$this->model->mention($mentionned, $this->getOption('notify'));
}
return '/' . preg_quote($key) . '(?!\w)/';
} | [
"protected",
"function",
"mapper",
"(",
"string",
"$",
"key",
")",
"{",
"$",
"character",
"=",
"$",
"this",
"->",
"getOption",
"(",
"'character'",
")",
";",
"$",
"config",
"=",
"config",
"(",
"'mentions.pools.'",
".",
"$",
"this",
"->",
"getOption",
"(",... | Handle a mention and return it has a regex. If you want to delete
this mention from the out array, just return `null`.
@param string $key The mention that has been matched.
@return null|string | [
"Handle",
"a",
"mention",
"and",
"return",
"it",
"has",
"a",
"regex",
".",
"If",
"you",
"want",
"to",
"delete",
"this",
"mention",
"from",
"the",
"out",
"array",
"just",
"return",
"null",
"."
] | 7e0505fdafc76c310824cfd24f62c18aa5029358 | https://github.com/XetaIO/Xetaravel-Mentions/blob/7e0505fdafc76c310824cfd24f62c18aa5029358/src/Parser/MentionParser.php#L139-L157 | train |
Rican7/incoming | src/Incoming/Hydrator/Exception/IncompatibleProcessException.php | IncompatibleProcessException.forRequiredContextCompatibility | public static function forRequiredContextCompatibility(
$process = null,
int $code = self::CODE_FOR_REQUIRED_CONTEXT_COMPATIBILITY,
Throwable $previous = null
): self {
if (self::CODE_FOR_REQUIRED_CONTEXT_COMPATIBILITY === $code) {
if ($process instanceof Hydrator) {
$code += self::CODE_FOR_HYDRATOR;
} elseif ($process instanceof Builder) {
$code += self::CODE_FOR_BUILDER;
}
}
$message = self::DEFAULT_MESSAGE . self::MESSAGE_EXTENSION_FOR_REQUIRED_CONTEXT_COMPATIBILITY;
return new static($message, $code, $previous);
} | php | public static function forRequiredContextCompatibility(
$process = null,
int $code = self::CODE_FOR_REQUIRED_CONTEXT_COMPATIBILITY,
Throwable $previous = null
): self {
if (self::CODE_FOR_REQUIRED_CONTEXT_COMPATIBILITY === $code) {
if ($process instanceof Hydrator) {
$code += self::CODE_FOR_HYDRATOR;
} elseif ($process instanceof Builder) {
$code += self::CODE_FOR_BUILDER;
}
}
$message = self::DEFAULT_MESSAGE . self::MESSAGE_EXTENSION_FOR_REQUIRED_CONTEXT_COMPATIBILITY;
return new static($message, $code, $previous);
} | [
"public",
"static",
"function",
"forRequiredContextCompatibility",
"(",
"$",
"process",
"=",
"null",
",",
"int",
"$",
"code",
"=",
"self",
"::",
"CODE_FOR_REQUIRED_CONTEXT_COMPATIBILITY",
",",
"Throwable",
"$",
"previous",
"=",
"null",
")",
":",
"self",
"{",
"if... | Create an exception instance for when context compatibility is required.
@param object|null $process The incompatible process.
@param int $code The exception code.
@param Throwable|null $previous A previous exception used for chaining.
@return static The newly created exception. | [
"Create",
"an",
"exception",
"instance",
"for",
"when",
"context",
"compatibility",
"is",
"required",
"."
] | 23d5179f994980d56dd32ae056498dc91e72c1f7 | https://github.com/Rican7/incoming/blob/23d5179f994980d56dd32ae056498dc91e72c1f7/src/Incoming/Hydrator/Exception/IncompatibleProcessException.php#L93-L109 | train |
XetaIO/Xetaravel-Mentions | src/Models/Repositories/MentionRepository.php | MentionRepository.create | public static function create(Model $model, Model $recipient, $notify = true): Mention
{
$mention = Mention::firstOrCreate([
'model_type' => get_class($model),
'model_id' => $model->getKey(),
'recipient_type' => get_class($recipient),
'recipient_id' => $recipient->getKey()
]);
if ($notify) {
$mention->notify($model, $recipient);
}
return $mention;
} | php | public static function create(Model $model, Model $recipient, $notify = true): Mention
{
$mention = Mention::firstOrCreate([
'model_type' => get_class($model),
'model_id' => $model->getKey(),
'recipient_type' => get_class($recipient),
'recipient_id' => $recipient->getKey()
]);
if ($notify) {
$mention->notify($model, $recipient);
}
return $mention;
} | [
"public",
"static",
"function",
"create",
"(",
"Model",
"$",
"model",
",",
"Model",
"$",
"recipient",
",",
"$",
"notify",
"=",
"true",
")",
":",
"Mention",
"{",
"$",
"mention",
"=",
"Mention",
"::",
"firstOrCreate",
"(",
"[",
"'model_type'",
"=>",
"get_c... | Creates a new mention.
@return \Xetaio\Mentions\Models\Mention | [
"Creates",
"a",
"new",
"mention",
"."
] | 7e0505fdafc76c310824cfd24f62c18aa5029358 | https://github.com/XetaIO/Xetaravel-Mentions/blob/7e0505fdafc76c310824cfd24f62c18aa5029358/src/Models/Repositories/MentionRepository.php#L27-L41 | train |
tarsana/command | src/Config/Config.php | Config.get | public function get(string $path = null)
{
if (null === $path)
return $this->data;
$keys = explode('.', $path);
$value = $this->data;
foreach ($keys as $key) {
if (!is_array($value) || !array_key_exists($key, $value))
throw new \Exception("Unable to find a configuration value with path '{$path}'");
$value = $value[$key];
}
return $value;
} | php | public function get(string $path = null)
{
if (null === $path)
return $this->data;
$keys = explode('.', $path);
$value = $this->data;
foreach ($keys as $key) {
if (!is_array($value) || !array_key_exists($key, $value))
throw new \Exception("Unable to find a configuration value with path '{$path}'");
$value = $value[$key];
}
return $value;
} | [
"public",
"function",
"get",
"(",
"string",
"$",
"path",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"path",
")",
"return",
"$",
"this",
"->",
"data",
";",
"$",
"keys",
"=",
"explode",
"(",
"'.'",
",",
"$",
"path",
")",
";",
"$",
"val... | Gets a configuration value by path. | [
"Gets",
"a",
"configuration",
"value",
"by",
"path",
"."
] | d439b949140c226a0cc5a30f72fbbe25570b9871 | https://github.com/tarsana/command/blob/d439b949140c226a0cc5a30f72fbbe25570b9871/src/Config/Config.php#L23-L35 | train |
tarsana/command | src/Console/ExceptionPrinter.php | ExceptionPrinter.printParseException | public function printParseException(ParseException $e) : string
{
$syntax = $e->syntax();
$error = '';
if ($syntax instanceof ObjectSyntax) {
$i = $e->extra();
if ($i['type'] == 'invalid-field')
$error = "{$i['field']} is invalid!";
if ($i['type'] == 'missing-field')
$error = "{$i['field']} is missing!";
if ($i['type'] == 'additional-items') {
$items = implode($syntax->separator(), $i['items']);
$error = "additional items {$items}";
}
}
$syntax = $this->printSyntax($e->syntax());
$output = "<reset>Failed to parse <warn>'{$e->input()}'</warn> as <info>{$syntax}</info>";
if ('' != $error)
$output .= " <error>{$error}</error>";
$previous = $e->previous();
if ($previous) {
$output .= '<br>' . $this->printParseException($previous);
}
return $output;
} | php | public function printParseException(ParseException $e) : string
{
$syntax = $e->syntax();
$error = '';
if ($syntax instanceof ObjectSyntax) {
$i = $e->extra();
if ($i['type'] == 'invalid-field')
$error = "{$i['field']} is invalid!";
if ($i['type'] == 'missing-field')
$error = "{$i['field']} is missing!";
if ($i['type'] == 'additional-items') {
$items = implode($syntax->separator(), $i['items']);
$error = "additional items {$items}";
}
}
$syntax = $this->printSyntax($e->syntax());
$output = "<reset>Failed to parse <warn>'{$e->input()}'</warn> as <info>{$syntax}</info>";
if ('' != $error)
$output .= " <error>{$error}</error>";
$previous = $e->previous();
if ($previous) {
$output .= '<br>' . $this->printParseException($previous);
}
return $output;
} | [
"public",
"function",
"printParseException",
"(",
"ParseException",
"$",
"e",
")",
":",
"string",
"{",
"$",
"syntax",
"=",
"$",
"e",
"->",
"syntax",
"(",
")",
";",
"$",
"error",
"=",
"''",
";",
"if",
"(",
"$",
"syntax",
"instanceof",
"ObjectSyntax",
")... | Converts a parse exception to a string.
@param Tarsana\Syntax\Exceptions\ParseException $e
@return string | [
"Converts",
"a",
"parse",
"exception",
"to",
"a",
"string",
"."
] | d439b949140c226a0cc5a30f72fbbe25570b9871 | https://github.com/tarsana/command/blob/d439b949140c226a0cc5a30f72fbbe25570b9871/src/Console/ExceptionPrinter.php#L33-L60 | train |
tarsana/command | src/Template/Twig/TwigTemplate.php | TwigTemplate.bind | public function bind (array $data) : TemplateInterface
{
$this->data = array_merge($this->data, $data);
return $this;
} | php | public function bind (array $data) : TemplateInterface
{
$this->data = array_merge($this->data, $data);
return $this;
} | [
"public",
"function",
"bind",
"(",
"array",
"$",
"data",
")",
":",
"TemplateInterface",
"{",
"$",
"this",
"->",
"data",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"data",
",",
"$",
"data",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Binds data to the template.
@param array $data
@return self | [
"Binds",
"data",
"to",
"the",
"template",
"."
] | d439b949140c226a0cc5a30f72fbbe25570b9871 | https://github.com/tarsana/command/blob/d439b949140c226a0cc5a30f72fbbe25570b9871/src/Template/Twig/TwigTemplate.php#L31-L35 | train |
tarsana/command | src/Command.php | Command.name | public function name(string $value = null)
{
if (null === $value) {
return $this->name;
}
$this->name = $value;
return $this;
} | php | public function name(string $value = null)
{
if (null === $value) {
return $this->name;
}
$this->name = $value;
return $this;
} | [
"public",
"function",
"name",
"(",
"string",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"value",
")",
"{",
"return",
"$",
"this",
"->",
"name",
";",
"}",
"$",
"this",
"->",
"name",
"=",
"$",
"value",
";",
"return",
"$",
... | name getter and setter.
@param string
@return mixed | [
"name",
"getter",
"and",
"setter",
"."
] | d439b949140c226a0cc5a30f72fbbe25570b9871 | https://github.com/tarsana/command/blob/d439b949140c226a0cc5a30f72fbbe25570b9871/src/Command.php#L67-L74 | train |
tarsana/command | src/Command.php | Command.version | public function version(string $value = null)
{
if (null === $value) {
return $this->version;
}
$this->version = $value;
return $this;
} | php | public function version(string $value = null)
{
if (null === $value) {
return $this->version;
}
$this->version = $value;
return $this;
} | [
"public",
"function",
"version",
"(",
"string",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"value",
")",
"{",
"return",
"$",
"this",
"->",
"version",
";",
"}",
"$",
"this",
"->",
"version",
"=",
"$",
"value",
";",
"return",... | version getter and setter.
@param string
@return mixed | [
"version",
"getter",
"and",
"setter",
"."
] | d439b949140c226a0cc5a30f72fbbe25570b9871 | https://github.com/tarsana/command/blob/d439b949140c226a0cc5a30f72fbbe25570b9871/src/Command.php#L82-L89 | train |
tarsana/command | src/Command.php | Command.description | public function description(string $value = null)
{
if (null === $value) {
return $this->description;
}
$this->description = $value;
return $this;
} | php | public function description(string $value = null)
{
if (null === $value) {
return $this->description;
}
$this->description = $value;
return $this;
} | [
"public",
"function",
"description",
"(",
"string",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"value",
")",
"{",
"return",
"$",
"this",
"->",
"description",
";",
"}",
"$",
"this",
"->",
"description",
"=",
"$",
"value",
";",... | description getter and setter.
@param string
@return mixed | [
"description",
"getter",
"and",
"setter",
"."
] | d439b949140c226a0cc5a30f72fbbe25570b9871 | https://github.com/tarsana/command/blob/d439b949140c226a0cc5a30f72fbbe25570b9871/src/Command.php#L97-L104 | train |
tarsana/command | src/Command.php | Command.descriptions | public function descriptions(array $value = null)
{
if (null === $value) {
return $this->descriptions;
}
$this->descriptions = $value;
return $this;
} | php | public function descriptions(array $value = null)
{
if (null === $value) {
return $this->descriptions;
}
$this->descriptions = $value;
return $this;
} | [
"public",
"function",
"descriptions",
"(",
"array",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"value",
")",
"{",
"return",
"$",
"this",
"->",
"descriptions",
";",
"}",
"$",
"this",
"->",
"descriptions",
"=",
"$",
"value",
";... | descriptions getter and setter.
@param string
@return mixed | [
"descriptions",
"getter",
"and",
"setter",
"."
] | d439b949140c226a0cc5a30f72fbbe25570b9871 | https://github.com/tarsana/command/blob/d439b949140c226a0cc5a30f72fbbe25570b9871/src/Command.php#L112-L119 | train |
tarsana/command | src/Command.php | Command.syntax | public function syntax(string $syntax = null)
{
if (null === $syntax)
return $this->syntax;
$this->syntax = S::syntax()->parse("{{$syntax}| }");
return $this;
} | php | public function syntax(string $syntax = null)
{
if (null === $syntax)
return $this->syntax;
$this->syntax = S::syntax()->parse("{{$syntax}| }");
return $this;
} | [
"public",
"function",
"syntax",
"(",
"string",
"$",
"syntax",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"syntax",
")",
"return",
"$",
"this",
"->",
"syntax",
";",
"$",
"this",
"->",
"syntax",
"=",
"S",
"::",
"syntax",
"(",
")",
"->",
... | syntax getter and setter.
@param string|null $syntax
@return Syntax|self | [
"syntax",
"getter",
"and",
"setter",
"."
] | d439b949140c226a0cc5a30f72fbbe25570b9871 | https://github.com/tarsana/command/blob/d439b949140c226a0cc5a30f72fbbe25570b9871/src/Command.php#L127-L134 | train |
tarsana/command | src/Command.php | Command.options | public function options(array $options = null)
{
if (null === $options) {
return $this->options;
}
$this->options = [];
foreach($options as $option)
$this->options[$option] = false;
return $this;
} | php | public function options(array $options = null)
{
if (null === $options) {
return $this->options;
}
$this->options = [];
foreach($options as $option)
$this->options[$option] = false;
return $this;
} | [
"public",
"function",
"options",
"(",
"array",
"$",
"options",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"options",
")",
"{",
"return",
"$",
"this",
"->",
"options",
";",
"}",
"$",
"this",
"->",
"options",
"=",
"[",
"]",
";",
"foreach",... | options getter and setter.
@param array
@return mixed | [
"options",
"getter",
"and",
"setter",
"."
] | d439b949140c226a0cc5a30f72fbbe25570b9871 | https://github.com/tarsana/command/blob/d439b949140c226a0cc5a30f72fbbe25570b9871/src/Command.php#L142-L153 | train |
tarsana/command | src/Command.php | Command.option | public function option(string $name)
{
if (!array_key_exists($name, $this->options))
throw new \InvalidArgumentException("Unknown option '{$name}'");
return $this->options[$name];
} | php | public function option(string $name)
{
if (!array_key_exists($name, $this->options))
throw new \InvalidArgumentException("Unknown option '{$name}'");
return $this->options[$name];
} | [
"public",
"function",
"option",
"(",
"string",
"$",
"name",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"name",
",",
"$",
"this",
"->",
"options",
")",
")",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"Unknown option '{$name}'\"",
")... | option getter.
@param string
@return mixed | [
"option",
"getter",
"."
] | d439b949140c226a0cc5a30f72fbbe25570b9871 | https://github.com/tarsana/command/blob/d439b949140c226a0cc5a30f72fbbe25570b9871/src/Command.php#L161-L166 | train |
tarsana/command | src/Command.php | Command.args | public function args(\stdClass $value = null)
{
if (null === $value) {
return $this->args;
}
$this->args = $value;
return $this;
} | php | public function args(\stdClass $value = null)
{
if (null === $value) {
return $this->args;
}
$this->args = $value;
return $this;
} | [
"public",
"function",
"args",
"(",
"\\",
"stdClass",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"value",
")",
"{",
"return",
"$",
"this",
"->",
"args",
";",
"}",
"$",
"this",
"->",
"args",
"=",
"$",
"value",
";",
"return"... | args getter and setter.
@param stdClass
@return mixed | [
"args",
"getter",
"and",
"setter",
"."
] | d439b949140c226a0cc5a30f72fbbe25570b9871 | https://github.com/tarsana/command/blob/d439b949140c226a0cc5a30f72fbbe25570b9871/src/Command.php#L174-L181 | train |
tarsana/command | src/Command.php | Command.console | public function console(ConsoleInterface $value = null)
{
if (null === $value) {
return $this->console;
}
$this->console = $value;
foreach ($this->commands as $name => $command) {
$command->console = $value;
}
return $this;
} | php | public function console(ConsoleInterface $value = null)
{
if (null === $value) {
return $this->console;
}
$this->console = $value;
foreach ($this->commands as $name => $command) {
$command->console = $value;
}
return $this;
} | [
"public",
"function",
"console",
"(",
"ConsoleInterface",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"value",
")",
"{",
"return",
"$",
"this",
"->",
"console",
";",
"}",
"$",
"this",
"->",
"console",
"=",
"$",
"value",
";",
... | console getter and setter.
@param ConsoleInterface
@return mixed | [
"console",
"getter",
"and",
"setter",
"."
] | d439b949140c226a0cc5a30f72fbbe25570b9871 | https://github.com/tarsana/command/blob/d439b949140c226a0cc5a30f72fbbe25570b9871/src/Command.php#L189-L199 | train |
tarsana/command | src/Command.php | Command.fs | public function fs($value = null)
{
if (null === $value) {
return $this->fs;
}
if (is_string($value))
$value = new Filesystem($value);
$this->fs = $value;
foreach ($this->commands as $name => $command) {
$command->fs = $value;
}
return $this;
} | php | public function fs($value = null)
{
if (null === $value) {
return $this->fs;
}
if (is_string($value))
$value = new Filesystem($value);
$this->fs = $value;
foreach ($this->commands as $name => $command) {
$command->fs = $value;
}
return $this;
} | [
"public",
"function",
"fs",
"(",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"value",
")",
"{",
"return",
"$",
"this",
"->",
"fs",
";",
"}",
"if",
"(",
"is_string",
"(",
"$",
"value",
")",
")",
"$",
"value",
"=",
"new",
... | fs getter and setter.
@param Tarsana\IO\Filesystem|string
@return mixed | [
"fs",
"getter",
"and",
"setter",
"."
] | d439b949140c226a0cc5a30f72fbbe25570b9871 | https://github.com/tarsana/command/blob/d439b949140c226a0cc5a30f72fbbe25570b9871/src/Command.php#L207-L219 | train |
tarsana/command | src/Command.php | Command.templatesLoader | public function templatesLoader(TemplateLoaderInterface $value = null)
{
if (null === $value) {
return $this->templatesLoader;
}
$this->templatesLoader = $value;
foreach ($this->commands as $name => $command) {
$command->templatesLoader = $value;
}
return $this;
} | php | public function templatesLoader(TemplateLoaderInterface $value = null)
{
if (null === $value) {
return $this->templatesLoader;
}
$this->templatesLoader = $value;
foreach ($this->commands as $name => $command) {
$command->templatesLoader = $value;
}
return $this;
} | [
"public",
"function",
"templatesLoader",
"(",
"TemplateLoaderInterface",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"value",
")",
"{",
"return",
"$",
"this",
"->",
"templatesLoader",
";",
"}",
"$",
"this",
"->",
"templatesLoader",
... | templatesLoader getter and setter.
@param Tarsana\Command\Interfaces\Template\TemplateLoaderInterface
@return mixed | [
"templatesLoader",
"getter",
"and",
"setter",
"."
] | d439b949140c226a0cc5a30f72fbbe25570b9871 | https://github.com/tarsana/command/blob/d439b949140c226a0cc5a30f72fbbe25570b9871/src/Command.php#L227-L237 | train |
tarsana/command | src/Command.php | Command.action | public function action(callable $value = null)
{
if (null === $value) {
return $this->action;
}
$this->action = $value;
return $this;
} | php | public function action(callable $value = null)
{
if (null === $value) {
return $this->action;
}
$this->action = $value;
return $this;
} | [
"public",
"function",
"action",
"(",
"callable",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"value",
")",
"{",
"return",
"$",
"this",
"->",
"action",
";",
"}",
"$",
"this",
"->",
"action",
"=",
"$",
"value",
";",
"return",
... | action getter and setter.
@param callable
@return mixed | [
"action",
"getter",
"and",
"setter",
"."
] | d439b949140c226a0cc5a30f72fbbe25570b9871 | https://github.com/tarsana/command/blob/d439b949140c226a0cc5a30f72fbbe25570b9871/src/Command.php#L276-L283 | train |
tarsana/command | src/Command.php | Command.commands | public function commands(array $value = null)
{
if (null === $value) {
return $this->commands;
}
$this->commands = [];
foreach ($value as $name => $command) {
$this->command($name, $command);
}
return $this;
} | php | public function commands(array $value = null)
{
if (null === $value) {
return $this->commands;
}
$this->commands = [];
foreach ($value as $name => $command) {
$this->command($name, $command);
}
return $this;
} | [
"public",
"function",
"commands",
"(",
"array",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"value",
")",
"{",
"return",
"$",
"this",
"->",
"commands",
";",
"}",
"$",
"this",
"->",
"commands",
"=",
"[",
"]",
";",
"foreach",
... | commands getter and setter.
@param array
@return mixed | [
"commands",
"getter",
"and",
"setter",
"."
] | d439b949140c226a0cc5a30f72fbbe25570b9871 | https://github.com/tarsana/command/blob/d439b949140c226a0cc5a30f72fbbe25570b9871/src/Command.php#L291-L301 | train |
forceedge01/behat-sql-extension | src/Extension.php | Extension.load | public function load(ContainerBuilder $container, array $config)
{
if (isset($config['connection_details'])) {
DEFINE('SQLDBENGINE', $config['connection_details']['engine']);
DEFINE('SQLDBHOST', $config['connection_details']['host']);
DEFINE('SQLDBSCHEMA', $config['connection_details']['schema']);
DEFINE('SQLDBNAME', $config['connection_details']['dbname']);
DEFINE('SQLDBUSERNAME', $config['connection_details']['username']);
DEFINE('SQLDBPASSWORD', $config['connection_details']['password']);
DEFINE('SQLDBPREFIX', $config['connection_details']['dbprefix']);
session_start();
// Store any keywords set in behat.yml file
if (isset($config['keywords']) and $config['keywords']) {
foreach ($config['keywords'] as $keyword => $value) {
$_SESSION['behat']['GenesisSqlExtension']['keywords'][$keyword] = $value;
}
}
// Set 'notQuotableKeywords' for later use.
$_SESSION['behat']['GenesisSqlExtension']['notQuotableKeywords'] = [];
if (isset($config['notQuotableKeywords'])) {
$_SESSION['behat']['GenesisSqlExtension']['notQuotableKeywords'] = $config['notQuotableKeywords'];
}
}
} | php | public function load(ContainerBuilder $container, array $config)
{
if (isset($config['connection_details'])) {
DEFINE('SQLDBENGINE', $config['connection_details']['engine']);
DEFINE('SQLDBHOST', $config['connection_details']['host']);
DEFINE('SQLDBSCHEMA', $config['connection_details']['schema']);
DEFINE('SQLDBNAME', $config['connection_details']['dbname']);
DEFINE('SQLDBUSERNAME', $config['connection_details']['username']);
DEFINE('SQLDBPASSWORD', $config['connection_details']['password']);
DEFINE('SQLDBPREFIX', $config['connection_details']['dbprefix']);
session_start();
// Store any keywords set in behat.yml file
if (isset($config['keywords']) and $config['keywords']) {
foreach ($config['keywords'] as $keyword => $value) {
$_SESSION['behat']['GenesisSqlExtension']['keywords'][$keyword] = $value;
}
}
// Set 'notQuotableKeywords' for later use.
$_SESSION['behat']['GenesisSqlExtension']['notQuotableKeywords'] = [];
if (isset($config['notQuotableKeywords'])) {
$_SESSION['behat']['GenesisSqlExtension']['notQuotableKeywords'] = $config['notQuotableKeywords'];
}
}
} | [
"public",
"function",
"load",
"(",
"ContainerBuilder",
"$",
"container",
",",
"array",
"$",
"config",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"config",
"[",
"'connection_details'",
"]",
")",
")",
"{",
"DEFINE",
"(",
"'SQLDBENGINE'",
",",
"$",
"config",
"... | Load and set the configuration options. | [
"Load",
"and",
"set",
"the",
"configuration",
"options",
"."
] | ce2b1ea9927ff2a65bf18bd3e757246188976d69 | https://github.com/forceedge01/behat-sql-extension/blob/ce2b1ea9927ff2a65bf18bd3e757246188976d69/src/Extension.php#L29-L54 | train |
tarsana/command | src/SubCommand.php | SubCommand.parent | public function parent(Command $value = null)
{
if (null === $value) {
return $this->parent;
}
$this->parent = $value;
return $this;
} | php | public function parent(Command $value = null)
{
if (null === $value) {
return $this->parent;
}
$this->parent = $value;
return $this;
} | [
"public",
"function",
"parent",
"(",
"Command",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"value",
")",
"{",
"return",
"$",
"this",
"->",
"parent",
";",
"}",
"$",
"this",
"->",
"parent",
"=",
"$",
"value",
";",
"return",
... | parent getter and setter.
@param Tarsana\Command\Command|null
@return Tarsana\Command\Command | [
"parent",
"getter",
"and",
"setter",
"."
] | d439b949140c226a0cc5a30f72fbbe25570b9871 | https://github.com/tarsana/command/blob/d439b949140c226a0cc5a30f72fbbe25570b9871/src/SubCommand.php#L38-L45 | train |
forceedge01/behat-sql-extension | src/Context/SQLHandler.php | SQLHandler.getConnection | public function getConnection()
{
if (! $this->connection) {
list($dns, $username, $password) = $this->connectionString();
$this->setConnection(new \PDO($dns, $username, $password));
}
return $this->connection;
} | php | public function getConnection()
{
if (! $this->connection) {
list($dns, $username, $password) = $this->connectionString();
$this->setConnection(new \PDO($dns, $username, $password));
}
return $this->connection;
} | [
"public",
"function",
"getConnection",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"connection",
")",
"{",
"list",
"(",
"$",
"dns",
",",
"$",
"username",
",",
"$",
"password",
")",
"=",
"$",
"this",
"->",
"connectionString",
"(",
")",
";",
"$... | Gets the connection for query execution. | [
"Gets",
"the",
"connection",
"for",
"query",
"execution",
"."
] | ce2b1ea9927ff2a65bf18bd3e757246188976d69 | https://github.com/forceedge01/behat-sql-extension/blob/ce2b1ea9927ff2a65bf18bd3e757246188976d69/src/Context/SQLHandler.php#L48-L57 | train |
forceedge01/behat-sql-extension | src/Context/SQLHandler.php | SQLHandler.setDBParams | public function setDBParams(array $dbParams = array())
{
if (defined('SQLDBENGINE')) {
$this->params = [
'DBSCHEMA' => SQLDBSCHEMA,
'DBNAME' => SQLDBNAME,
'DBPREFIX' => SQLDBPREFIX
];
// Allow params to be over-ridable.
$this->params['DBHOST'] = (isset($dbParams['host']) ? $dbParams['host'] : SQLDBHOST);
$this->params['DBUSER'] = (isset($dbParams['username']) ? $dbParams['username'] : SQLDBUSERNAME);
$this->params['DBPASSWORD'] = (isset($dbParams['password']) ? $dbParams['password'] : SQLDBPASSWORD);
$this->params['DBENGINE'] = (isset($dbParams['engine']) ? $dbParams['engine'] : SQLDBENGINE);
} else {
$params = getenv('BEHAT_ENV_PARAMS');
if (! $params) {
throw new \Exception('"BEHAT_ENV_PARAMS" environment variable was not found.');
}
$params = explode(';', $params);
foreach ($params as $param) {
list($key, $val) = explode(':', $param);
$this->params[$key] = trim($val);
}
}
return $this;
} | php | public function setDBParams(array $dbParams = array())
{
if (defined('SQLDBENGINE')) {
$this->params = [
'DBSCHEMA' => SQLDBSCHEMA,
'DBNAME' => SQLDBNAME,
'DBPREFIX' => SQLDBPREFIX
];
// Allow params to be over-ridable.
$this->params['DBHOST'] = (isset($dbParams['host']) ? $dbParams['host'] : SQLDBHOST);
$this->params['DBUSER'] = (isset($dbParams['username']) ? $dbParams['username'] : SQLDBUSERNAME);
$this->params['DBPASSWORD'] = (isset($dbParams['password']) ? $dbParams['password'] : SQLDBPASSWORD);
$this->params['DBENGINE'] = (isset($dbParams['engine']) ? $dbParams['engine'] : SQLDBENGINE);
} else {
$params = getenv('BEHAT_ENV_PARAMS');
if (! $params) {
throw new \Exception('"BEHAT_ENV_PARAMS" environment variable was not found.');
}
$params = explode(';', $params);
foreach ($params as $param) {
list($key, $val) = explode(':', $param);
$this->params[$key] = trim($val);
}
}
return $this;
} | [
"public",
"function",
"setDBParams",
"(",
"array",
"$",
"dbParams",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"defined",
"(",
"'SQLDBENGINE'",
")",
")",
"{",
"$",
"this",
"->",
"params",
"=",
"[",
"'DBSCHEMA'",
"=>",
"SQLDBSCHEMA",
",",
"'DBNAME'",
... | Sets the database param from either the environment variable or params
passed in by behat.yml, params have precedence over env variable. | [
"Sets",
"the",
"database",
"param",
"from",
"either",
"the",
"environment",
"variable",
"or",
"params",
"passed",
"in",
"by",
"behat",
".",
"yml",
"params",
"have",
"precedence",
"over",
"env",
"variable",
"."
] | ce2b1ea9927ff2a65bf18bd3e757246188976d69 | https://github.com/forceedge01/behat-sql-extension/blob/ce2b1ea9927ff2a65bf18bd3e757246188976d69/src/Context/SQLHandler.php#L73-L103 | train |
forceedge01/behat-sql-extension | src/Context/SQLHandler.php | SQLHandler.connectionString | private function connectionString()
{
return [
sprintf(
'%s:dbname=%s;host=%s',
$this->params['DBENGINE'],
$this->params['DBNAME'],
$this->params['DBHOST']
),
$this->params['DBUSER'],
$this->params['DBPASSWORD']
];
} | php | private function connectionString()
{
return [
sprintf(
'%s:dbname=%s;host=%s',
$this->params['DBENGINE'],
$this->params['DBNAME'],
$this->params['DBHOST']
),
$this->params['DBUSER'],
$this->params['DBPASSWORD']
];
} | [
"private",
"function",
"connectionString",
"(",
")",
"{",
"return",
"[",
"sprintf",
"(",
"'%s:dbname=%s;host=%s'",
",",
"$",
"this",
"->",
"params",
"[",
"'DBENGINE'",
"]",
",",
"$",
"this",
"->",
"params",
"[",
"'DBNAME'",
"]",
",",
"$",
"this",
"->",
"... | Creates the connection string for the pdo object. | [
"Creates",
"the",
"connection",
"string",
"for",
"the",
"pdo",
"object",
"."
] | ce2b1ea9927ff2a65bf18bd3e757246188976d69 | https://github.com/forceedge01/behat-sql-extension/blob/ce2b1ea9927ff2a65bf18bd3e757246188976d69/src/Context/SQLHandler.php#L116-L128 | train |
forceedge01/behat-sql-extension | src/Context/SQLHandler.php | SQLHandler.requiredTableColumns | protected function requiredTableColumns($table)
{
// If the DBSCHEMA is not set, try using the database name if provided with the table.
if (! $this->params['DBSCHEMA']) {
preg_match('/(.*)\./', $table, $db);
if (isset($db[1])) {
$this->params['DBSCHEMA'] = $db[1];
}
}
// Parse out the table name.
$table = preg_replace('/(.*\.)/', '', $table);
$table = trim($table, '`');
// Statement to extract all required columns for a table.
$sqlStatement = "
SELECT
column_name, data_type
FROM
information_schema.columns
WHERE
is_nullable = 'NO'
AND
table_name = '%s'
AND
table_schema = '%s';";
// Get not null columns
$sql = sprintf(
$sqlStatement,
$table,
$this->params['DBSCHEMA']
);
$statement = $this->execute($sql);
$this->throwExceptionIfErrors($statement);
$result = $statement->fetchAll();
if (! $result) {
return [];
}
$cols = [];
foreach ($result as $column) {
$cols[$column['column_name']] = $column['data_type'];
}
// Dont populate primary key, let db handle that
unset($cols['id']);
return $cols;
} | php | protected function requiredTableColumns($table)
{
// If the DBSCHEMA is not set, try using the database name if provided with the table.
if (! $this->params['DBSCHEMA']) {
preg_match('/(.*)\./', $table, $db);
if (isset($db[1])) {
$this->params['DBSCHEMA'] = $db[1];
}
}
// Parse out the table name.
$table = preg_replace('/(.*\.)/', '', $table);
$table = trim($table, '`');
// Statement to extract all required columns for a table.
$sqlStatement = "
SELECT
column_name, data_type
FROM
information_schema.columns
WHERE
is_nullable = 'NO'
AND
table_name = '%s'
AND
table_schema = '%s';";
// Get not null columns
$sql = sprintf(
$sqlStatement,
$table,
$this->params['DBSCHEMA']
);
$statement = $this->execute($sql);
$this->throwExceptionIfErrors($statement);
$result = $statement->fetchAll();
if (! $result) {
return [];
}
$cols = [];
foreach ($result as $column) {
$cols[$column['column_name']] = $column['data_type'];
}
// Dont populate primary key, let db handle that
unset($cols['id']);
return $cols;
} | [
"protected",
"function",
"requiredTableColumns",
"(",
"$",
"table",
")",
"{",
"// If the DBSCHEMA is not set, try using the database name if provided with the table.",
"if",
"(",
"!",
"$",
"this",
"->",
"params",
"[",
"'DBSCHEMA'",
"]",
")",
"{",
"preg_match",
"(",
"'/(... | Gets a column list for a table with their type. | [
"Gets",
"a",
"column",
"list",
"for",
"a",
"table",
"with",
"their",
"type",
"."
] | ce2b1ea9927ff2a65bf18bd3e757246188976d69 | https://github.com/forceedge01/behat-sql-extension/blob/ce2b1ea9927ff2a65bf18bd3e757246188976d69/src/Context/SQLHandler.php#L133-L185 | train |
forceedge01/behat-sql-extension | src/Context/SQLHandler.php | SQLHandler.sampleData | public function sampleData($type)
{
switch (strtolower($type)) {
case 'boolean':
return 'false';
case 'integer':
case 'double':
case 'int':
return rand();
case 'tinyint':
return rand(0, 9);
case 'string':
case 'text':
case 'varchar':
case 'character varying':
case 'tinytext':
case 'longtext':
return $this->quoteOrNot(sprintf("behat-test-string-%s", time()));
case 'char':
return "'f'";
case 'timestamp':
case 'timestamp with time zone':
return 'NOW()';
case 'null':
return null;
default:
return $this->quoteOrNot(sprintf("behat-test-string-%s", time()));
}
} | php | public function sampleData($type)
{
switch (strtolower($type)) {
case 'boolean':
return 'false';
case 'integer':
case 'double':
case 'int':
return rand();
case 'tinyint':
return rand(0, 9);
case 'string':
case 'text':
case 'varchar':
case 'character varying':
case 'tinytext':
case 'longtext':
return $this->quoteOrNot(sprintf("behat-test-string-%s", time()));
case 'char':
return "'f'";
case 'timestamp':
case 'timestamp with time zone':
return 'NOW()';
case 'null':
return null;
default:
return $this->quoteOrNot(sprintf("behat-test-string-%s", time()));
}
} | [
"public",
"function",
"sampleData",
"(",
"$",
"type",
")",
"{",
"switch",
"(",
"strtolower",
"(",
"$",
"type",
")",
")",
"{",
"case",
"'boolean'",
":",
"return",
"'false'",
";",
"case",
"'integer'",
":",
"case",
"'double'",
":",
"case",
"'int'",
":",
"... | returns sample data for a data type. | [
"returns",
"sample",
"data",
"for",
"a",
"data",
"type",
"."
] | ce2b1ea9927ff2a65bf18bd3e757246188976d69 | https://github.com/forceedge01/behat-sql-extension/blob/ce2b1ea9927ff2a65bf18bd3e757246188976d69/src/Context/SQLHandler.php#L190-L218 | train |
forceedge01/behat-sql-extension | src/Context/SQLHandler.php | SQLHandler.constructSQLClause | public function constructSQLClause($glue, array $columns)
{
$whereClause = [];
foreach ($columns as $column => $value) {
$newValue = ltrim($value, '!');
$quotedValue = $this->quoteOrNot($newValue);
$comparator = '%s=';
$notOperator = '';
// Check if the supplied value is null, if so change the format.
if (strtolower($newValue) == 'null') {
$comparator = 'is%s';
}
// Check if a not is applied to the value.
if ($newValue !== $value) {
if (strtolower($newValue) == 'null') {
$notOperator = ' not';
} else {
$notOperator = '!';
}
}
// Check if the value is surrounded by wildcards. If so, we'll want to use a LIKE comparator.
if (preg_match('/^%.+%$/', $value)) {
$comparator = 'LIKE';
}
// Make up the sql.
$comparator = sprintf($comparator, $notOperator);
$whereClause[] = sprintf('%s %s %s', $column, $comparator, $quotedValue);
}
return implode($glue, $whereClause);
} | php | public function constructSQLClause($glue, array $columns)
{
$whereClause = [];
foreach ($columns as $column => $value) {
$newValue = ltrim($value, '!');
$quotedValue = $this->quoteOrNot($newValue);
$comparator = '%s=';
$notOperator = '';
// Check if the supplied value is null, if so change the format.
if (strtolower($newValue) == 'null') {
$comparator = 'is%s';
}
// Check if a not is applied to the value.
if ($newValue !== $value) {
if (strtolower($newValue) == 'null') {
$notOperator = ' not';
} else {
$notOperator = '!';
}
}
// Check if the value is surrounded by wildcards. If so, we'll want to use a LIKE comparator.
if (preg_match('/^%.+%$/', $value)) {
$comparator = 'LIKE';
}
// Make up the sql.
$comparator = sprintf($comparator, $notOperator);
$whereClause[] = sprintf('%s %s %s', $column, $comparator, $quotedValue);
}
return implode($glue, $whereClause);
} | [
"public",
"function",
"constructSQLClause",
"(",
"$",
"glue",
",",
"array",
"$",
"columns",
")",
"{",
"$",
"whereClause",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"columns",
"as",
"$",
"column",
"=>",
"$",
"value",
")",
"{",
"$",
"newValue",
"=",
"lt... | Constructs a clause based on the glue, to be used for where and update clause. | [
"Constructs",
"a",
"clause",
"based",
"on",
"the",
"glue",
"to",
"be",
"used",
"for",
"where",
"and",
"update",
"clause",
"."
] | ce2b1ea9927ff2a65bf18bd3e757246188976d69 | https://github.com/forceedge01/behat-sql-extension/blob/ce2b1ea9927ff2a65bf18bd3e757246188976d69/src/Context/SQLHandler.php#L223-L259 | train |
forceedge01/behat-sql-extension | src/Context/SQLHandler.php | SQLHandler.getTableColumns | protected function getTableColumns($entity)
{
$columnClause = [];
// Get all columns for insertion
$allColumns = array_merge($this->requiredTableColumns($entity), $this->columns);
// Set values for columns
foreach ($allColumns as $col => $type) {
$columnClause[$col] = isset($this->columns[$col]) ?
$this->quoteOrNot($this->columns[$col]) :
$this->sampleData($type);
}
$columnNames = implode(', ', array_keys($columnClause));
$columnValues = implode(', ', $columnClause);
return [$columnNames, $columnValues];
} | php | protected function getTableColumns($entity)
{
$columnClause = [];
// Get all columns for insertion
$allColumns = array_merge($this->requiredTableColumns($entity), $this->columns);
// Set values for columns
foreach ($allColumns as $col => $type) {
$columnClause[$col] = isset($this->columns[$col]) ?
$this->quoteOrNot($this->columns[$col]) :
$this->sampleData($type);
}
$columnNames = implode(', ', array_keys($columnClause));
$columnValues = implode(', ', $columnClause);
return [$columnNames, $columnValues];
} | [
"protected",
"function",
"getTableColumns",
"(",
"$",
"entity",
")",
"{",
"$",
"columnClause",
"=",
"[",
"]",
";",
"// Get all columns for insertion",
"$",
"allColumns",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"requiredTableColumns",
"(",
"$",
"entity",
")",... | Gets table columns and its values, returns array. | [
"Gets",
"table",
"columns",
"and",
"its",
"values",
"returns",
"array",
"."
] | ce2b1ea9927ff2a65bf18bd3e757246188976d69 | https://github.com/forceedge01/behat-sql-extension/blob/ce2b1ea9927ff2a65bf18bd3e757246188976d69/src/Context/SQLHandler.php#L264-L282 | train |
forceedge01/behat-sql-extension | src/Context/SQLHandler.php | SQLHandler.filterAndConvertToArray | public function filterAndConvertToArray($columns)
{
$this->columns = [];
$columns = explode(',', $columns);
foreach ($columns as $column) {
try {
list($col, $val) = explode(':', $column, self::EXPLODE_MAX_LIMIT);
} catch (\Exception $e) {
throw new \Exception('Unable to explode columns based on ":" separator');
}
$val = $this->checkForKeyword(trim($val));
$this->columns[trim($col)] = $val;
}
return $this;
} | php | public function filterAndConvertToArray($columns)
{
$this->columns = [];
$columns = explode(',', $columns);
foreach ($columns as $column) {
try {
list($col, $val) = explode(':', $column, self::EXPLODE_MAX_LIMIT);
} catch (\Exception $e) {
throw new \Exception('Unable to explode columns based on ":" separator');
}
$val = $this->checkForKeyword(trim($val));
$this->columns[trim($col)] = $val;
}
return $this;
} | [
"public",
"function",
"filterAndConvertToArray",
"(",
"$",
"columns",
")",
"{",
"$",
"this",
"->",
"columns",
"=",
"[",
"]",
";",
"$",
"columns",
"=",
"explode",
"(",
"','",
",",
"$",
"columns",
")",
";",
"foreach",
"(",
"$",
"columns",
"as",
"$",
"c... | Converts the incoming string param from steps to array. | [
"Converts",
"the",
"incoming",
"string",
"param",
"from",
"steps",
"to",
"array",
"."
] | ce2b1ea9927ff2a65bf18bd3e757246188976d69 | https://github.com/forceedge01/behat-sql-extension/blob/ce2b1ea9927ff2a65bf18bd3e757246188976d69/src/Context/SQLHandler.php#L287-L304 | train |
forceedge01/behat-sql-extension | src/Context/SQLHandler.php | SQLHandler.setKeyword | public function setKeyword($key, $value)
{
$this->debugLog(sprintf(
'Saving keyword "%s" with value "%s"',
$key,
$value
));
$_SESSION['behat']['GenesisSqlExtension']['keywords'][$key] = $value;
return $this;
} | php | public function setKeyword($key, $value)
{
$this->debugLog(sprintf(
'Saving keyword "%s" with value "%s"',
$key,
$value
));
$_SESSION['behat']['GenesisSqlExtension']['keywords'][$key] = $value;
return $this;
} | [
"public",
"function",
"setKeyword",
"(",
"$",
"key",
",",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"debugLog",
"(",
"sprintf",
"(",
"'Saving keyword \"%s\" with value \"%s\"'",
",",
"$",
"key",
",",
"$",
"value",
")",
")",
";",
"$",
"_SESSION",
"[",
"'... | Sets a behat keyword. | [
"Sets",
"a",
"behat",
"keyword",
"."
] | ce2b1ea9927ff2a65bf18bd3e757246188976d69 | https://github.com/forceedge01/behat-sql-extension/blob/ce2b1ea9927ff2a65bf18bd3e757246188976d69/src/Context/SQLHandler.php#L309-L320 | train |
forceedge01/behat-sql-extension | src/Context/SQLHandler.php | SQLHandler.getKeyword | public function getKeyword($key)
{
$this->debugLog(sprintf(
'Retrieving keyword "%s"',
$key
));
if (! isset($_SESSION['behat']['GenesisSqlExtension']['keywords'][$key])) {
throw new \Exception(sprintf(
'Key "%s" not found in behat store, all keys available: %s',
$key,
print_r($_SESSION['behat']['GenesisSqlExtension']['keywords'], true)
));
}
$value = $_SESSION['behat']['GenesisSqlExtension']['keywords'][$key];
$this->debugLog(sprintf(
'Retrieved keyword "%s" with value "%s"',
$key,
$value
));
return $value;
} | php | public function getKeyword($key)
{
$this->debugLog(sprintf(
'Retrieving keyword "%s"',
$key
));
if (! isset($_SESSION['behat']['GenesisSqlExtension']['keywords'][$key])) {
throw new \Exception(sprintf(
'Key "%s" not found in behat store, all keys available: %s',
$key,
print_r($_SESSION['behat']['GenesisSqlExtension']['keywords'], true)
));
}
$value = $_SESSION['behat']['GenesisSqlExtension']['keywords'][$key];
$this->debugLog(sprintf(
'Retrieved keyword "%s" with value "%s"',
$key,
$value
));
return $value;
} | [
"public",
"function",
"getKeyword",
"(",
"$",
"key",
")",
"{",
"$",
"this",
"->",
"debugLog",
"(",
"sprintf",
"(",
"'Retrieving keyword \"%s\"'",
",",
"$",
"key",
")",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"_SESSION",
"[",
"'behat'",
"]",
"[",
... | Fetches a specific keyword from the behat keywords store. | [
"Fetches",
"a",
"specific",
"keyword",
"from",
"the",
"behat",
"keywords",
"store",
"."
] | ce2b1ea9927ff2a65bf18bd3e757246188976d69 | https://github.com/forceedge01/behat-sql-extension/blob/ce2b1ea9927ff2a65bf18bd3e757246188976d69/src/Context/SQLHandler.php#L325-L349 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.