repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Subset/RangeSubset.php
src/Fogger/Subset/RangeSubset.php
<?php namespace App\Fogger\Subset; use App\Fogger\Recipe\Table; use Doctrine\DBAL\Query\QueryBuilder; class RangeSubset extends AbstractSubset { /** * @param array $options * @throws Exception\RequiredOptionMissingException */ private function ensureValidOptions(array $options) { $this->ensureOptionIsSet($options, 'column'); $this->ensureOptionIsSet($options, 'from'); $this->ensureOptionIsSet($options, 'to'); } /** * @param QueryBuilder $queryBuilder * @param Table $table * @return QueryBuilder * @throws Exception\RequiredOptionMissingException */ public function subsetQuery(QueryBuilder $queryBuilder, Table $table): QueryBuilder { $this->ensureValidOptions($options = $table->getSubset()->getOptions()); return $queryBuilder ->where(sprintf('%s >= ?', $options['column'])) ->andWhere(sprintf('%s <= ?', $options['column'])) ->setParameter(0, $options['from']) ->setParameter(1, $options['to']); } protected function getSubsetStrategyName(): string { return 'range'; } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Subset/HeadSubset.php
src/Fogger/Subset/HeadSubset.php
<?php namespace App\Fogger\Subset; use App\Fogger\Recipe\Table; use App\Fogger\Subset\Exception\SortByColumnRequired; use Doctrine\DBAL\Query\QueryBuilder; class HeadSubset extends AbstratctHeadOrTailSubset { /** * @param QueryBuilder $queryBuilder * @param Table $table * @return QueryBuilder * @throws Exception\RequiredOptionMissingException * @throws SortByColumnRequired */ public function subsetQuery(QueryBuilder $queryBuilder, Table $table): QueryBuilder { $this->ensureOptionIsSet($table->getSubset()->getOptions(), 'length'); $this->ensureSortByColumn($table); return $queryBuilder ->andWhere(sprintf('%s <= ?', $table->getSortBy())) ->setParameter(0, $this->findOffsetId($table, false)); } public function getSubsetStrategyName(): string { return 'head'; } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Subset/AbstratctHeadOrTailSubset.php
src/Fogger/Subset/AbstratctHeadOrTailSubset.php
<?php namespace App\Fogger\Subset; use App\Fogger\Recipe\Table; use App\Fogger\Subset\Exception\SortByColumnRequired; use Doctrine\Common\Collections\Criteria; use Doctrine\DBAL\Connection; abstract class AbstratctHeadOrTailSubset extends AbstractSubset { private $source; public function __construct(Connection $source) { $this->source = $source; } /** * @param Table $table * @throws SortByColumnRequired */ protected function ensureSortByColumn(Table $table) { if (null === $table->getSortBy()) { throw new SortByColumnRequired( sprintf( 'Error! Strategy require the table to have a unique sortBy column', $table->getName() ) ); } } protected function findOffsetId(Table $table, bool $reverse) { $options = $table->getSubset()->getOptions(); $findOffsetId = $this->source->createQueryBuilder(); $findOffsetId ->select($this->source->quoteIdentifier($table->getSortBy())) ->from($this->source->quoteIdentifier($table->getName())) ->addOrderBy($table->getSortBy(), $reverse ? Criteria::DESC : Criteria::ASC) ->setFirstResult($options['length'] - 1) ->setMaxResults(1); return $findOffsetId->execute()->fetchColumn(); } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Subset/Exception/SortByColumnRequired.php
src/Fogger/Subset/Exception/SortByColumnRequired.php
<?php namespace App\Fogger\Subset\Exception; class SortByColumnRequired extends \Exception { }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Subset/Exception/UnknownSubsetStrategyException.php
src/Fogger/Subset/Exception/UnknownSubsetStrategyException.php
<?php namespace App\Fogger\Subset\Exception; class UnknownSubsetStrategyException extends \Exception { }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Subset/Exception/RequiredOptionMissingException.php
src/Fogger/Subset/Exception/RequiredOptionMissingException.php
<?php namespace App\Fogger\Subset\Exception; class RequiredOptionMissingException extends \Exception { }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Serializer/TableDenormalizer.php
src/Fogger/Serializer/TableDenormalizer.php
<?php namespace App\Fogger\Serializer; use App\Fogger\Recipe\StrategyDefinition; use App\Fogger\Recipe\Table; use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait; use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; class TableDenormalizer implements DenormalizerInterface { use DenormalizerAwareTrait; public function supportsDenormalization($data, $type, $format = null) { return $format == 'json' && $type == Table::class; } public function denormalize($data, $class, $format = null, array $context = array()) { /** @var StrategyDefinition $subset */ $subset = $this->denormalizer ->denormalize($data['subset'], StrategyDefinition::class, $format, $context); $table = new Table( $data['name'], $data['chunkSize'], $data['sortBy'], $subset ?? new StrategyDefinition('noSubset') ); foreach ($data['masks'] ?? [] as $key => $mask) { $table->addMask($key, new StrategyDefinition($mask['name'], $mask['options'])); } return $table; } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Mask/HashifyMask.php
src/Fogger/Mask/HashifyMask.php
<?php namespace App\Fogger\Mask; final class HashifyMask extends AbstractMask { public function apply(?string $value, array $options = []): ?string { if (null === $value) { return $value; } return sprintf($options['template'] ?? '%s', md5($value)); } protected function getMaskName(): string { return 'hashify'; } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Mask/FakerMask.php
src/Fogger/Mask/FakerMask.php
<?php namespace App\Fogger\Mask; use Faker\Generator; use Psr\Cache\CacheItemPoolInterface; final class FakerMask extends AbstractCachedMask { const DEFAULT_METHOD = 'email'; private $generator; public function __construct(Generator $generator, CacheItemPoolInterface $cache) { $this->generator = $generator; parent::__construct($cache); } public function getSubstitution(array $options = []): ?string { $method = $options['method'] ?? self::DEFAULT_METHOD; $arguments = $options['arguments'] ?? []; $modifier = $options['modifier'] ?? null; $modifierArguments = $options['modifierArguments'] ?? []; $generator = $this->generator; if ('optional' === $modifier) { $generator = $generator->optional(...$modifierArguments); } $result = $generator->$method(...$arguments); if (is_array($result)) { $result = implode(' ', $result); } elseif ($result instanceof \DateTime) { $result = $result->format("Y-m-d H:i:s"); } return $result; } protected function getMaskName(): string { return 'faker'; } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Mask/AbstractCachedMask.php
src/Fogger/Mask/AbstractCachedMask.php
<?php namespace App\Fogger\Mask; use Psr\Cache\CacheItemPoolInterface; abstract class AbstractCachedMask extends AbstractMask { private const LOCK_VALUE = 'fogger::pending'; /** * @var CacheItemPoolInterface */ protected $cache; public function __construct(CacheItemPoolInterface $cache) { $this->cache = $cache; } abstract protected function getSubstitution(array $options = []): ?string; private function forgeCacheKey(string $value, array $options, bool $substitute = false) { return md5( sprintf("%s.%s.%s.%s", $value, $this->getMaskName(), json_encode($options), $substitute) ); } /** * @param null|string $value * @param array $options * @return null|string * @throws \Psr\Cache\InvalidArgumentException */ public function apply(?string $value, array $options = []): ?string { if (null === $value) { return $value; } do { $originalValueCacheItem = $this->cache->getItem($this->forgeCacheKey($value, $options)); } while ($originalValueCacheItem->get() === self::LOCK_VALUE); if ($originalValueCacheItem->isHit()) { return $originalValueCacheItem->get(); } else { $originalValueCacheItem->set(self::LOCK_VALUE); $this->cache->save($originalValueCacheItem); } $tries = 0; do { $tries++; $substitution = $this->getSubstitution($options); $substitutionCacheItem = $this->cache->getItem($this->forgeCacheKey($substitution, $options, true)); if ($tries == 100) { break; } } while ($substitutionCacheItem->isHit()); $this->cache->save($substitutionCacheItem); $originalValueCacheItem->set($substitution); $this->cache->save($originalValueCacheItem); return $substitution; } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Mask/MaskStrategyInterface.php
src/Fogger/Mask/MaskStrategyInterface.php
<?php namespace App\Fogger\Mask; interface MaskStrategyInterface { public function apply(?string $value, array $options = []): ?string; public function supports(string $name): bool; }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Mask/AbstractMask.php
src/Fogger/Mask/AbstractMask.php
<?php namespace App\Fogger\Mask; abstract class AbstractMask implements MaskStrategyInterface { abstract protected function getMaskName(): string; public function supports(string $name): bool { if ($name === $this->getMaskName()) { return true; } return false; } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Mask/MaskStrategyProvider.php
src/Fogger/Mask/MaskStrategyProvider.php
<?php namespace App\Fogger\Mask; use App\Fogger\Mask\Exception\UnknownMaskException; class MaskStrategyProvider { private $masks = []; public function __construct(iterable $masks) { foreach ($masks as $mask) { $this->addMask($mask); } } private function addMask(MaskStrategyInterface $mask) { $this->masks[] = $mask; } /** * @param string $name * @return MaskStrategyInterface * @throws UnknownMaskException */ public function getMask(string $name): MaskStrategyInterface { foreach ($this->masks as $mask) { if ($mask->supports($name)) { return $mask; } } throw new UnknownMaskException('Unknown mask "'.$name.'".'); } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Mask/StarifyMask.php
src/Fogger/Mask/StarifyMask.php
<?php namespace App\Fogger\Mask; final class StarifyMask extends AbstractMask { public function apply(?string $value, array $options = []): ?string { if (null === $value) { return $value; } return str_repeat('*', $options['length'] ?? 10); } protected function getMaskName(): string { return 'starify'; } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Mask/Exception/UnknownMaskException.php
src/Fogger/Mask/Exception/UnknownMaskException.php
<?php namespace App\Fogger\Mask\Exception; class UnknownMaskException extends \Exception { }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Data/ChunkReader.php
src/Fogger/Data/ChunkReader.php
<?php namespace App\Fogger\Data; class ChunkReader { private $sourceQuery; public function __construct(SourceQuery $sourceQuery) { $this->sourceQuery = $sourceQuery; } /** * @param ChunkMessage $chunkMessage * @return array * @throws \App\Fogger\Subset\Exception\UnknownSubsetStrategyException */ public function getDataChunk(ChunkMessage $chunkMessage): array { $query = $this->sourceQuery->getAllRowsQuery( $chunkMessage->getTable(), $chunkMessage->getKeys() ); return $query->execute()->fetchAll(); } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Data/SourceQuery.php
src/Fogger/Data/SourceQuery.php
<?php namespace App\Fogger\Data; use App\Fogger\Recipe\Table; use App\Fogger\Subset\SubsetStrategyProvider; use Doctrine\DBAL\Connection; use Doctrine\DBAL\Query\QueryBuilder; class SourceQuery { private $source; private $provider; public function __construct(Connection $source, SubsetStrategyProvider $provider) { $this->source = $source; $this->provider = $provider; } /** * @param Table $table * @return QueryBuilder * @throws \App\Fogger\Subset\Exception\UnknownSubsetStrategyException */ public function getAllKeysQuery(Table $table) { $query = $this->getAllRowsQuery($table); $query ->resetQueryPart('select') ->select($this->source->quoteIdentifier($table->getSortBy())); return $query; } /** * @param Table $table * @param array $keys * @return QueryBuilder * @throws \App\Fogger\Subset\Exception\UnknownSubsetStrategyException */ public function getAllRowsQuery(Table $table, array $keys = []): QueryBuilder { $query = $this->source->createQueryBuilder(); $query ->select('*') ->from($this->source->quoteIdentifier($table->getName())); if (count($keys)) { $query ->where($query->expr()->in($table->getSortBy(), ':keys')) ->setParameter('keys', $keys, Connection::PARAM_STR_ARRAY); return $query; } $subset = $this->provider->getSubsetStrategy($table->getSubsetName()); return $subset->subsetQuery($query, $table); } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Data/ChunkConsumer.php
src/Fogger/Data/ChunkConsumer.php
<?php namespace App\Fogger\Data; class ChunkConsumer { private $dataCopier; private $cache; private $error; public function __construct( DataCopier $dataCopier, ChunkCache $cache, ChunkError $error ) { $this->dataCopier = $dataCopier; $this->cache = $cache; $this->error = $error; } public function execute(ChunkMessage $message) { try { $this->dataCopier->copyDataChunk($message); } catch (\Exception $exception) { $this->error->addError($exception->getMessage()); } $this->cache->increaseProcessedCount(); } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Data/ChunkCache.php
src/Fogger/Data/ChunkCache.php
<?php namespace App\Fogger\Data; use App\Fogger\Recipe\Table; use Predis\Client; use Symfony\Component\Serializer\SerializerInterface; class ChunkCache { const LIST_NAME = 'fogger::chunks'; const CHUNKS_PUBLISHED = 'fogger::chunks_published'; const CHUNKS_PROCESSED = 'fogger::chunks_processed'; private $redis; private $serializer; public function __construct(Client $redis, SerializerInterface $serializer) { $this->redis = $redis; $this->serializer = $serializer; } public function reset() { $this->redis->del( [ self::CHUNKS_PUBLISHED, self::CHUNKS_PROCESSED, self::LIST_NAME, ] ); } public function pushMessage(Table $table, array $keys = []) { $message = $this->serializer->serialize(new ChunkMessage($table, $keys), 'json'); $this->redis->rpush(self::LIST_NAME, [$message]); $this->increasePublishedCount(); } public function popMessage() { if (null === $content = $this->redis->lpop(self::LIST_NAME)) { return null; } return $this->serializer->deserialize( $content, ChunkMessage::class, 'json' ); } public function increasePublishedCount() { $this->redis->incr(self::CHUNKS_PUBLISHED); } public function increaseProcessedCount() { $this->redis->incr(self::CHUNKS_PROCESSED); } public function getPublishedCount(): int { return $this->redis->get(self::CHUNKS_PUBLISHED) ?? 0; } public function getProcessedCount(): int { return $this->redis->get(self::CHUNKS_PROCESSED) ?? 0; } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Data/Masker.php
src/Fogger/Data/Masker.php
<?php namespace App\Fogger\Data; use App\Fogger\Mask\MaskStrategyProvider; use App\Fogger\Recipe\StrategyDefinition; class Masker { private $maskStrategyProvider; public function __construct(MaskStrategyProvider $maskStrategyProvider) { $this->maskStrategyProvider = $maskStrategyProvider; } /** * @param array $data * @param array $masks * @return array * @throws \App\Fogger\Mask\Exception\UnknownMaskException */ public function applyMasks(array $data, array $masks): array { foreach ($masks as $column => $definition) { $data = $this->maskData($data, $column, $definition); } return $data; } /** * @param array $data * @param string $column * @param StrategyDefinition $definition * @return array * @throws \App\Fogger\Mask\Exception\UnknownMaskException */ private function maskData(array $data, string $column, StrategyDefinition $definition): array { foreach ($data as $key => $row) { $data[$key] = $this->maskRow($row, $column, $definition); } return $data; } /** * @param array $row * @param string $column * @param StrategyDefinition $definition * @return array * @throws \App\Fogger\Mask\Exception\UnknownMaskException */ private function maskRow(array $row, string $column, StrategyDefinition $definition): array { $row[$column] = $this->maskStrategyProvider->getMask($definition->getName()) ->apply($row[$column], $definition->getOptions()); return $row; } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Data/DataCopier.php
src/Fogger/Data/DataCopier.php
<?php namespace App\Fogger\Data; use App\Fogger\Data\Writer\ChunkWriterProvider; class DataCopier { private $chunkReader; private $masker; private $chunkWriterProvider; public function __construct( ChunkReader $chunkReader, Masker $masker, ChunkWriterProvider $chunkWriterchunkWriterProvider ) { $this->chunkReader = $chunkReader; $this->masker = $masker; $this->chunkWriterProvider = $chunkWriterchunkWriterProvider; } /** * @param ChunkMessage $chunkMessage * @throws \App\Fogger\Mask\Exception\UnknownMaskException * @throws \App\Fogger\Subset\Exception\UnknownSubsetStrategyException * @throws Writer\Exception\ChunkWriterNotFound */ public function copyDataChunk(ChunkMessage $chunkMessage) { $data = $this->chunkReader->getDataChunk($chunkMessage); $table = $chunkMessage->getTable(); $this->chunkWriterProvider->getWriter()->insert( $table->getName(), $this->masker->applyMasks($data, $table->getMasks()) ); } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Data/ChunkError.php
src/Fogger/Data/ChunkError.php
<?php namespace App\Fogger\Data; use Predis\Client; class ChunkError { const CHUNKS_ERROR = 'fogger::chunks_error'; private $redis; public function __construct(Client $redis) { $this->redis = $redis; } public function reset(): void { $this->redis->set(self::CHUNKS_ERROR, ''); } public function addError(string $errorMessage): void { $this->redis->append(self::CHUNKS_ERROR, trim($errorMessage) . "\n"); } public function getError(): string { return (string)trim($this->redis->get(self::CHUNKS_ERROR)); } public function hasError(): bool { return $this->redis->get(self::CHUNKS_ERROR) !== ''; } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Data/ChunkProducer.php
src/Fogger/Data/ChunkProducer.php
<?php namespace App\Fogger\Data; use App\Fogger\Recipe\Recipe; use App\Fogger\Recipe\Table; class ChunkProducer { private $sourceQuery; private $chunkCache; private $chunkError; public function __construct( SourceQuery $sourceQuery, ChunkCache $chunkCache, ChunkError $chunkError ) { $this->sourceQuery = $sourceQuery; $this->chunkCache = $chunkCache; $this->chunkError = $chunkError; } /** * @param Table $table * @throws \App\Fogger\Subset\Exception\UnknownSubsetStrategyException */ private function queueTableChunks(Table $table) { if (null === $table->getSortBy()) { $this->sourceQuery->getAllKeysQuery($table); $this->chunkCache->pushMessage($table); return; } $result = $this->sourceQuery->getAllKeysQuery($table)->execute(); $counter = 0; $keys = []; while ($key = $result->fetchColumn()) { $keys[] = $key; $counter++; if (0 === $counter % $table->getChunkSize()) { $this->chunkCache->pushMessage($table, $keys); $keys = []; } } if (0 !== $counter % $table->getChunkSize()) { $this->chunkCache->pushMessage($table, $keys); } } /** * @param Recipe $recipe * @throws \App\Fogger\Subset\Exception\UnknownSubsetStrategyException */ public function run(Recipe $recipe) { $this->chunkCache->reset(); $this->chunkError->reset(); foreach ($recipe->getTables() as $table) { $this->queueTableChunks($table); } } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Data/ChunkMessage.php
src/Fogger/Data/ChunkMessage.php
<?php namespace App\Fogger\Data; use App\Fogger\Recipe\Table; class ChunkMessage { const DEFAULT_CHUNK_SIZE = 2000; private $table; private $keys; public function __construct(Table $table, array $keys) { $this->table = $table; $this->keys = $keys; } public function getTable(): Table { return $this->table; } public function getKeys(): array { return $this->keys; } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Data/Writer/MysqlInfileWriter.php
src/Fogger/Data/Writer/MysqlInfileWriter.php
<?php namespace App\Fogger\Data\Writer; use Doctrine\DBAL\Connection; use Exception; class MysqlInfileWriter implements ChunkWriterInterface { private $target; private $cacheDir; public function __construct(Connection $target, string $cacheDir) { $this->target = $target; $this->cacheDir = $cacheDir; } private function forgeTempFilename() { return sprintf('%s/%s.txt', $this->cacheDir, uniqid()); } /** * @param string $table * @param array $inserts * @throws \Doctrine\DBAL\DBALException */ private function loadInfile(string $table, array $inserts) { $filename = $this->forgeTempFilename(); file_put_contents($filename, implode("\n", $inserts)); $this->target->exec( sprintf( "LOAD DATA LOCAL INFILE '%s' INTO TABLE %s", $filename, $table ). " FIELDS TERMINATED BY ',' ENCLOSED BY '\'' LINES TERMINATED BY '\n' STARTING BY ''" ); unlink($filename); } private function forgeRow(array $row): string { return implode( ',', array_map( function ($item) { return $item === null ? '\N' : $this->target->quote($item); }, $row ) ); } /** * @param string $table * @param array $data * @throws Exception */ public function insert(string $table, array $data) { $inserts = []; foreach ($data as $row) { $inserts[] = $this->forgeRow($row); } $this->loadInfile($table, $inserts); } public function isApplicable(): bool { return $this->target->getDriver()->getName() === 'pdo_mysql'; } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Data/Writer/GenericInsertWriter.php
src/Fogger/Data/Writer/GenericInsertWriter.php
<?php namespace App\Fogger\Data\Writer; use Doctrine\DBAL\Connection; class GenericInsertWriter implements ChunkWriterInterface { const FLUSH_RATE = 1000; private $target; private $inserts = []; public function __construct(Connection $target) { $this->target = $target; } /** * @throws \Doctrine\DBAL\DBALException */ private function flush() { if (!count($this->inserts)) { return; } $this->target->beginTransaction(); foreach ($this->inserts as $insert) { $this->target->exec($insert); } $this->target->commit(); $this->inserts = []; } /** * @param string $table * @param array $data * @throws \Doctrine\DBAL\DBALException */ public function insert(string $table, array $data) { $counter = 0; $queryBuilder = $this->target->createQueryBuilder(); $this->inserts = []; foreach ($data as $row) { $this->inserts[] = $queryBuilder ->insert($this->target->quoteIdentifier($table)) ->values( array_combine( array_map( function ($key) { return $this->target->quoteIdentifier($key); }, array_keys($row) ), array_map( function ($value) { return $value === null ? 'null' : $this->target->quote($value); }, $row ) ) )->getSQL(); if (!(++$counter % self::FLUSH_RATE)) { $this->flush(); } } $this->flush(); } public function isApplicable(): bool { return true; } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Data/Writer/ChunkWriterInterface.php
src/Fogger/Data/Writer/ChunkWriterInterface.php
<?php namespace App\Fogger\Data\Writer; interface ChunkWriterInterface { public function insert(string $table, array $data); public function isApplicable(): bool; }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Data/Writer/ChunkWriterProvider.php
src/Fogger/Data/Writer/ChunkWriterProvider.php
<?php namespace App\Fogger\Data\Writer; use App\Fogger\Data\Writer\Exception\ChunkWriterNotFound; class ChunkWriterProvider { /** @var ChunkWriterInterface[] */ private $chunkWriters; public function __construct(iterable $writers) { foreach ($writers as $writer) { $this->addWriter($writer); } } private function addWriter(ChunkWriterInterface $chunkWriter) { $this->chunkWriters[] = $chunkWriter; } /** * @return ChunkWriterInterface * @throws ChunkWriterNotFound */ public function getWriter(): ChunkWriterInterface { foreach ($this->chunkWriters as $chunkWriter) { if ($chunkWriter->isApplicable()) { return $chunkWriter; } } throw new ChunkWriterNotFound('Adapter that could write data could not be found'); } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Data/Writer/Exception/ChunkWriterNotFound.php
src/Fogger/Data/Writer/Exception/ChunkWriterNotFound.php
<?php namespace App\Fogger\Data\Writer\Exception; class ChunkWriterNotFound extends \Exception { }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Recipe/RecipeFactory.php
src/Fogger/Recipe/RecipeFactory.php
<?php namespace App\Fogger\Recipe; use App\Config\ConfigLoader; use App\Fogger\Data\ChunkMessage; use Doctrine\DBAL\Connection; class RecipeFactory { private $configLoader; private $sourceSchema; private $recipeTableFactory; private $maskReplicator; public function __construct( ConfigLoader $configLoader, Connection $connection, RecipeTableFactory $recipeTableFactory, MaskReplicator $maskReplicator ) { $this->configLoader = $configLoader; $this->sourceSchema = $connection->getSchemaManager(); $this->recipeTableFactory = $recipeTableFactory; $this->maskReplicator = $maskReplicator; } /** * @param string $configFilename * @param int $chunkSize * @return Recipe * @throws \Doctrine\DBAL\DBALException */ public function createRecipe(string $configFilename, int $chunkSize = ChunkMessage::DEFAULT_CHUNK_SIZE) { $config = $this->configLoader->load($configFilename); $recipe = new Recipe($config->getExcludes()); foreach ($this->sourceSchema->listTables() as $dbalTable) { $tableName = $dbalTable->getName(); if (!in_array($tableName, $config->getExcludes())) { $recipe->addTable( $tableName, $this->recipeTableFactory->createRecipeTable($dbalTable, $chunkSize, $config->getTable($tableName)) ); } } $this->maskReplicator->replicateMasksToRelatedColumns($recipe); return $recipe; } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Recipe/Table.php
src/Fogger/Recipe/Table.php
<?php namespace App\Fogger\Recipe; class Table { private $name; private $sortBy; private $subset; private $masks = []; private $chunkSize; public function __construct(string $name, int $chunkSize, ?string $sortBy, StrategyDefinition $subset) { $this->name = $name; $this->sortBy = $sortBy; $this->subset = $subset; $this->chunkSize = $chunkSize; } public function getName(): string { return $this->name; } public function getSortBy(): ?string { return $this->sortBy; } public function getSubset(): StrategyDefinition { return $this->subset; } /** * @return StrategyDefinition[] */ public function getMasks(): array { return $this->masks; } public function addMask(string $column, StrategyDefinition $mask) { $this->masks[$column] = $mask; } public function getSubsetName(): string { return $this->getSubset()->getName(); } public function getChunkSize(): int { return $this->chunkSize; } public function setChunkSize(int $chunkSize): void { $this->chunkSize = $chunkSize; } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Recipe/RecipeTableFactory.php
src/Fogger/Recipe/RecipeTableFactory.php
<?php namespace App\Fogger\Recipe; use Doctrine\DBAL\Schema as DBAL; use App\Config\Model as Config; class RecipeTableFactory { private function addMask(Table $table, Config\ColumnConfig $column, $columnName): void { if ($column->getMaskStrategy() != Config\ColumnConfig::NONE_STRATEGY) { $table->addMask( $columnName, new StrategyDefinition($column->getMaskStrategy(), $column->getOptions()) ); } } /** * @param DBAL\Table $table * @return null|string * @throws \Doctrine\DBAL\DBALException */ private function findSortBy(DBAL\Table $table): ?string { if ($table->getPrimaryKey() && 1 === count($table->getPrimaryKeyColumns())) { return $table->getPrimaryKeyColumns()[0]; } foreach ($table->getIndexes() as $index) { if ($index->isUnique() && 1 === count($index->getColumns())) { return $index->getColumns()[0]; } } return null; } /** * @param DBAL\Table $dbalTable * @param int $chunkSize * @param Config\TableConfig|null $tableConfig * @return Table * @throws \Doctrine\DBAL\DBALException */ public function createRecipeTable( DBAL\Table $dbalTable, int $chunkSize, Config\TableConfig $tableConfig = null ): Table { if ($tableConfig && $subsetStrategy = $tableConfig->getSubsetStrategy()) { $subset = new StrategyDefinition($subsetStrategy, $tableConfig->getSubsetOptions()); } $table = new Table( $dbalTable->getName(), $chunkSize, $this->findSortBy($dbalTable), $subset ?? new StrategyDefinition('noSubset') ); if (!$tableConfig) { return $table; } foreach ($tableConfig->getColumns() as $key => $column) { $this->addMask($table, $column, $key); } return $table; } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Recipe/MaskReplicator.php
src/Fogger/Recipe/MaskReplicator.php
<?php namespace App\Fogger\Recipe; use App\Fogger\Schema\RelationGroups\GrouppedRelationColumns; use App\Fogger\Schema\RelationGroups\RelationColumn; use App\Fogger\Schema\RelationGroupsFactory; class MaskReplicator { private $relationGroups; public function __construct(RelationGroupsFactory $relationGroupsFactory) { $this->relationGroups = $relationGroupsFactory->createFromDBAL(); } private function replicateMask( GrouppedRelationColumns $group, StrategyDefinition $mask, Recipe $recipe ) { /** @var RelationColumn $relationColumn */ foreach ($group->getColumns() as $relationColumn) { $table = $recipe->getTable($relationColumn->getTable()); $table->addMask(implode('|', $relationColumn->getColumns()), $mask); } } private function replicateMasksInTable(Table $table, Recipe $recipe) { foreach ($table->getMasks() as $column => $mask) { if (null === $group = $this->relationGroups ->getGroupByTableAndColumn($table->getName(), $column)) { continue; } $this->replicateMask($group, $mask, $recipe); } } public function replicateMasksToRelatedColumns(Recipe $recipe) { foreach ($recipe->getTables() as $table) { $this->replicateMasksInTable($table, $recipe); } } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Recipe/Recipe.php
src/Fogger/Recipe/Recipe.php
<?php namespace App\Fogger\Recipe; class Recipe { private $tables = []; private $excludes; public function __construct(array $excludes) { $this->excludes = $excludes; } public function getTables(): array { return $this->tables; } public function getExcludes(): array { return $this->excludes; } public function addTable(string $name, Table $table) { $this->tables[$name] = $table; } public function getTable(string $name) { return $this->tables[$name] ?? null; } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Recipe/StrategyDefinition.php
src/Fogger/Recipe/StrategyDefinition.php
<?php namespace App\Fogger\Recipe; class StrategyDefinition { private $name; private $options; /** * StrategyDefinition constructor. * @param $name * @param $options */ public function __construct(string $name, array $options = []) { $this->name = $name; $this->options = $options; } public function getName(): string { return $this->name; } public function getOptions(): array { return $this->options; } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Command/FinishCommand.php
src/Command/FinishCommand.php
<?php namespace App\Command; use App\Config\ConfigLoader; use App\Fogger\Data\ChunkCache; use App\Fogger\Data\ChunkError; use App\Fogger\Recipe\RecipeFactory; use App\Fogger\Refine\Refiner; use App\Fogger\Schema\SchemaManipulator; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; class FinishCommand extends Command { protected $schemaManipulator; protected $chunkCache; protected $chunkError; protected $recipeFactory; protected $recipe = null; private $refiner; public function __construct( SchemaManipulator $schemaManipulator, Refiner $refiner, ChunkCache $chunkCache, ChunkError $chunkError, RecipeFactory $recipeFactory ) { $this->schemaManipulator = $schemaManipulator; $this->refiner = $refiner; $this->chunkCache = $chunkCache; $this->chunkError = $chunkError; $this->recipeFactory = $recipeFactory; parent::__construct(); } protected function configure() { $this ->setName('fogger:finish') ->addOption( 'file', 'f', InputOption::VALUE_REQUIRED, 'Where should the command look for a config file. Defaults to fogger.yaml in root folder.', ConfigLoader::DEFAULT_FILENAME ) ->setDescription('Recreates all the indexes and foreign keys in the target'); } protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln('Fogger finish procedure'); $io = new SymfonyStyle($input, $output); if ($this->chunkCache->getProcessedCount() < $this->chunkCache->getPublishedCount()) { $this->outputMessage( sprintf( "We are still working on it, please try again later (%d/%d)", $this->chunkCache->getProcessedCount(), $this->chunkCache->getPublishedCount() ), $io, 'fg=black;bg=yellow' ); return -1; } if ($this->chunkError->hasError()) { $this->outputMessage(sprintf("There has been an error:\n\n%s", $this->chunkError->getError()), $io); return -1; } try { $output->writeln(' - refining database...'); $this->refiner->refine( $this->recipe ?? $this->recipeFactory->createRecipe($input->getOption('file')) ); $output->writeln(' - recreating indexes...'); $this->schemaManipulator->recreateIndexes(); $output->writeln(' - recreating foreign keys...'); $this->schemaManipulator->recreateForeignKeys(); } catch (\Exception $exception) { $this->outputMessage(sprintf("There has been an error:\n\n%s", $exception->getMessage()), $io); return -1; } $this->outputMessage('Data moved, constraints and indexes recreated.', $io, 'fg=black;bg=green'); return 0; } protected function outputMessage(string $message, SymfonyStyle $io, string $style = 'fg=white;bg=red') { $io->block($message, null, $style, ' ', true); } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Command/ConsumerCommand.php
src/Command/ConsumerCommand.php
<?php namespace App\Command; use App\Config\ConfigLoader; use App\Fogger\Data\ChunkCache; use App\Fogger\Data\ChunkConsumer; use App\Fogger\Data\ChunkMessage; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class ConsumerCommand extends Command { private $chunkCache; private $chunkConsumer; public function __construct( ChunkCache $chunkCache, ChunkConsumer $chunkConsumer ) { $this->chunkCache = $chunkCache; $this->chunkConsumer = $chunkConsumer; parent::__construct(); } protected function configure() { $this ->setName('fogger:consumer') ->addOption( 'file', 'f', InputOption::VALUE_REQUIRED, 'Where should the command look for a config file. Defaults to fogger.yaml in root folder.', ConfigLoader::DEFAULT_FILENAME ) ->addOption( 'messages', 'm', InputOption::VALUE_REQUIRED, 'How many messages to process.', 200 ) ->setDescription('Consumes a message'); } protected function execute(InputInterface $input, OutputInterface $output) { for ($i = 0; $i < $input->getOption('messages'); $i++) { /** @var ChunkMessage $message */ $message = $this->chunkCache->popMessage(); if ($message instanceof ChunkMessage) { $this->chunkConsumer->execute($message); } else { echo('.'); usleep(500000); } } } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Command/RunCommand.php
src/Command/RunCommand.php
<?php namespace App\Command; use App\Config\ConfigLoader; use App\Fogger\Data\ChunkCache; use App\Fogger\Data\ChunkError; use App\Fogger\Data\ChunkMessage; use App\Fogger\Data\ChunkProducer; use App\Fogger\Recipe\RecipeFactory; use App\Fogger\Refine\Refiner; use App\Fogger\Schema\SchemaManipulator; use Symfony\Component\Console\Helper\ProgressBar; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; class RunCommand extends FinishCommand { private $chunkProducer; public function __construct( SchemaManipulator $schemaManipulator, ChunkProducer $chunkProducer, RecipeFactory $recipeFactory, Refiner $refiner, ChunkCache $chunkCache, ChunkError $chunkError ) { $this->chunkProducer = $chunkProducer; parent::__construct($schemaManipulator, $refiner, $chunkCache, $chunkError, $recipeFactory); } protected function configure() { $this ->setName('fogger:run') ->addOption( 'file', 'f', InputOption::VALUE_REQUIRED, 'Where should the command look for a config file. Defaults to fogger.yaml in root folder.', ConfigLoader::DEFAULT_FILENAME ) ->addOption( 'chunk-size', 'c', InputOption::VALUE_REQUIRED, sprintf( 'Data is moved in chunks. What should be the size of a chunk. Defaults to %d', ChunkMessage::DEFAULT_CHUNK_SIZE ), ChunkMessage::DEFAULT_CHUNK_SIZE ) ->addOption( 'dont-wait', '', InputOption::VALUE_NONE, 'With this option command will not wait for the workers to finish.' ) ->setDescription('Starts the process of moving data from source to target database. '); } private function showProgressBar(OutputInterface $output) { $published = $this->chunkCache->getPublishedCount(); $output->writeln(''); $output->writeln('If you are masking big database, you can stop this process with Cmd/Ctrl + C'); $output->writeln('Moving data will continue in the background - but in that case, you must manually'); $output->writeln('invoke the fogger:finish command to recreate indexes and foreign keys'); $output->writeln(''); $output->writeln('Moving data in chunks:'); $progressBar = new ProgressBar($output, $published); $progressBar->start(); do { $processed = $this->chunkCache->getProcessedCount(); $progressBar->setProgress($processed); usleep(100000); } while ($processed < $published); $progressBar->finish(); } protected function execute(InputInterface $input, OutputInterface $output) { $io = new SymfonyStyle($input, $output); $output->writeln('Fogger run.'); $chunkSize = (int)$input->getOption('chunk-size'); if ($chunkSize < 1) { $this->outputMessage("There has been an error:\n\nChunk size should be greater than 0", $io); return -1; } try { $this->schemaManipulator->copySchemaDroppingIndexesAndForeignKeys(); $this->recipe = $this->recipeFactory ->createRecipe($input->getOption('file'), $chunkSize); $this->chunkProducer->run($this->recipe); } catch (\Exception $exception) { $this->outputMessage("There has been an error:\n\n".$exception->getMessage(), $io); return -1; } if ($input->getOption('dont-wait')) { $output->writeln(''); $output->writeln( <<<EOT <comment>With dont-wait option the command will only queue data chunks to be processed by the rabbit worker command. Worker runs in background unless you started docker-composer with --scale=worker=0. In order to recreate indexes and foreign keys you will need to manually execute the fogger:finish command after the workers</comment> EOT ); $output->writeln(''); $output->writeln( sprintf('<info>%d chunks have been added to queue</info>', $this->chunkCache->getPublishedCount()) ); return 0; } $this->showProgressBar($output); $output->writeln(''); $output->writeln(''); parent::execute($input, $output); return 0; } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Command/InitCommand.php
src/Command/InitCommand.php
<?php namespace App\Command; use App\Config\ConfigFactory; use App\Config\ConfigLoader; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class InitCommand extends Command { private $configFactory; private $configLoader; public function __construct(ConfigFactory $configFactory, ConfigLoader $configLoader) { $this->configFactory = $configFactory; $this->configLoader = $configLoader; parent::__construct(); } protected function configure() { $this ->setName('fogger:init') ->addOption( 'file', 'f', InputOption::VALUE_REQUIRED, 'Where should the command save the config file. Defaults to fogger.yaml in root folder.', ConfigLoader::DEFAULT_FILENAME ) ->setDescription('Creates configuration boilerplate base on the source DB schema'); } protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln('Fogger init.'); $filename = $input->getOption('file'); try { $this->configLoader->save($this->configFactory->createFromDBAL(), $filename); } catch (\Exception $exception) { $output->writeln('There has been an error: '.$exception->getMessage()); return -1; } $output->writeln('Done! Config boilerplate saved to '.$filename); return 0; } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/public/index.php
public/index.php
<?php use App\Kernel; use Symfony\Component\Debug\Debug; use Symfony\Component\Dotenv\Dotenv; use Symfony\Component\HttpFoundation\Request; require __DIR__.'/../vendor/autoload.php'; // The check is to ensure we don't use .env in production if (!isset($_SERVER['APP_ENV'])) { if (!class_exists(Dotenv::class)) { throw new \RuntimeException('APP_ENV environment variable is not defined. You need to define environment variables for configuration or add "symfony/dotenv" as a Composer dependency to load variables from a .env file.'); } (new Dotenv())->load(__DIR__.'/../.env'); } $env = $_SERVER['APP_ENV'] ?? 'dev'; $debug = (bool) ($_SERVER['APP_DEBUG'] ?? ('prod' !== $env)); if ($debug) { umask(0000); Debug::enable(); } if ($trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? false) { Request::setTrustedProxies(explode(',', $trustedProxies), Request::HEADER_X_FORWARDED_ALL ^ Request::HEADER_X_FORWARDED_HOST); } if ($trustedHosts = $_SERVER['TRUSTED_HOSTS'] ?? false) { Request::setTrustedHosts(explode(',', $trustedHosts)); } $kernel = new Kernel($env, $debug); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/features/bootstrap/ConfigFileContext.php
features/bootstrap/ConfigFileContext.php
<?php use App\Config\ConfigLoader; use Behat\Behat\Context\Context; use Behat\Gherkin\Node\PyStringNode; use Symfony\Component\Yaml\Yaml; class ConfigFileContext implements Context { /** * @Given the file :filename doesn't exist * @param string $filename */ public function theFileDoesntExist(string $filename) { if (file_exists(ConfigLoader::forgePath($filename))) { unlink(ConfigLoader::forgePath($filename)); } } /** * @Then YAML file :filename should be like: * @param string $filename * @param PyStringNode $string * @throws Exception */ public function YamlfileShouldBeLike(string $filename, PyStringNode $string) { if (Yaml::parse(file_get_contents(ConfigLoader::forgePath($filename))) != Yaml::parse($string->getRaw())) { throw new \Exception('File content does not match the template'); } } /** * @Given the config :filename contains: */ public function theConfigTestYamlContains(string $filename, PyStringNode $string) { file_put_contents(ConfigLoader::forgePath($filename), $string->getRaw()); } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/features/bootstrap/CommandContext.php
features/bootstrap/CommandContext.php
<?php use App\Command\InitCommand; use App\Config\ConfigFactory; use App\Config\ConfigLoader; use Behat\Behat\Context\Context; use Behat\Gherkin\Node\TableNode; use Symfony\Bundle\FrameworkBundle\Console\Application; use Symfony\Component\Console\Tester\CommandTester; use Symfony\Component\HttpKernel\KernelInterface; class CommandContext implements Context { const FOGGER_COMMAND_TEMPLATE = 'fogger:%s'; private $application; /** @var CommandTester */ private $tester; public function __construct( KernelInterface $kernel, ConfigFactory $configFactory, ConfigLoader $configLoader ) { $this->application = new Application($kernel); $this->application->add(new InitCommand($configFactory, $configLoader)); } private function foggerName(string $name): string { return sprintf(self::FOGGER_COMMAND_TEMPLATE, $name); } private function runCommand(string $name, array $input = []) { $command = $this->application->find($name); $this->tester = new CommandTester($command); $this->tester->execute(array_merge(['command' => $command->getName()], $input)); } /** * @When I run :name command * @param string $name */ public function iRunCommand(string $name) { $this->runCommand($this->foggerName($name)); } /** * @When I run :name command with input: * @param $name * @param TableNode $table */ public function iRunCommandWithInput($name, TableNode $table) { $this->runCommand( $this->foggerName($name), array_map( function ($item) { return $item === 'true' ? true : $item; }, $table->getRowsHash() ) ); } /** * @Then I should see :text in command's output * @param string $text * @throws Exception */ public function iShouldSeeInCommandsOutput($text) { if (false === strpos($this->tester->getDisplay(), $text)) { throw new \Exception('Text not present in command output'); } } /** * @When the command should exit with code :code * @param int $code * @throws Exception */ public function theCommandShouldExitCode(int $code) { if ($code !== $this->tester->getStatusCode()) { throw new \Exception( sprintf( 'Command exited with %d, %d expected', $this->tester->getStatusCode(), $code ) ); } } /** * @Then print commands output */ public function printCommandsOutput() { dump($this->tester->getDisplay()); } /** * @When worker processes :count task(s) * @param int $count */ public function workerProcessTask(int $count) { $this->runCommand( 'fogger:consumer', [ '--messages' => $count, ] ); } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/features/bootstrap/DatabaseContext.php
features/bootstrap/DatabaseContext.php
<?php use Behat\Behat\Context\Context; use Behat\Gherkin\Node\TableNode; use Doctrine\DBAL\Connection; use Doctrine\DBAL\Schema as Schema; use Doctrine\DBAL\Types\Type; class DatabaseContext implements Context { private $source; private $target; public function __construct(Connection $source, Connection $target) { error_reporting(E_ALL); $this->source = $source; $this->target = $target; } /** * @param Connection $connection * @throws \Doctrine\DBAL\DBALException */ private function dropSchema(Connection $connection) { if ($connection->getDriver()->getName() === 'pdo_mysql') { $connection->exec('SET FOREIGN_KEY_CHECKS = 0;'); } foreach ($connection->getSchemaManager()->listTables() as $table) { $connection->exec( sprintf( 'DROP TABLE %s CASCADE', $connection->quoteIdentifier($table->getName()) ) ); } if ($connection->getDriver()->getName() === 'pdo_mysql') { $connection->exec('SET FOREIGN_KEY_CHECKS = 1;'); } } /** * @Given there is a source database * @throws \Doctrine\DBAL\DBALException */ public function thereIsASourceDatabase() { $this->dropSchema($this->source); } /** * @Given there is an empty target database * @throws \Doctrine\DBAL\DBALException */ public function thereIsAnEmptyTargetDatabase() { $this->dropSchema($this->target); } /** * @Given there is a table :tableName with following columns: * @param $tableName * @param TableNode $tableNode * @throws \Doctrine\DBAL\DBALException */ public function thereIsATableWithFollowingColumns(string $tableName, TableNode $tableNode) { $columns = $pkColumns = $indexes = $uniqueIndexes = []; foreach ($tableNode->getHash() as $row) { $column = $this->createColumn($row); $columns[] = $column; switch ($row['index'] ?? false) { case 'primary': $pkColumns[] = $column->getName(); break; case 'index' : $indexes[] = $column->getName(); break; case 'unique' : $uniqueIndexes[] = $column->getName(); break; } } $table = new Schema\Table($tableName, $columns); if ($pkColumns) { $table->setPrimaryKey($pkColumns); } foreach ($indexes as $index) { $table->addIndex([$index]); } foreach ($uniqueIndexes as $index) { $table->addUniqueIndex([$index]); } $this->source->getSchemaManager()->dropAndCreateTable($table); } /** * @param $row * @return Schema\Column * @throws \Doctrine\DBAL\DBALException */ private function createColumn(array $row): Schema\Column { $column = new Schema\Column($row['name'], Type::getType($row['type'])); $column->setLength($row['length'] ?? null); $column->setComment($row['comment'] ?? ''); $column->setNotnull(($row['nullable'] ?? false) !== 'true'); return $column; } /** * @Given the table :tableName contains following data: * @param string $tableName * @param TableNode $table */ public function theTableTableContainsFollowingData(string $tableName, TableNode $table) { foreach ($table->getHash() as $hash) { $queryBuilder = $this->source->createQueryBuilder(); $queryBuilder ->insert($this->source->quoteIdentifier($tableName)) ->values( array_combine( array_map( function ($key) { return $this->source->quoteIdentifier($key); }, array_keys($hash) ), array_map( function ($value) { return $value === '' ? 'null' : $this->source->quote($value); }, $hash ) ) ) ->execute(); } } /** * @Then the table :tablename in target database should have :expected row(s) * @param string $tablename * @param int $expected * @throws Exception */ public function theTableInTargetDatabaseShouldHaveRows(string $tablename, int $expected) { $queryBuilder = $this->target->createQueryBuilder(); $count = (int)$queryBuilder ->select('count(*)') ->from($this->target->quoteIdentifier($tablename)) ->execute() ->fetchColumn(); if ($count === $expected) { return; } throw new \Exception( sprintf( 'Table contains %d rows, %d expected', $count, $expected ) ); } private function rowInTableExists(string $tablename, array $columns) { $queryBuilder = $this->target->createQueryBuilder(); $queryBuilder ->resetQueryParts() ->select('count(*)') ->from($this->target->quoteIdentifier($tablename)); $counter = 0; foreach ($columns as $key => $value) { if ($value === '') { $queryBuilder->andWhere($queryBuilder->expr()->isNull($key)); continue; } $queryBuilder ->andWhere(sprintf('%s = ?', $this->target->quoteIdentifier($key))) ->setParameter($counter++, $value); } return 0 !== (int)$queryBuilder->execute()->fetchColumn(); } /** * @Then the table :tablename in target database should contain rows: * @param string $tablename * @param TableNode $table * @throws Exception */ public function theTableInTargetDatabaseShouldContainRows(string $tablename, TableNode $table) { foreach ($table->getColumnsHash() as $hash) { if ($this->rowInTableExists($tablename, $hash)) { continue; } throw new \Exception(sprintf('Row %s not found', json_encode($hash))); } } /** * @Then the table :tablename in target database should not contain rows: * @param string $tablename * @param TableNode $table * @throws Exception */ public function theTableInTargetDatabaseShouldNotContainRows(string $tablename, TableNode $table) { foreach ($table->getColumnsHash() as $hash) { if (!$this->rowInTableExists($tablename, $hash)) { continue; } throw new \Exception('row is not in the table'); } } /** * @Given the :local references :foreign * @param string $local * @param string $foreign */ public function theUsersSupervisorReferencesUsersEmail(string $local, string $foreign) { $local = explode('.', $local); $foreign = explode('.', $foreign); $schemaManager = $this->source->getSchemaManager(); $schemaManager->createForeignKey( new Schema\ForeignKeyConstraint([$local[1]], $foreign[0], [$foreign[1]]), $local[0] ); } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/features/bootstrap/ChunkCacheContext.php
features/bootstrap/ChunkCacheContext.php
<?php use App\Fogger\Data\ChunkCache; use Behat\Behat\Context\Context; class ChunkCacheContext implements Context { private $chunkCache; public function __construct(ChunkCache $chunkCache) { $this->chunkCache = $chunkCache; } /** * @param int $value * @param int $expected * @throws Exception */ private function assertCountEquals(int $value, int $expected) { if ($value === $expected) { return; } throw new \Exception( sprintf( 'Counter equals %d, %d expected', $value, $expected ) ); } /** * @Then published tasks counter should equal :expected * @param $expected * @throws Exception */ public function publishedTasksCounterShouldEqual(int $expected) { $this->assertCountEquals($this->chunkCache->getPublishedCount(), $expected); } /** * @Then processed tasks counter should equal :expected * @param $expected * @throws Exception */ public function processedTasksCounterShouldEqual(int $expected) { $this->assertCountEquals($this->chunkCache->getProcessedCount(), $expected); } /** * @Given the task queue is empty */ public function theTaskQueueIsEmpty() { $this->chunkCache->reset(); } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/features/bootstrap/bootstrap.php
features/bootstrap/bootstrap.php
<?php use Symfony\Component\Dotenv\Dotenv; // The check is to ensure we don't use .env in production if (!isset($_SERVER['APP_ENV'])) { if (!class_exists(Dotenv::class)) { throw new \RuntimeException('APP_ENV environment variable is not defined. You need to define environment variables for configuration or add "symfony/dotenv" as a Composer dependency to load variables from a .env file.'); } (new Dotenv())->load(__DIR__.'/../../.env'); }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/spec/Config/TableConfigFactorySpec.php
spec/Config/TableConfigFactorySpec.php
<?php namespace spec\App\Config; use App\Config\ColumnConfigFactory; use App\Config\Model\ColumnConfig; use App\Config\Model\TableConfig; use Doctrine\DBAL\Schema\Column; use Doctrine\DBAL\Schema\Table; use PhpSpec\ObjectBehavior; class TableConfigFactorySpec extends ObjectBehavior { function let(ColumnConfigFactory $columnConfigFactory) { $this->beConstructedWith($columnConfigFactory); } function it_creates_table_config_object_from_dbal_schema_table_instance( Table $table, Column $schemaColumn, ColumnConfigFactory $columnConfigFactory ) { $schemaColumn->getName()->willReturn('column'); $table->getColumns()->willReturn([$schemaColumn]); $columnConfig = new ColumnConfig('none'); $columnConfigFactory->createFromDBALColumn($schemaColumn)->willReturn($columnConfig); $instance = new TableConfig(); $instance->addColumn('column', $columnConfig); $this->createFromDBALTable($table)->shouldBeLike($instance); } function it_creates_table_config_object_from_dbal_schema_table_instance_no_columns(Table $table) { $table->getColumns()->willReturn([]); $instance = new TableConfig(); $this->createFromDBALTable($table)->shouldBeLike($instance); } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/spec/Config/ColumnConfigFactorySpec.php
spec/Config/ColumnConfigFactorySpec.php
<?php namespace spec\App\Config; use App\Config\Model\ColumnConfig; use App\Config\StrategyExtractor; use Doctrine\DBAL\Schema\Column; use PhpSpec\ObjectBehavior; use Prophecy\Argument; class ColumnConfigFactorySpec extends ObjectBehavior { function let(StrategyExtractor $extractor) { $this->beConstructedWith($extractor); } function it_returns_column_config_created_by_extractor(Column $column, StrategyExtractor $extractor) { $instance = new ColumnConfig('none'); $extractor->extract(Argument::any())->willReturn($instance); $this->createFromDBALColumn($column)->shouldBe($instance); } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/spec/Config/StrategyExtractorSpec.php
spec/Config/StrategyExtractorSpec.php
<?php namespace spec\App\Config; use App\Config\Model\ColumnConfig; use PhpSpec\ObjectBehavior; class StrategyExtractorSpec extends ObjectBehavior { function it_returns_column_config_with_none_strategy_for_empty_comment() { $this->extract('')->shouldBeLike(new ColumnConfig('none')); } function it_returns_column_config_with_none_strategy_for_comment_not_maching_template() { $this->extract('some comment')->shouldBeLike(new ColumnConfig('none')); } function it_returns_column_config_with_proper_strategy_for_comment_maching_template() { $this->extract('fogger::strategy')->shouldBeLike(new ColumnConfig('strategy')); } function it_returns_column_config_with_proper_strategy_for_comment_maching_template_with_options() { $this->extract('fogger::strategy{"key": "value"}') ->shouldBeLike(new ColumnConfig('strategy', ['key' => 'value'])); } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/spec/Config/ConfigFactorySpec.php
spec/Config/ConfigFactorySpec.php
<?php namespace spec\App\Config; use App\Config\Model\Config; use App\Config\Model\TableConfig; use App\Config\TableConfigFactory; use Doctrine\DBAL\Connection; use Doctrine\DBAL\Schema\AbstractSchemaManager; use Doctrine\DBAL\Schema\Table; use PhpSpec\ObjectBehavior; class ConfigFactorySpec extends ObjectBehavior { function let(Connection $connection, TableConfigFactory $tableConfigFactory, AbstractSchemaManager $schemaManager) { $connection->getSchemaManager()->willReturn($schemaManager); $this->beConstructedWith($connection, $tableConfigFactory); } function it_creates_config_with_tables_fetched_from_DBAL_schema( Table $table, TableConfigFactory $tableConfigFactory, AbstractSchemaManager $schemaManager ) { $config = new Config(); $tableConfig = new TableConfig(); $config->addTable('table', $tableConfig); $schemaManager->listTables()->willReturn([$table]); $table->getName()->willReturn('table'); $tableConfigFactory->createFromDBALTable($table)->willReturn($tableConfig); $this->createFromDBAL()->shouldBeLike($config); } function it_created_empty_config_when_there_are_no_tables_in_schema(AbstractSchemaManager $schemaManager) { $config = new Config(); $schemaManager->listTables()->willReturn([]); $this->createFromDBAL()->shouldBeLike($config); } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/spec/Config/Serializer/ConfigDenormalizerSpec.php
spec/Config/Serializer/ConfigDenormalizerSpec.php
<?php namespace spec\App\Config\Serializer; use App\Config\Model\Config; use App\Config\Model\TableConfig; use PhpSpec\ObjectBehavior; use Prophecy\Argument; use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; class ConfigDenormalizerSpec extends ObjectBehavior { function let(DenormalizerInterface $denormalizer) { $this->setDenormalizer($denormalizer); } function it_supports_only_denormalization_of_config_class() { $this->supportsDenormalization(Argument::any(), Config::class)->shouldReturn(true); $this->supportsDenormalization(Argument::any(), 'WrongClassName')->shouldReturn(false); } function it_denormalizes_empty_config() { $data = ['tables' => []]; $config = new Config(); $this->denormalize($data, Config::class)->shouldBeLike($config); } function it_denormalizes_config_with_tables(DenormalizerInterface $denormalizer) { $data = [ 'tables' => [ 'table' => [], ], ]; $config = new Config(); foreach ($data['tables'] as $key => $table) { $tableConfig = new TableConfig(); $config->addTable($key, $tableConfig); $denormalizer->denormalize($table, TableConfig::class, Argument::any(), Argument::any()) ->willReturn($tableConfig); } $this->denormalize($data, TableConfig::class)->shouldBeLike($config); } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/spec/Config/Serializer/TableConfigDenormalizerSpec.php
spec/Config/Serializer/TableConfigDenormalizerSpec.php
<?php namespace spec\App\Config\Serializer; use App\Config\Model\ColumnConfig; use App\Config\Model\TableConfig; use PhpSpec\ObjectBehavior; use Prophecy\Argument; use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; class TableConfigDenormalizerSpec extends ObjectBehavior { function let(DenormalizerInterface $denormalizer) { $this->setDenormalizer($denormalizer); } function it_supports_only_denormalization_of_table_config_class() { $this->supportsDenormalization(Argument::any(), TableConfig::class)->shouldReturn(true); $this->supportsDenormalization(Argument::any(), 'WrongClassName')->shouldReturn(false); } function it_denormalizes_data_with_empty_columns_array_and_no_subset_into_table_config_object() { $data = ['columns' => []]; $table = new TableConfig(); $this->denormalize($data, TableConfig::class)->shouldBeLike($table); } function it_denormalizes_data_with_empty_columns_array_and_subset_into_table_config_object() { $data = ['columns' => [], 'subsetStrategy' => 'none', 'subsetOptions' => []]; $table = new TableConfig(); $table->setSubsetStrategy($data['subsetStrategy'], $data['subsetOptions']); $this->denormalize($data, TableConfig::class)->shouldBeLike($table); } function it_denormalizes_data_with_columns_array(DenormalizerInterface $denormalizer) { $data = [ 'columns' => [ 'column' => [], ], ]; $table = new TableConfig(); foreach ($data['columns'] as $key => $col) { $columnConfig = new ColumnConfig(); $table->addColumn($key, $columnConfig); $denormalizer->denormalize($col, ColumnConfig::class, Argument::any(), Argument::any())->willReturn( $columnConfig ); } $this->denormalize($data, TableConfig::class)->shouldBeLike($table); } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/spec/Fogger/Serializer/TableDenormalizerSpec.php
spec/Fogger/Serializer/TableDenormalizerSpec.php
<?php namespace spec\App\Fogger\Serializer; use App\Fogger\Recipe\StrategyDefinition; use App\Fogger\Recipe\Table; use PhpSpec\ObjectBehavior; use Prophecy\Argument; use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; class TableDenormalizerSpec extends ObjectBehavior { function let(DenormalizerInterface $denormalizer) { $this->setDenormalizer($denormalizer); } function it_supports_only_denormalization_of_recipe_table_class_only_from_json() { $this->supportsDenormalization(Argument::any(), Table::class, 'json')->shouldReturn(true); $this->supportsDenormalization(Argument::any(), Table::class, Argument::any())->shouldReturn(false); $this->supportsDenormalization(Argument::any(), 'WrongClassName')->shouldReturn(false); } function it_denormalizes_table_without_masks_specified() { $data = ['name' => 'table', 'chunkSize' => 10, 'sortBy' => null, 'subset' => 'noSubset']; $table = new Table('table', 10, null, new StrategyDefinition('noSubset')); $this->denormalize($data, Table::class, 'json')->shouldBeLike($table); } function it_denormalizes_table_with_subset_strategy_specified(DenormalizerInterface $denormalizer) { $data = ['name' => 'table', 'chunkSize' => 10, 'sortBy' => null, 'subset' => 'subset']; $subsetStrategy = new StrategyDefinition('subset'); $denormalizer->denormalize($data['subset'], StrategyDefinition::class, 'json', [])->willReturn($subsetStrategy); $table = new Table('table', 10, null, $subsetStrategy); $this->denormalize($data, Table::class, 'json')->shouldBeLike($table); } function it_denormalizes_table_with_masks_specified() { $data = [ 'name' => 'table', 'chunkSize' => 10, 'subset' => 'noSubset', 'sortBy' => null, 'masks' => [ 'column' => ['name' => 'mask', 'options' => []], 'other' => ['name' => 'otherMask', 'options' => ['option' => 'value']], ], ]; $table = new Table('table', 10, null, new StrategyDefinition('noSubset')); $table->addMask('column', new StrategyDefinition('mask')); $table->addMask('other', new StrategyDefinition('otherMask', ['option' => 'value'])); $this->denormalize($data, Table::class, 'json')->shouldBeLike($table); } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/spec/Fogger/Mask/HashifyMaskSpec.php
spec/Fogger/Mask/HashifyMaskSpec.php
<?php namespace spec\App\Fogger\Mask; use App\Fogger\Mask\HashifyMask; use App\Fogger\Mask\MaskStrategyInterface; use PhpSpec\ObjectBehavior; use Prophecy\Argument; class HashifyMaskSpec extends ObjectBehavior { function it_should_implement_mask_provider_interface() { $this->shouldHaveType(MaskStrategyInterface::class); } function it_should_supports_hashify() { $this->supports('hashify')->shouldBe(true); $this->supports('wrongName')->shouldBe(false); } function it_should_mask_given_value() { $dummyValue = 'dummyValue'; $this->apply($dummyValue)->shouldBe(md5($dummyValue)); } function it_should_allow_to_specify_template_which_should_be_use_to_generate_response() { $template = 'template %s template'; $dummyValue = 'dummyValue'; $this->apply($dummyValue, ['template' => $template])->shouldBe(sprintf($template, md5($dummyValue))); } function it_should_ignore_null_value() { $this->apply(null)->shouldBe(null); } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/spec/Fogger/Mask/StarifyMaskSpec.php
spec/Fogger/Mask/StarifyMaskSpec.php
<?php namespace spec\App\Fogger\Mask; use App\Fogger\Mask\MaskStrategyInterface; use PhpSpec\ObjectBehavior; class StarifyMaskSpec extends ObjectBehavior { function it_should_implement_mask_provider_interface() { $this->shouldHaveType(MaskStrategyInterface::class); } function it_should_supports_starify() { $this->supports('starify')->shouldBe(true); $this->supports('wrongName')->shouldBe(false); } function it_should_mask_given_value() { $this->apply('dummyValue')->shouldBe('**********'); } function it_should_allow_to_specify_how_many_character_should_be_returned() { $this->apply('dummyValue', ['length' => 2])->shouldBe('**'); } function it_should_ignore_null_value() { $this->apply(null)->shouldBe(null); } }
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
TheSoftwareHouse/fogger
https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/config/bundles.php
config/bundles.php
<?php return [ Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true], Doctrine\Bundle\DoctrineCacheBundle\DoctrineCacheBundle::class => ['all' => true], Doctrine\Bundle\DoctrineBundle\DoctrineBundle::class => ['all' => true], Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle::class => ['all' => true], Snc\RedisBundle\SncRedisBundle::class => ['all' => true], ];
php
MIT
733ebda8ad9bec0a903f8252da8e242525de24f6
2026-01-05T04:45:10.065464Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/_functions.php
src/_functions.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); use Bluz\Common\Collection; use Bluz\Common\Str; use Bluz\Translator\Translator; /** * Simple functions of framework * be careful with this way * * @author Anton Shevchuk */ if (!function_exists('debug')) { /** * Debug variables * * Example of usage * debug(123); * debug(new stdClass()); * debug($_GET, $_POST, $_FILES); * * @codeCoverageIgnore * * @param mixed ...$params */ function debug(...$params) { // check definition if (!getenv('BLUZ_DEBUG') || !isset($_COOKIE['BLUZ_DEBUG'])) { return; } ini_set('xdebug.var_display_max_children', '512'); if (PHP_SAPI === 'cli') { if (extension_loaded('xdebug')) { // try to enable CLI colors ini_set('xdebug.cli_color', '1'); xdebug_print_function_stack(); } else { debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); } var_dump($params); } else { echo '<div class="textleft clear"><pre class="bluz-debug">'; debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); var_dump($params); echo '</pre></div>'; } } } if (!function_exists('esc')) { /** * Escape variable for use in View * * Example of usage * esc($_GET['name']); * esc($_GET['name'], ENT_QUOTES); * * @param string $variable * @param integer $flags * * @return string */ function esc($variable, int $flags = ENT_HTML5) { return htmlentities((string)$variable, $flags, 'UTF-8'); } } if (!function_exists('str_trim_end')) { /** * Added symbol to end of string, trim it before * * @param string $subject * @param string $symbols * * @return string */ function str_trim_end($subject, $symbols) { return rtrim($subject, $symbols) . $symbols; } } if (!function_exists('to_camel_case')) { /** * Convert string to camel case * * @param string $subject * * @return string */ function to_camel_case($subject) { return Str::toCamelCase($subject); } } if (!function_exists('class_namespace')) { /** * Get namespace of class * * @param string $class * * @return string */ function class_namespace($class) { return substr($class, 0, strrpos($class, '\\')); } } if (!function_exists('value')) { /** * Return the value for callable * * @param callable|mixed $value * * @return mixed */ function value($value) { return is_callable($value) ? $value() : $value; } } // @codingStandardsIgnoreStart if (!function_exists('__')) { /** * Translate message * * Example of usage * * // simple * // equal to gettext('Message') * __('Message'); * * // simple replace of one or more argument(s) * // equal to sprintf(gettext('Message to %s'), 'Username') * __('Message to %s', 'Username'); * * @param string $message * @param string[] $text [optional] * * @return string */ function __($message, ...$text) { return Translator::translate($message, ...$text); } } if (!function_exists('_n')) { /** * Translate plural form * * Example of usage * * // plural form + sprintf * // equal to sprintf(ngettext('%d comment', '%d comments', 4), 4) * _n('%d comment', '%d comments', 4, 4) * * // plural form + sprintf * // equal to sprintf(ngettext('%d comment', '%d comments', 4), 4, 'Topic') * _n('%d comment to %s', '%d comments to %s', 4, 'Topic') * * @param string $singular * @param string $plural * @param integer $number * @param string[] $text [optional] * * @return string */ function _n($singular, $plural, $number, ...$text) { return Translator::translatePlural($singular, $plural, $number, ...$text); } } // @codingStandardsIgnoreEnd
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/_loader.php
src/_loader.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); /** * Files in this list is core of framework * use require_once it's really faster than use Loader for it * * Use absolute path `/...` for avoid usage `include_path` for search files * * @author Anton Shevchuk */ // @codeCoverageIgnoreStart // traits require_once __DIR__ . '/Common/Container/Container.php'; require_once __DIR__ . '/Common/Container/JsonSerialize.php'; require_once __DIR__ . '/Common/Container/MagicAccess.php'; require_once __DIR__ . '/Common/Container/RegularAccess.php'; require_once __DIR__ . '/Common/Helper.php'; require_once __DIR__ . '/Common/Nil.php'; require_once __DIR__ . '/Common/Options.php'; require_once __DIR__ . '/Common/Singleton.php'; // application require_once __DIR__ . '/Application/Application.php'; // proxy package require_once __DIR__ . '/Proxy/ProxyTrait.php'; require_once __DIR__ . '/Proxy/Cache.php'; require_once __DIR__ . '/Proxy/Config.php'; require_once __DIR__ . '/Proxy/Logger.php'; require_once __DIR__ . '/Proxy/Messages.php'; require_once __DIR__ . '/Proxy/Response.php'; require_once __DIR__ . '/Proxy/Request.php'; require_once __DIR__ . '/Proxy/Router.php'; require_once __DIR__ . '/Proxy/Session.php'; require_once __DIR__ . '/Proxy/Translator.php'; // packages and support require_once __DIR__ . '/Config/Config.php'; require_once __DIR__ . '/Controller/Controller.php'; require_once __DIR__ . '/Controller/Data.php'; require_once __DIR__ . '/Controller/Meta.php'; require_once __DIR__ . '/Http/RequestMethod.php'; require_once __DIR__ . '/Http/StatusCode.php'; require_once __DIR__ . '/Messages/Messages.php'; require_once __DIR__ . '/Response/Response.php'; require_once __DIR__ . '/Request/RequestFactory.php'; require_once __DIR__ . '/Router/Router.php'; require_once __DIR__ . '/Session/Session.php'; require_once __DIR__ . '/Translator/Translator.php'; require_once __DIR__ . '/View/ViewInterface.php'; require_once __DIR__ . '/View/View.php'; // @codeCoverageIgnoreEnd
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/_translator.php
src/_translator.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); /** * This is file required for poedit parser only * Please, don't use it for anything else * * @author Anton Shevchuk */ // @codeCoverageIgnoreStart /** Validator\Rule\* */ _('is invalid'); _('is required'); _('"%s" is not a valid numeric length'); _('"%s" is not a valid numeric length'); _('"%s" cannot be less than "%s" for validation'); _('must be a float number'); _('must be a string'); _('must be a valid country code'); _('must be a valid Credit Card number'); _('must be a valid date'); _('must be a valid date. Sample format: "%s"'); _('must be a valid domain'); _('must be a valid email address'); _('must be a valid JSON string'); _('must be a valid slug'); _('must be a valid version number'); _('must be an array'); _('must be an integer number'); _('must be an IP address'); _('must be an IP address in the "%s" range'); _('must be between "%1" and "%2"'); _('must be equals "%s"'); _('must be greater than or equals "%s"'); _('must be greater than "%s"'); _('must be identical as "%s"'); _('must be in "%s"'); _('must be inclusive between "%1" and "%2"'); _('must be lower than or equals "%s"'); _('must be lower than "%s"'); _('must be negative'); _('must be numeric'); _('must be positive'); _('must contain the value "%s"'); _('must contain only Latin letters'); _('must contain only Latin letters and "%s"'); _('must contain only Latin letters and digits'); _('must contain only Latin letters, digits and "%s"'); _('must have a length "%d"'); _('must have a length greater than "%d"'); _('must have a length lower than "%d"'); _('must have a length between "%d" and "%d"'); _('must not be empty'); _('must not contain whitespace'); _('must validate with regular expression rule'); // @codeCoverageIgnoreEnd
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Registry/Registry.php
src/Registry/Registry.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Registry; use Bluz\Common\Container; /** * Registry * * @package Bluz\Registry * @author Anton Shevchuk * @link https://github.com/bluzphp/framework/wiki/Registry */ class Registry { use Container\Container; use Container\JsonSerialize; use Container\RegularAccess; }
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Application/Application.php
src/Application/Application.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Application; use Bluz\Application\Exception\ApplicationException; use Bluz\Config\ConfigException; use Bluz\Config\ConfigLoader; use Bluz\Http\Exception\ForbiddenException; use Bluz\Http\Exception\RedirectException; use Bluz\Common; use Bluz\Common\Exception\CommonException; use Bluz\Common\Exception\ComponentException; use Bluz\Controller\Controller; use Bluz\Controller\ControllerException; use Bluz\Proxy\Config; use Bluz\Proxy\Layout; use Bluz\Proxy\Logger; use Bluz\Proxy\Messages; use Bluz\Proxy\Request; use Bluz\Proxy\Response; use Bluz\Proxy\Router; use Bluz\Proxy\Session; use Bluz\Proxy\Translator; use Bluz\Request\RequestFactory; use Bluz\Response\Response as ResponseInstance; use Exception; use InvalidArgumentException; use ReflectionClass; use ReflectionException; use Laminas\Diactoros\ServerRequest; /** * Application * * @package Bluz\Application * @link https://github.com/bluzphp/framework/wiki/Application * @author Anton Shevchuk * @created 06.07.11 16:25 * * @method Controller error(Exception $exception) * @method mixed forbidden(ForbiddenException $exception) * @method null redirect(RedirectException $url) */ class Application { use Common\Helper; use Common\Singleton; /** * @var string Environment name */ protected $environment = 'production'; /** * @var string Application path */ protected $path; /** * @var bool Debug application flag */ protected $debugFlag = false; /** * @var bool Layout usage flag */ protected $layoutFlag = true; /** * Get application environment * * @return string */ public function getEnvironment(): string { return $this->environment; } /** * Get path to Application * * @return string */ public function getPath(): string { if (!$this->path) { if (defined('PATH_APPLICATION')) { $this->path = PATH_APPLICATION; } else { $reflection = new ReflectionClass($this); // 3 level up $this->path = dirname($reflection->getFileName(), 3); } } return $this->path; } /** * Return Debug flag * * @return bool */ public function isDebug(): bool { return $this->debugFlag; } /** * Return/setup Layout Flag * * @param bool|null $flag * * @return bool */ public function useLayout(?bool $flag = null): bool { if (is_bool($flag)) { $this->layoutFlag = $flag; } return $this->layoutFlag; } /** * Initialize system packages * * @param string $environment * * @return void * @throws ApplicationException */ public function init(string $environment = 'production'): void { $this->environment = $environment; try { // initial default helper path $this->addHelperPath(__DIR__ . '/Helper/'); // init Config $this->initConfig(); // first log message Logger::info('app:init'); // init Session, start inside class (if needed) Session::getInstance(); // init Messages Messages::getInstance(); // init Request $this->initRequest(); // init Response $this->initResponse(); // init Translator $this->initTranslator(); // init Router $this->initRouter(); } catch (Exception $e) { throw new ApplicationException("Application can't be loaded: " . $e->getMessage()); } } /** * Initial Request instance * * @return void * @throws ConfigException */ protected function initConfig(): void { $loader = new ConfigLoader(); $loader->setPath($this->getPath()); $loader->setEnvironment($this->getEnvironment()); $loader->load(); $config = new \Bluz\Config\Config(); $config->setFromArray($loader->getConfig()); Config::setInstance($config); // setup configuration for current environment if ($debug = Config::get('debug')) { $this->debugFlag = (bool)$debug; } // initial php settings if ($ini = Config::get('php')) { foreach ($ini as $key => $value) { $result = ini_set($key, $value); Logger::info('app:init:php:' . $key . ':' . ($result ?: '---')); } } } /** * Initial Request instance * * @return void * @throws InvalidArgumentException */ protected function initRequest(): void { $request = RequestFactory::fromGlobals(); Request::setInstance($request); } /** * Initial Response instance * * @return void */ protected function initResponse(): void { $response = new ResponseInstance(); Response::setInstance($response); } /** * Get Response instance * * @return ResponseInstance */ public function getResponse(): ResponseInstance { return Response::getInstance(); } /** * Get Request instance * * @return ServerRequest */ public function getRequest(): ServerRequest { return Request::getInstance(); } /** * Initial Router instance * * @return void */ protected function initRouter(): void { $router = new \Bluz\Router\Router(); $router->setOptions(Config::get('router')); Router::setInstance($router); } /** * Initial Translator instance * * @return void * @throws Common\Exception\ConfigurationException */ protected function initTranslator(): void { $translator = new \Bluz\Translator\Translator(); $translator->setOptions(Config::get('translator')); $translator->init(); Translator::setInstance($translator); } /** * Run application * * @return void */ public function run(): void { $this->process(); $this->render(); $this->end(); } /** * Process application * * Note: * - Why you don't use "X-" prefix for custom headers? * - Because it deprecated ({@link http://tools.ietf.org/html/rfc6648}) * * @return void */ public function process(): void { $this->preProcess(); $this->doProcess(); $this->postProcess(); } /** * Extension point: pre process * * - Router processing * - Analyse request headers * * @return void */ protected function preProcess(): void { Router::process(); // disable Layout for XmlHttpRequests if (Request::isXmlHttpRequest()) { $this->layoutFlag = false; } // switch to JSON response based on Accept header if (Request::checkAccept([Request::TYPE_HTML, Request::TYPE_JSON]) === Request::TYPE_JSON) { $this->layoutFlag = false; Response::setType('JSON'); } } /** * Do process * * - Dispatch controller * - Exceptions handling * - Setup layout * - Setup response body * * @return void */ protected function doProcess(): void { $module = Request::getModule(); $controller = Request::getController(); $params = Request::getParams(); try { // try to dispatch controller $result = $this->dispatch($module, $controller, $params); } catch (ForbiddenException $e) { // dispatch default error controller $result = $this->forbidden($e); } catch (RedirectException $e) { // should return `null` for disable output and setup redirect headers $result = $this->redirect($e); } catch (Exception $e) { // dispatch default error controller $result = $this->error($e); } // setup layout, if needed if ($this->useLayout()) { // render view to layout // needed for headScript and headStyle helpers Layout::setContent($result->render()); Response::setBody(Layout::getInstance()); } else { Response::setBody($result); } } /** * Extension point: post process * * @return void */ protected function postProcess(): void { // nothing } /** * Dispatch controller with params * * Call dispatch from any \Bluz\Package * Application::getInstance()->dispatch($module, $controller, array $params); * * @param string $module * @param string $controller * @param array $params * * @return Controller * @throws CommonException * @throws ComponentException * @throws ControllerException * @throws ReflectionException */ public function dispatch(string $module, string $controller, array $params = []): Controller { $instance = new Controller($module, $controller, $params); Logger::info("app:dispatch:>>>: $module/$controller"); $this->preDispatch($instance); Logger::info("app:dispatch:===: $module/$controller"); $this->doDispatch($instance); Logger::info("app:dispatch:<<<: $module/$controller"); $this->postDispatch($instance); return $instance; } /** * Extension point: pre dispatch * * @param Controller $controller * * @return void */ protected function preDispatch(Controller $controller): void { // check HTTP method $controller->checkHttpMethod(); // check ACL privileges $controller->checkPrivilege(); // check HTTP Accept header $controller->checkHttpAccept(); } /** * Do dispatch * * @param Controller $controller * * @return void * @throws ComponentException * @throws ControllerException * @throws ReflectionException */ protected function doDispatch(Controller $controller): void { // run controller $controller->run(); } /** * Extension point: post dispatch * * @param Controller $controller * * @return void */ protected function postDispatch(Controller $controller): void { // nothing by default } /** * Render send Response * * @return void */ public function render(): void { Response::send(); } /** * Extension point: finally method * * @return void */ public function end(): void { // nothing by default } }
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Application/Exception/ApplicationException.php
src/Application/Exception/ApplicationException.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Application\Exception; use Bluz\Common\Exception\CommonException; /** * Application Exception * * @package Bluz\Application\Exception * @author Anton Shevchuk */ class ApplicationException extends CommonException { }
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Application/Helper/Forbidden.php
src/Application/Helper/Forbidden.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Application\Helper; use Bluz\Application\Application; use Bluz\Http\Exception\ForbiddenException; use Bluz\Controller\Controller; /** * Forbidden helper can be declared inside Bootstrap * * @param ForbiddenException $exception * * @return Controller */ return function (ForbiddenException $exception) { /** * @var Application $this */ return $this->error($exception); };
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Application/Helper/Redirect.php
src/Application/Helper/Redirect.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Application\Helper; use Bluz\Application\Application; use Bluz\Http\Exception\RedirectException; use Bluz\Http\StatusCode; use Bluz\Proxy\Request; use Bluz\Proxy\Response; /** * Redirect helper can be declared inside Bootstrap * * @param RedirectException $exception * * @return null */ return function (RedirectException $exception) { /** * @var Application $this */ $this->useLayout(false); Response::removeHeaders(); Response::clearBody(); if (Request::isXmlHttpRequest()) { Response::setStatusCode(StatusCode::NO_CONTENT); Response::setHeader('Bluz-Redirect', $exception->getUrl()); } else { Response::setStatusCode(StatusCode::FOUND); Response::setHeader('Location', $exception->getUrl()); } return null; };
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Application/Helper/Error.php
src/Application/Helper/Error.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Application\Helper; use Bluz\Application\Application; use Bluz\Common\Exception\CommonException; use Bluz\Common\Exception\ComponentException; use Bluz\Controller\Controller; use Bluz\Controller\ControllerException; use Bluz\Proxy\Response; use Bluz\Proxy\Router; use Exception; use ReflectionException; /** * Reload helper can be declared inside Bootstrap * * @param Exception $exception * * @return Controller * @throws CommonException * @throws ComponentException * @throws ControllerException * @throws ReflectionException */ return function (Exception $exception) { /** * @var Application $this */ Response::removeHeaders(); Response::clearBody(); $module = Router::getErrorModule(); $controller = Router::getErrorController(); $params = ['code' => $exception->getCode(), 'exception' => $exception]; return $this->dispatch($module, $controller, $params); };
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Messages/Messages.php
src/Messages/Messages.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Messages; use ArrayObject; use Bluz\Common\Options; use Bluz\Proxy\Session; use Bluz\Proxy\Translator; use stdClass; /** * Realization of Flash Messages * * @package Bluz\Messages * @author Anton Shevchuk * @link https://github.com/bluzphp/framework/wiki/Messages */ class Messages { use Options; private const TYPE_ERROR = 'error'; private const TYPE_SUCCESS = 'success'; private const TYPE_NOTICE = 'notice'; /** * @var array list of messages types */ protected $types = [ self::TYPE_ERROR, self::TYPE_SUCCESS, self::TYPE_NOTICE ]; /** * Add notice * * @param string $message * @param string[] $text * * @return void * @since 1.0.0 added $text */ public function addNotice(string $message, ...$text): void { $this->add(self::TYPE_NOTICE, $message, ...$text); } /** * Add success * * @param string $message * @param string[] $text * * @return void * @since 1.0.0 added $text */ public function addSuccess(string $message, ...$text): void { $this->add(self::TYPE_SUCCESS, $message, ...$text); } /** * Add error * * @param string $message * @param string[] $text * * @return void * @since 1.0.0 added $text */ public function addError(string $message, ...$text): void { $this->add(self::TYPE_ERROR, $message, ...$text); } /** * Add message to container * * @param string $type One of error, notice or success * @param string $message * @param string[] $text * * @return void */ protected function add(string $type, string $message, ...$text): void { $this->getMessagesStore()[$type][] = Translator::translate($message, ...$text); } /** * Pop a message by type * * @param string $type * * @return stdClass|null */ public function pop(string $type): ?stdClass { $text = array_shift($this->getMessagesStore()[$type]); if ($text) { $message = new stdClass(); $message->text = $text; $message->type = $type; return $message; } return null; } /** * Pop all messages * * @return array */ public function popAll() { $messages = $this->getMessagesStore()->getArrayCopy(); $this->resetMessagesStore(); return $messages; } /** * Get size of messages container * * @return integer */ public function count(): int { $size = 0; if (!$store = $this->getMessagesStore()) { return $size; } foreach ($store as $messages) { $size += count($messages); } return $size; } /** * Reset messages * * @param ArrayObject $store * @return void */ protected function setMessagesStore(ArrayObject $store): void { Session::set('messages:store', $store); } /** * Returns current or new messages store if it not exists * * @return ArrayObject */ protected function getMessagesStore(): ArrayObject { if (!$store = Session::get('messages:store')) { $this->resetMessagesStore(); } return Session::get('messages:store'); } /** * Reset messages * * @return void */ protected function resetMessagesStore(): void { $this->setMessagesStore($this->createEmptyMessagesStore()); } /** * Creates a new empty store for messages * * @return ArrayObject */ protected function createEmptyMessagesStore(): ArrayObject { return new ArrayObject( [ self::TYPE_ERROR => [], self::TYPE_SUCCESS => [], self::TYPE_NOTICE => [] ] ); } }
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Layout/Layout.php
src/Layout/Layout.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Layout; use Bluz\Common\Container\RegularAccess; use Bluz\Common\Exception\CommonException; use Bluz\View\View; use Exception; /** * Layout * * @package Bluz\Layout * @author Anton Shevchuk * @link https://github.com/bluzphp/framework/wiki/Layout * * @method array|null breadCrumbs(array $data = []) * @method string|null headScript(string $src = null, array $attributes = []) * @method string|null headScriptBlock(string $code = null) * @method string|null headStyle(string $href = null, string $media = 'all') * @method string|null link(string $src = null, string $rel = 'stylesheet') * @method string|null meta(string $name = null, string $content = null) * @method string|null title(string $title = null) * @method string titleAppend(string $title, string $separator = ' :: ') * @method string titlePrepend(string $title, string $separator = ' :: ') */ class Layout extends View { use RegularAccess; /** * @var mixed content container, usually is instance of View */ protected $content; /** * Layout constructor * - init Layout helpers * - call parent View constructor * * @throws CommonException */ public function __construct() { // init layout helper path $this->addHelperPath(__DIR__ . '/Helper/'); // init view helper path parent::__construct(); } /** * Get content * * @return View|callable */ public function getContent() { return $this->content; } /** * Set content * * @param View|callable $content * * @return void */ public function setContent($content): void { try { $this->content = value($content); } catch (Exception $e) { $this->content = $e->getMessage(); } } }
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Layout/Helper/Link.php
src/Layout/Helper/Link.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\View\Helper; use Bluz\Layout\Layout; use Bluz\Proxy\Registry; /** * Set or generate <link> code for <head> * * @param array|null $link * * @return string|null */ return function (?array $link = null) { /** * @var Layout $this */ // it's stack for <head> $links = Registry::get('layout:link') ?: []; if (null === $link) { // clear system vars Registry::set('layout:link', []); // prepare to output $tags = array_map( function ($attr) { return '<link ' . $this->attributes($attr) . '/>'; }, $links ); $tags = array_unique($tags); return implode("\n", $tags); } $links[] = $link; Registry::set('layout:link', $links); return null; };
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Layout/Helper/HeadStyle.php
src/Layout/Helper/HeadStyle.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Layout\Helper; use Bluz\Layout\Layout; use Bluz\Proxy\Registry; /** * Set or generate <style> code for <head> * * @param string|null $href * @param string $media * * @return string|null */ return function (?string $href = null, string $media = 'all') { /** * @var Layout $this */ // it's stack for <head> $headStyle = Registry::get('layout:headStyle') ?: []; if (null === $href) { // clear system vars Registry::set('layout:headStyle', []); $tags = []; foreach ($headStyle as $aHref => $aMedia) { $tags[] = $this->style($aHref, $aMedia); } return implode("\n", $tags); } $headStyle[$href] = $media; Registry::set('layout:headStyle', $headStyle); return null; };
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Layout/Helper/Title.php
src/Layout/Helper/Title.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Layout\Helper; use Bluz\Layout\Layout; use Bluz\Proxy\Registry; /** * Set or generate <title> code for <head> * * @param string|null $title * * @return string */ return function (?string $title = null) { // it's stack for <title> tag if (null === $title) { return Registry::get('layout:title'); } Registry::set('layout:title', $title); return $title; };
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Layout/Helper/TitlePrepend.php
src/Layout/Helper/TitlePrepend.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Layout\Helper; use Bluz\Layout\Layout; use Bluz\Proxy\Registry; /** * Set or generate <title> code for <head> * * @param string $title * @param string $separator * * @return string */ return function (string $title, string $separator = ' :: ') { // it's stack for <title> tag $oldTitle = Registry::get('layout:title'); $result = $title . (!$oldTitle ?: $separator . $oldTitle); Registry::set('layout:title', $result); return $result; };
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Layout/Helper/Meta.php
src/Layout/Helper/Meta.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\View\Helper; use Bluz\Proxy\Registry; /** * Set or generate <meta> code for <head> * * @param string|array|null $name * @param string|null $content * * @return string|null */ return function ($name = null, ?string $content = null) { // it's stack for <head> $meta = Registry::get('layout:meta') ?: []; if (null === $name && null === $content) { // clear system vars Registry::set('layout:meta', []); // prepare to output $tags = []; foreach ($meta as $aName => $aContent) { $tags[] = '<meta name="' . $aName . '" ' . 'content="' . htmlspecialchars((string)$aContent, ENT_QUOTES) . '"/>'; } return implode("\n", $tags); } if (null === $name) { // if exists only $content, do nothing return null; } $meta[$name] = $content; Registry::set('layout:meta', $meta); return null; };
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Layout/Helper/TitleAppend.php
src/Layout/Helper/TitleAppend.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Layout\Helper; use Bluz\Layout\Layout; use Bluz\Proxy\Registry; /** * Set or generate <title> code for <head> * * @param string $title * @param string $separator * * @return string */ return function (string $title, string $separator = ' :: ') { // it's stack for <title> tag $oldTitle = Registry::get('layout:title'); $result = (!$oldTitle ?: $oldTitle . $separator) . $title; Registry::set('layout:title', $result); return $result; };
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Layout/Helper/BreadCrumbs.php
src/Layout/Helper/BreadCrumbs.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Layout\Helper; use Bluz\Proxy\Registry; /** * Set or Get Breadcrumbs * * @param array $data * * @return array|null */ return function (array $data = []) { if (empty($data)) { return Registry::get('layout:breadcrumbs'); } Registry::set('layout:breadcrumbs', $data); return null; };
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Layout/Helper/HeadScript.php
src/Layout/Helper/HeadScript.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Layout\Helper; use Bluz\Layout\Layout; use Bluz\Proxy\Registry; /** * Set or generate <script> code for <head> * * @param string|null $src * @param array $attributes * * @return null|string */ return function (?string $src = null, array $attributes = []) { /** * @var Layout $this */ // it's stack for <head> $headScripts = Registry::get('layout:headScripts') ?: []; if (null === $src) { // clear system vars Registry::set('layout:headScripts', []); $tags = []; foreach ($headScripts as $aSrc => $aData) { $tags[] = $this->script($aSrc, $aData); } return implode("\n", $tags); } $headScripts[$src] = $attributes; Registry::set('layout:headScripts', $headScripts); return null; };
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Http/RequestMethod.php
src/Http/RequestMethod.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Http; /** * RequestMethod * * @package Bluz\Http * @author dark */ class RequestMethod { /** * @const string HTTP methods */ public const OPTIONS = 'OPTIONS'; public const GET = 'GET'; public const HEAD = 'HEAD'; public const PATCH = 'PATCH'; public const POST = 'POST'; public const PUT = 'PUT'; public const DELETE = 'DELETE'; public const TRACE = 'TRACE'; public const CONNECT = 'CONNECT'; }
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Http/StatusCode.php
src/Http/StatusCode.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Http; /** * HTTP Status Codes with translation table * * @package Bluz\Http * @author Anton Shevchuk */ class StatusCode { public const CONTINUE = 100; public const SWITCHING_PROTOCOLS = 101; public const PROCESSING = 102; // RFC2518 public const OK = 200; public const CREATED = 201; public const ACCEPTED = 202; public const NON_AUTHORITATIVE_INFORMATION = 203; public const NO_CONTENT = 204; public const RESET_CONTENT = 205; public const PARTIAL_CONTENT = 206; public const MULTI_STATUS = 207; // RFC4918 public const ALREADY_REPORTED = 208; // RFC5842 public const IM_USED = 226; // RFC3229 public const MULTIPLE_CHOICES = 300; public const MOVED_PERMANENTLY = 301; public const FOUND = 302; public const SEE_OTHER = 303; public const NOT_MODIFIED = 304; public const USE_PROXY = 305; public const RESERVED = 306; public const TEMPORARY_REDIRECT = 307; public const PERMANENTLY_REDIRECT = 308; // RFC7238 public const BAD_REQUEST = 400; public const UNAUTHORIZED = 401; public const PAYMENT_REQUIRED = 402; public const FORBIDDEN = 403; public const NOT_FOUND = 404; public const METHOD_NOT_ALLOWED = 405; public const NOT_ACCEPTABLE = 406; public const PROXY_AUTHENTICATION_REQUIRED = 407; public const REQUEST_TIMEOUT = 408; public const CONFLICT = 409; public const GONE = 410; public const LENGTH_REQUIRED = 411; public const PRECONDITION_FAILED = 412; public const REQUEST_ENTITY_TOO_LARGE = 413; public const REQUEST_URI_TOO_LONG = 414; public const UNSUPPORTED_MEDIA_TYPE = 415; public const REQUESTED_RANGE_NOT_SATISFIABLE = 416; public const EXPECTATION_FAILED = 417; public const I_AM_A_TEAPOT = 418; // RFC2324 public const MISDIRECTED_REQUEST = 421; // RFC7540 public const UNPROCESSABLE_ENTITY = 422; // RFC4918 public const LOCKED = 423; // RFC4918 public const FAILED_DEPENDENCY = 424; // RFC4918 public const RESERVED_FOR_WEBDAV_ADVANCED_COLLECTIONS_EXPIRED_PROPOSAL = 425; // RFC2817 public const UPGRADE_REQUIRED = 426; // RFC2817 public const PRECONDITION_REQUIRED = 428; // RFC6585 public const TOO_MANY_REQUESTS = 429; // RFC6585 public const REQUEST_HEADER_FIELDS_TOO_LARGE = 431; // RFC6585 public const UNAVAILABLE_FOR_LEGAL_REASONS = 451; public const INTERNAL_SERVER_ERROR = 500; public const NOT_IMPLEMENTED = 501; public const BAD_GATEWAY = 502; public const SERVICE_UNAVAILABLE = 503; public const GATEWAY_TIMEOUT = 504; public const VERSION_NOT_SUPPORTED = 505; public const VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL = 506; // RFC2295 public const INSUFFICIENT_STORAGE = 507; // RFC4918 public const LOOP_DETECTED = 508; // RFC5842 public const NOT_EXTENDED = 510; // RFC2774 public const NETWORK_AUTHENTICATION_REQUIRED = 511; // RFC6585 /** * Status codes translation table * * The list of codes is complete according to the * {@link http://www.iana.org/assignments/http-status-codes/ Hypertext Transfer Protocol Status Code Registry} * * @var array */ public static $statusTexts = [ 100 => 'Continue', 101 => 'Switching Protocols', 102 => 'Processing', // RFC2518 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 207 => 'Multi-Status', // RFC4918 208 => 'Already Reported', // RFC5842 226 => 'IM Used', // RFC3229 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect', 308 => 'Permanent Redirect', // RFC7238 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Timeout', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Payload Too Large', 414 => 'URI Too Long', 415 => 'Unsupported Media Type', 416 => 'Range Not Satisfiable', 417 => 'Expectation Failed', 418 => 'I\'m a teapot', // RFC2324 421 => 'Misdirected Request', // RFC7540 422 => 'Unprocessable Entity', // RFC4918 423 => 'Locked', // RFC4918 424 => 'Failed Dependency', // RFC4918 425 => 'Reserved for WebDAV advanced collections expired proposal', // RFC2817 426 => 'Upgrade Required', // RFC2817 428 => 'Precondition Required', // RFC6585 429 => 'Too Many Requests', // RFC6585 431 => 'Request Header Fields Too Large', // RFC6585 451 => 'Unavailable For Legal Reasons', // RFC7725 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Timeout', 505 => 'HTTP Version Not Supported', 506 => 'Variant Also Negotiates (Experimental)', // RFC2295 507 => 'Insufficient Storage', // RFC4918 508 => 'Loop Detected', // RFC5842 510 => 'Not Extended', // RFC2774 511 => 'Network Authentication Required', // RFC6585 ]; }
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Http/CacheControl.php
src/Http/CacheControl.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Http; use Bluz\Common\Container\Container; use Bluz\Response\Response; use DateTime; use DateTimeZone; use Exception; /** * HTTP Cache Control * * Wrapper for working with HTTP headers * - Cache-Control * - Last-Modified * - Expires * - ETag * - Age * * @package Bluz\Http * @author Anton Shevchuk * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9 */ class CacheControl { use Container; /** * @var Response instance */ protected $response; /** * Create instance * * @param Response $response */ public function __construct(Response $response) { $this->response = $response; } /** * Prepare Cache-Control header * * @return void */ protected function updateCacheControlHeader(): void { $parts = []; ksort($this->container); foreach ($this->container as $key => $value) { if (true === $value) { $parts[] = $key; } else { if (preg_match('#[^a-zA-Z0-9._-]#', (string)$value)) { $value = '"' . $value . '"'; } $parts[] = "$key=$value"; } } if (count($parts)) { $this->response->setHeader('Cache-Control', implode(', ', $parts)); } } /** * Marks the response as "private". * * It makes the response ineligible for serving other clients. * * @return void */ public function setPrivate(): void { $this->doDeleteContainer('public'); $this->doSetContainer('private', true); $this->updateCacheControlHeader(); } /** * Marks the response as "public". * * It makes the response eligible for serving other clients. * * @return void */ public function setPublic(): void { $this->doDeleteContainer('private'); $this->doSetContainer('public', true); $this->updateCacheControlHeader(); } /** * Returns the number of seconds after the time specified in the response's Date * header when the response should no longer be considered fresh. * * First, it checks for a s-maxage directive, then a max-age directive, and then it falls * back on an expires header. It returns null when no maximum age can be established. * * @return integer|null Number of seconds */ public function getMaxAge(): ?int { if ($this->doContainsContainer('s-maxage')) { return (int)$this->doGetContainer('s-maxage'); } if ($this->doContainsContainer('max-age')) { return (int)$this->doGetContainer('max-age'); } if ($expires = $this->getExpires()) { $expires = DateTime::createFromFormat(DATE_RFC2822, $expires); return (int) $expires->format('U') - date('U'); } return null; } /** * Sets the number of seconds after which the response should no longer be considered fresh. * * This methods sets the Cache-Control max-age directive. * * @param integer $value Number of seconds * * @return void */ public function setMaxAge(int $value): void { $this->doSetContainer('max-age', $value); $this->updateCacheControlHeader(); } /** * Sets the number of seconds after which the response should no longer be considered fresh by shared caches. * * This methods sets the Cache-Control s-maxage directive. * * @param integer $value Number of seconds * * @return void */ public function setSharedMaxAge(int $value): void { $this->setPublic(); $this->doSetContainer('s-maxage', $value); $this->updateCacheControlHeader(); } /** * Returns the response's time-to-live in seconds. * * It returns null when no freshness information is present in the response. * When the responses TTL is <= 0, the response may not be served from cache without first * revalidating with the origin. * * @return integer|null The TTL in seconds */ public function getTtl(): ?int { if ($maxAge = $this->getMaxAge()) { return $maxAge - $this->getAge(); } return null; } /** * Sets the response's time-to-live for shared caches. * * This method adjusts the Cache-Control/s-maxage directive. * * @param integer $seconds Number of seconds * * @return void */ public function setTtl(int $seconds): void { $this->setSharedMaxAge($this->getAge() + $seconds); } /** * Sets the response's time-to-live for private/client caches. * * This method adjusts the Cache-Control/max-age directive. * * @param integer $seconds Number of seconds * * @return void */ public function setClientTtl(int $seconds): void { $this->setMaxAge($this->getAge() + $seconds); } /** * Returns the literal value of the ETag HTTP header * * @return string The ETag HTTP header or null if it does not exist */ public function getEtag(): string { return $this->response->getHeader('ETag'); } /** * Sets the ETag value * * @param string $etag The ETag unique identifier * @param bool $weak Whether you want a weak ETag or not * * @return void */ public function setEtag(string $etag, bool $weak = false): void { $etag = trim($etag, '"'); $this->response->setHeader('ETag', (true === $weak ? 'W/' : '') . '"' . $etag . '"'); } /** * Returns the age of the response * * @return integer The age of the response in seconds */ public function getAge(): int { if ($age = $this->response->getHeader('Age')) { return (int)$age; } return max(time() - date('U'), 0); } /** * Set the age of the response * * @param integer $age * * @return void */ public function setAge(int $age): void { $this->response->setHeader('Age', $age); } /** * Returns the value of the Expires header as a DateTime instance * * @return string A string or null if the header does not exist */ public function getExpires(): string { return $this->response->getHeader('Expires'); } /** * Sets the Expires HTTP header with a DateTime instance * * @param DateTime|string $date A \DateTime instance or date as string * * @return void * @throws Exception */ public function setExpires($date): void { if ($date instanceof DateTime) { $date = clone $date; } else { $date = new DateTime($date); } $date->setTimezone(new DateTimeZone('UTC')); $this->response->setHeader('Expires', $date->format('D, d M Y H:i:s') . ' GMT'); } /** * Returns the Last-Modified HTTP header as a string * * @return string A string or null if the header does not exist */ public function getLastModified(): string { return $this->response->getHeader('Last-Modified'); } /** * Sets the Last-Modified HTTP header with a DateTime instance or string * * @param DateTime|string $date A \DateTime instance or date as string * * @return void * @throws Exception */ public function setLastModified($date): void { if ($date instanceof DateTime) { $date = clone $date; } else { $date = new DateTime($date); } $date->setTimezone(new DateTimeZone('UTC')); $this->response->setHeader('Last-Modified', $date->format('D, d M Y H:i:s') . ' GMT'); } /** * Marks the response stale by setting the Age header to be equal to the maximum age of the response * * @return void */ public function expire(): void { if ($this->getTtl() > 0) { $this->setAge($this->getMaxAge()); } } }
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Http/Exception/ForbiddenException.php
src/Http/Exception/ForbiddenException.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Http\Exception; use Bluz\Http\StatusCode; /** * Forbidden Exception * * @package Bluz\Http\Exception * @author Anton Shevchuk */ class ForbiddenException extends HttpException { /** * @var integer HTTP Code */ protected $code = StatusCode::FORBIDDEN; }
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Http/Exception/UnauthorizedException.php
src/Http/Exception/UnauthorizedException.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Http\Exception; use Bluz\Http\StatusCode; /** * Unauthorized Exception * * @package Bluz\Http\Exception * @author Anton Shevchuk */ class UnauthorizedException extends HttpException { /** * @var integer HTTP code */ protected $code = StatusCode::UNAUTHORIZED; }
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Http/Exception/NotFoundException.php
src/Http/Exception/NotFoundException.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Http\Exception; use Bluz\Http\StatusCode; /** * NotFound Exception * * @package Bluz\Http\Exception * @author Anton Shevchuk */ class NotFoundException extends HttpException { /** * @var integer HTTP Code */ protected $code = StatusCode::NOT_FOUND; }
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Http/Exception/NotAllowedException.php
src/Http/Exception/NotAllowedException.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Http\Exception; use Bluz\Http\StatusCode; /** * Not Allowed Exception * * @package Bluz\Http\Exception * @author Anton Shevchuk */ class NotAllowedException extends HttpException { /** * @var integer HTTP Code */ protected $code = StatusCode::METHOD_NOT_ALLOWED; }
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Http/Exception/NotImplementedException.php
src/Http/Exception/NotImplementedException.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Http\Exception; use Bluz\Http\StatusCode; /** * NotImplemented Exception * * @package Bluz\Http\Exception * @author Anton Shevchuk */ class NotImplementedException extends HttpException { /** * @var integer HTTP code */ protected $code = StatusCode::NOT_IMPLEMENTED; }
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Http/Exception/NotAcceptableException.php
src/Http/Exception/NotAcceptableException.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Http\Exception; use Bluz\Http\StatusCode; /** * Not Acceptable Exception * * @package Bluz\Http\Exception * @author Anton Shevchuk */ class NotAcceptableException extends HttpException { /** * @var integer HTTP Code */ protected $code = StatusCode::NOT_ACCEPTABLE; }
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Http/Exception/HttpException.php
src/Http/Exception/HttpException.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Http\Exception; use Bluz\Common\Exception\CommonException; use Bluz\Http\StatusCode; /** * HttpException * * @package Bluz\Http\Exception * @author Anton Shevchuk */ class HttpException extends CommonException { /** * Return HTTP Status Message * * @return string */ public function getStatus(): string { return StatusCode::$statusTexts[$this->code]; } }
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Http/Exception/RedirectException.php
src/Http/Exception/RedirectException.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Http\Exception; use Bluz\Http\StatusCode; /** * Redirect Exception * * @package Bluz\Http\Exception * @author Anton Shevchuk */ class RedirectException extends HttpException { /** * Redirect HTTP code * * - 301 Moved Permanently * - 302 Moved Temporarily / Found * - 307 Temporary Redirect * * @var integer */ protected $code = StatusCode::FOUND; /** * @var string */ protected $url; /** * Set Url to Redirect * * @param string $url */ public function setUrl($url): void { $this->url = $url; } /** * getUrl * * @return string */ public function getUrl(): string { return $this->url; } }
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Http/Exception/BadRequestException.php
src/Http/Exception/BadRequestException.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Http\Exception; use Bluz\Http\StatusCode; /** * BadRequest Exception * * @package Bluz\Http\Exception * @author Anton Shevchuk */ class BadRequestException extends HttpException { /** * @var integer HTTP Code */ protected $code = StatusCode::BAD_REQUEST; }
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Controller/Controller.php
src/Controller/Controller.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Controller; use Bluz\Application\Application; use Bluz\Auth\IdentityInterface; use Bluz\Common\Exception\CommonException; use Bluz\Common\Exception\ComponentException; use Bluz\Common\Helper; use Bluz\Http\Exception\ForbiddenException; use Bluz\Proxy\Cache; use Bluz\Proxy\Logger; use Bluz\Response\ResponseTrait; use Bluz\View\View; use Closure; use Exception; use JsonSerializable; use ReflectionException; /** * Statement * * @package Bluz\Controller * @author Anton Shevchuk * * @method void attachment(string $file) * @method void checkHttpAccept() * @method void checkHttpMethod() * @method void checkPrivilege() * @method void denied() * @method void disableLayout() * @method void disableView() * @method Controller dispatch(string $module, string $controller, array $params = []) * @method void redirect(string $url) * @method void redirectTo(string $module, string $controller, array $params = []) * @method void reload() * @method bool isAllowed($privilege) * @method void useJson() * @method void useLayout($layout) * @method IdentityInterface user() */ class Controller implements JsonSerializable { use Helper; use ResponseTrait; /** * @var string */ protected $module; /** * @var string */ protected $controller; /** * @var array */ protected $params; /** * @var string Cache key */ protected $key; /** * @var string Template name, by default is equal to controller name */ protected $template; /** * @var string */ protected $file; /** * @var Meta */ protected $meta; /** * @var Data */ protected $data; /** * Constructor of Statement * * @param string $module * @param string $controller * @param array $params * * @throws CommonException */ public function __construct(string $module, string $controller, array $params = []) { // initial default helper path $this->addHelperPath(__DIR__ . '/Helper/'); $this->setModule($module); $this->setController($controller); $this->setParams($params); $this->setTemplate($controller . '.phtml'); $this->key = "data.$module.$controller." . md5(http_build_query($params)); } /** * @return string */ public function getModule(): string { return $this->module; } /** * @param string $module */ protected function setModule(string $module): void { $this->module = $module; } /** * @return string */ public function getController(): string { return $this->controller; } /** * @param string $controller */ protected function setController(string $controller): void { $this->controller = $controller; } /** * @return array */ public function getParams(): array { return $this->params; } /** * @param array $params */ protected function setParams(array $params): void { $this->params = $params; } /** * @return string */ public function getTemplate(): ?string { return $this->template; } /** * @param string $template */ protected function setTemplate(string $template): void { $this->template = $template; } /** * Run controller logic * * @return Data * @throws ComponentException * @throws ControllerException * @throws ReflectionException */ public function run(): Data { if (!$this->loadData()) { $this->process(); $this->saveData(); } return $this->data; } /** * Controller run * * @return Data * @throws ComponentException * @throws ControllerException * @throws ReflectionException */ protected function process(): Data { // initial variables for use inside controller $module = $this->module; $controller = $this->controller; $params = $this->params; /** * @var Closure $controllerClosure */ $controllerClosure = include $this->getFile(); if (!is_callable($controllerClosure)) { throw new ControllerException("Controller is not callable '{$module}/{$controller}'"); } // process params $params = $this->getMeta()->params($params); // call Closure or Controller $result = $controllerClosure(...$params); // switch statement for result of Closure run switch (true) { case ($result === false): // return "false" is equal to disable view and layout $this->disableLayout(); $this->disableView(); break; case is_string($result): // return string variable is equal to change view template $this->setTemplate($result); break; case is_array($result): // return associative array is equal to setup view data $this->getData()->setFromArray($result); break; case ($result instanceof self): // return Controller - just extract data from it $this->getData()->setFromArray($result->getData()->toArray()); break; } return $this->getData(); } /** * Setup controller file * * @return void * @throws ControllerException */ protected function findFile(): void { $path = Application::getInstance()->getPath(); $file = "$path/modules/{$this->module}/controllers/{$this->controller}.php"; if (!file_exists($file)) { throw new ControllerException("Controller file not found '{$this->module}/{$this->controller}'", 404); } $this->file = $file; } /** * Get controller file path * * @return string * @throws ControllerException */ protected function getFile(): string { if (!$this->file) { $this->findFile(); } return $this->file; } /** * Retrieve reflection for anonymous function * * @return void * @throws ComponentException * @throws ControllerException * @throws ReflectionException */ protected function initMeta(): void { // cache for reflection data $cacheKey = "meta.{$this->module}.{$this->controller}"; if (!$meta = Cache::get($cacheKey)) { $meta = new Meta($this->getFile()); $meta->process(); Cache::set( $cacheKey, $meta, Cache::TTL_NO_EXPIRY, ['system', 'meta'] ); } $this->meta = $meta; } /** * Get meta information * * @return Meta * @throws ControllerException * @throws ComponentException * @throws ReflectionException */ public function getMeta(): Meta { if (!$this->meta) { $this->initMeta(); } return $this->meta; } /** * Assign key/value pair to Data object * * @param string $key * @param mixed $value * * @return void */ public function assign(string $key, $value): void { $this->getData()->set($key, $value); } /** * Get controller Data container * * @return Data */ public function getData(): Data { if (!$this->data) { $this->data = new Data(); } return $this->data; } /** * Load Data from cache * * @return bool * @throws ComponentException * @throws ControllerException * @throws ReflectionException */ private function loadData(): bool { $cacheTime = $this->getMeta()->getCache(); if ($cacheTime && $cached = Cache::get($this->key)) { $this->data = $cached; return true; } return false; } /** * Save Data to cache * * @return bool * @throws ComponentException * @throws ControllerException * @throws ReflectionException */ private function saveData(): bool { if ($cacheTime = $this->getMeta()->getCache()) { return Cache::set( $this->key, $this->getData(), $cacheTime, ['system', 'data'] ); } return false; } /** * Specify data which should be serialized to JSON * * @return Data */ public function jsonSerialize() { return $this->getData(); } /** * Magic cast to string * * @return string */ public function __toString() { if (!$this->template) { return ''; } try { // $view for use in closure $view = new View(); $path = Application::getInstance()->getPath(); // setup additional helper path $view->addHelperPath($path . '/layouts/helpers'); // setup additional partial path $view->addPartialPath($path . '/layouts/partial'); // setup default path $view->setPath($path . '/modules/' . $this->module . '/views'); // setup template $view->setTemplate($this->template); // setup data $view->setFromArray($this->getData()->toArray()); return $view->render(); } catch (Exception $e) { // save log Logger::exception($e); return ''; } } }
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Controller/Data.php
src/Controller/Data.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Controller; use Bluz\Common\Container\ArrayAccess; use Bluz\Common\Container\Container; use Bluz\Common\Container\JsonSerialize; use Bluz\Common\Container\MagicAccess; use Bluz\Common\Container\RegularAccess; /** * Data * * @package Bluz\Controller * @author Anton Shevchuk */ class Data implements \JsonSerializable, \ArrayAccess { use ArrayAccess; use Container; use MagicAccess; use RegularAccess; use JsonSerialize; }
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Controller/Meta.php
src/Controller/Meta.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Controller; use Bluz\Common\Exception\ComponentException; use Bluz\Common\Options; use Bluz\Proxy\Request; use Closure; use ReflectionException; /** * Meta information from reflection of the function * * @package Bluz\Controller * @author Anton Shevchuk */ class Meta { use Options; /** * @var string full path to file */ protected $file; /** * @var integer cache TTL */ protected $cache = 0; /** * @var array list of Accept */ protected $accept = []; /** * @var array list of Acl */ protected $acl = []; /** * @var array list of HTTP methods */ protected $method = []; /** * @var array described params */ protected $params = []; /** * @var string privilege */ protected $privilege; /** * @var array routers */ protected $route = []; /** * @var array default values of params */ protected $values = []; /** * Constructor of Reflection * * @param string $file */ public function __construct($file) { $this->file = $file; } /** * Set state required for working with var_export (used inside PHP File cache) * * @param array $array * * @return Meta */ public static function __set_state($array) { $instance = new Meta($array['file']); foreach ($array as $key => $value) { $instance->{$key} = $value; } return $instance; } /** * Process to get reflection from file * * @return void * @throws ComponentException * @throws ReflectionException */ public function process(): void { /** @var Closure|object $closure */ $closure = include $this->file; if (!is_callable($closure)) { throw new ComponentException("There is no callable structure in file `{$this->file}`"); } $reflection = new \ReflectionFunction($closure); // check and normalize params by doc comment $docComment = $reflection->getDocComment(); // get all options by one regular expression if (preg_match_all('/\s*\*\s*\@([a-z0-9-_]+)\s+(.*).*\s+/i', $docComment, $matches)) { foreach ($matches[1] as $i => $key) { $this->setOption($key, trim($matches[2][$i])); } } // init routes $this->initRoute(); // get params and convert it to simple array $reflectionParams = $reflection->getParameters(); // setup params and optional params foreach ($reflectionParams as $param) { $name = $param->getName(); // if some function params is missed in description if (!isset($this->params[$name])) { $this->params[$name] = null; } if ($param->isOptional()) { $this->values[$name] = $param->getDefaultValue(); } } } /** * Process request params * * - type conversion * - set default value * * @param array $requestParams * * @return array */ public function params(array $requestParams): array { // apply type and default value for request params $params = []; foreach ($this->params as $param => $type) { if (isset($requestParams[$param])) { switch ($type) { case 'bool': case 'boolean': $params[] = (bool)$requestParams[$param]; break; case 'int': case 'integer': $params[] = (int)$requestParams[$param]; break; case 'float': $params[] = (float)$requestParams[$param]; break; case 'string': $params[] = (string)$requestParams[$param]; break; case 'array': $params[] = (array)$requestParams[$param]; break; default: $params[] = $requestParams[$param]; break; } } elseif (isset($this->values[$param])) { $params[] = $this->values[$param]; } else { $params[] = null; } } return $params; } /** * Get path to file * * @return string */ public function getFile(): string { return $this->file; } /** * Get Cache TTL * * @return integer */ public function getCache(): int { return $this->cache; } /** * Set Cache TTL * * @param string $ttl * * @return void */ public function setCache(string $ttl): void { $this->cache = $this->prepareCache($ttl); } /** * Prepare Cache * * @param string $cache * * @return integer */ protected function prepareCache(string $cache): int { $num = (int)$cache; $time = 'min'; if ($pos = strpos($cache, ' ')) { $time = substr($cache, $pos); } switch ($time) { case 'day': case 'days': return $num * 86400; case 'hour': case 'hours': return $num * 3600; case 'min': default: return $num * 60; } } /** * Get accepted type * * @return array|null */ public function getAccept(): ?array { return count($this->accept) ? $this->accept : null; } /** * Set accepted types * * @param string $accept * * @return void */ public function setAccept(string $accept): void { // allow accept map $acceptMap = [ 'ANY' => Request::TYPE_ANY, 'HTML' => Request::TYPE_HTML, 'JSON' => Request::TYPE_JSON ]; $accept = strtoupper($accept); if (isset($acceptMap[$accept])) { $this->accept[] = $acceptMap[$accept]; } } /** * Get Acl privileges * * @return array|null */ public function getAcl(): ?array { return count($this->acl) ? $this->acl : null; } /** * Set Acl privileges * * @param string $acl * * @return void */ public function setAcl(string $acl): void { $this->acl[] = $acl; } /** * Get HTTP Method * * @return array|null */ public function getMethod(): ?array { return count($this->method) ? $this->method : null; } /** * Set HTTP Method * * @param string $method * * @return void */ public function setMethod(string $method): void { $this->method[] = strtoupper($method); } /** * Get all params * * @return array */ public function getParams(): array { return $this->params; } /** * Set param types * * @param string $param * * @return void */ public function setParam(string $param): void { // prepare params data // setup param types if (strpos($param, '$') === false) { return; } [$type, $key] = preg_split('/[ $]+/', $param); $this->params[$key] = trim($type); } /** * Get Privilege fo ACL * * @return string|null */ public function getPrivilege(): ?string { return $this->privilege; } /** * Set Privilege fo ACL allow only one privilege * * @param string $privilege * * @return void */ public function setPrivilege(string $privilege): void { $this->privilege = $privilege; } /** * Get Route * * @return array|null */ public function getRoute(): ?array { return count($this->route) ? $this->route : null; } /** * Set Route * * @param string $route * * @return void */ public function setRoute(string $route): void { $this->route[$route] = null; } /** * Init Route * * @return void */ protected function initRoute(): void { foreach ($this->route as $route => &$pattern) { $pattern = $this->prepareRoutePattern($route); } } /** * Prepare Route pattern * * @param string $route * * @return string */ protected function prepareRoutePattern(string $route): string { $pattern = str_replace('/', '\/', $route); foreach ($this->getParams() as $param => $type) { switch ($type) { case 'int': case 'integer': $pattern = str_replace("{\$$param}", "(?P<$param>[0-9]+)", $pattern); break; case 'float': $pattern = str_replace("{\$$param}", "(?P<$param>[0-9.,]+)", $pattern); break; case 'string': case 'module': case 'controller': $pattern = str_replace( "{\$$param}", "(?P<$param>[a-zA-Z0-9-_.]+)", $pattern ); break; } } return '/^' . $pattern . '/i'; } }
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Controller/ControllerException.php
src/Controller/ControllerException.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Controller; use Bluz\Application\Exception\ApplicationException; /** * ControllerException * * @package Bluz\Controller * @author Anton Shevchuk */ class ControllerException extends ApplicationException { }
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Controller/Helper/Attachment.php
src/Controller/Helper/Attachment.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Controller\Helper; use Bluz\Controller\Controller; use Bluz\Proxy\Response; /** * Switch layout * * @param $file */ return function ($file) { /** * @var Controller $this */ Response::setType('FILE'); $this->assign('FILE', $file); $this->disableLayout(); $this->disableView(); };
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Controller/Helper/CheckHttpAccept.php
src/Controller/Helper/CheckHttpAccept.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Controller\Helper; use Bluz\Common\Exception\ComponentException; use Bluz\Controller\ControllerException; use Bluz\Http\Exception\NotAcceptableException; use Bluz\Controller\Controller; use Bluz\Proxy\Request; use ReflectionException; /** * Denied helper can be declared inside Bootstrap * * @return void * @throws NotAcceptableException * @throws ComponentException * @throws ControllerException * @throws ReflectionException */ return function () { /** * @var Controller $this */ $allowAccept = $this->getMeta()->getAccept(); // some controllers hasn't @accept tag if (!$allowAccept) { // but by default allow just HTML output $allowAccept = [Request::TYPE_HTML, Request::TYPE_ANY]; } // get Accept with high priority $accept = Request::checkAccept($allowAccept); // some controllers allow any type (*/*) // and client doesn't send Accept header if (!$accept && in_array(Request::TYPE_ANY, $allowAccept, true)) { // all OK, controller should realize logic for response return; } // some controllers allow just selected types // choose MIME type by browser accept header // filtered by controller @accept // switch statement for this logic switch ($accept) { case Request::TYPE_ANY: case Request::TYPE_HTML: // HTML response with layout break; case Request::TYPE_JSON: // JSON response $this->disableView(); break; default: throw new NotAcceptableException(); } };
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Controller/Helper/User.php
src/Controller/Helper/User.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Controller\Helper; use Bluz\Auth\IdentityInterface; use Bluz\Controller\Controller; use Bluz\Proxy\Auth; /** * Get current user * * @return IdentityInterface|null */ return function () { /** * @var Controller $this */ return Auth::getIdentity(); };
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Controller/Helper/IsAllowed.php
src/Controller/Helper/IsAllowed.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Controller\Helper; use Bluz\Controller\Controller; use Bluz\Proxy\Acl; /** * Check privilege * * @param string $privilege * * @return bool */ return function (string $privilege) { /** * @var Controller $this */ return Acl::isAllowed($this->module, $privilege); };
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Controller/Helper/CheckHttpMethod.php
src/Controller/Helper/CheckHttpMethod.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Controller\Helper; use Bluz\Common\Exception\ComponentException; use Bluz\Controller\ControllerException; use Bluz\Http\Exception\NotAllowedException; use Bluz\Controller\Controller; use Bluz\Proxy\Request; use ReflectionException; /** * Denied helper can be declared inside Bootstrap * * @return void * @throws NotAllowedException * @throws ComponentException * @throws ControllerException * @throws ReflectionException */ return function () { /** * @var Controller $this */ $methods = $this->getMeta()->getMethod(); if ($methods && !in_array(Request::getMethod(), $methods, true)) { throw new NotAllowedException(implode(',', $methods)); } };
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Controller/Helper/DisableLayout.php
src/Controller/Helper/DisableLayout.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Controller\Helper; use Bluz\Application\Application; use Bluz\Controller\Controller; /** * Switch layout or disable it * * @return void */ return function () { /** * @var Controller $this */ Application::getInstance()->useLayout(false); };
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Controller/Helper/Denied.php
src/Controller/Helper/Denied.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Controller\Helper; use Bluz\Http\Exception\ForbiddenException; use Bluz\Controller\Controller; /** * Denied helper can be declared inside Bootstrap * * @return void * @throws ForbiddenException */ return function () { /** * @var Controller $this */ throw new ForbiddenException(); };
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Controller/Helper/Dispatch.php
src/Controller/Helper/Dispatch.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Controller\Helper; use Bluz\Application\Application; use Bluz\Common\Exception\CommonException; use Bluz\Common\Exception\ComponentException; use Bluz\Controller\Controller; use Bluz\Controller\ControllerException; use ReflectionException; /** * Dispatch controller * * @param string $module * @param string $controller * @param array $params * * @return Controller * @throws CommonException * @throws ComponentException * @throws ControllerException * @throws ReflectionException */ return function (string $module, string $controller, array $params = []) { /** * @var Controller $this */ return Application::getInstance()->dispatch($module, $controller, $params); };
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Controller/Helper/DisableView.php
src/Controller/Helper/DisableView.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Controller\Helper; use Bluz\Controller\Controller; /** * Switch layout or disable it * * @return void */ return function () { /** * @var Controller $this */ $this->template = null; };
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false
bluzphp/framework
https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Controller/Helper/UseJson.php
src/Controller/Helper/UseJson.php
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ declare(strict_types=1); namespace Bluz\Controller\Helper; use Bluz\Application\Application; use Bluz\Controller\Controller; use Bluz\Proxy\Response; /** * Switch to JSON content * * @return void */ return function () { /** * @var Controller $this */ Application::getInstance()->useLayout(false); Response::setType('JSON'); };
php
MIT
be908a41e27f50f3786bfa8919d5245efb0d9942
2026-01-05T04:45:21.018855Z
false