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 |
|---|---|---|---|---|---|---|---|---|
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/src/bytecode/Disassembler.php | src/bytecode/Disassembler.php | <?php declare(strict_types=1);
/*
* This file is part of FOAL.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\FOAL;
/**
* @internal This interface is not covered by the backward compatibility promise for FOAL
*/
interface Disassembler
{
/**
* @param non-empty-string $file
*
* @return list<int>
*/
public function linesWithOpcodesBeforeOptimization(string $file): array;
/**
* @param non-empty-string $file
*
* @return list<int>
*/
public function linesWithOpcodesAfterOptimization(string $file): array;
/**
* @param non-empty-string $file
*
* @return non-empty-string
*/
public function pathsBeforeOptimization(string $file): string;
/**
* @param non-empty-string $file
*
* @return non-empty-string
*/
public function pathsAfterOptimization(string $file): string;
}
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/src/bytecode/VldParser.php | src/bytecode/VldParser.php | <?php declare(strict_types=1);
/*
* This file is part of FOAL.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\FOAL;
use function array_unique;
use function explode;
use function sort;
use function str_starts_with;
use function trim;
/**
* @internal This class is not covered by the backward compatibility promise for FOAL
*/
final readonly class VldParser
{
/**
* @param list<string> $lines
*
* @return list<int>
*/
public function linesWithOpcodes(array $lines): array
{
$linesWithOpcodes = [];
$opArray = false;
foreach ($lines as $line) {
if (str_starts_with($line, ';line')) {
$opArray = true;
continue;
}
if (trim($line) === ';') {
$opArray = false;
}
if (!$opArray) {
continue;
}
$linesWithOpcodes[] = (int) explode(';', $line)[1];
}
$linesWithOpcodes = array_unique($linesWithOpcodes);
sort($linesWithOpcodes);
return $linesWithOpcodes;
}
}
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/src/cli/Version.php | src/cli/Version.php | <?php declare(strict_types=1);
/*
* This file is part of FOAL.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\FOAL\CLI;
use function assert;
use function dirname;
use SebastianBergmann\Version as VersionId;
/**
* @internal This class is not covered by the backward compatibility promise for FOAL
*/
final class Version
{
private static string $pharVersion = '';
private static string $version = '';
public static function id(): string
{
if (self::$pharVersion !== '') {
// @codeCoverageIgnoreStart
return self::$pharVersion;
// @codeCoverageIgnoreEnd
}
if (self::$version === '') {
$path = dirname(__DIR__, 2);
assert($path !== '');
self::$version = (new VersionId('0.4', $path))->asString();
}
return self::$version;
}
}
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/src/cli/Application.php | src/cli/Application.php | <?php declare(strict_types=1);
/*
* This file is part of FOAL.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\FOAL\CLI;
use const PHP_EOL;
use function array_merge;
use function array_unique;
use function array_values;
use function assert;
use function count;
use function defined;
use function file_put_contents;
use function is_dir;
use function is_file;
use function printf;
use function realpath;
use SebastianBergmann\FileIterator\Facade;
use SebastianBergmann\FOAL\Analyser;
use SebastianBergmann\FOAL\Disassembler;
use SebastianBergmann\FOAL\TextRenderer;
/**
* @internal This class is not covered by the backward compatibility promise for FOAL
*/
final readonly class Application
{
private Analyser $analyser;
private Disassembler $disassembler;
public function __construct(Analyser $analyser, Disassembler $disassembler)
{
$this->analyser = $analyser;
$this->disassembler = $disassembler;
}
/**
* @param list<non-empty-string> $argv
*/
public function run(array $argv): int
{
$this->printVersion();
try {
$configuration = (new ConfigurationBuilder)->build($argv);
// @codeCoverageIgnoreStart
} catch (ConfigurationBuilderException $e) {
print PHP_EOL . $e->getMessage() . PHP_EOL;
return 1;
// @codeCoverageIgnoreEnd
}
if ($configuration->version()) {
return 0;
}
print PHP_EOL;
if ($configuration->help()) {
$this->help();
return 0;
}
if ($configuration->arguments() === []) {
$this->help();
return 1;
}
$files = [];
foreach ($configuration->arguments() as $argument) {
$candidate = realpath($argument);
if ($candidate === false) {
continue;
}
assert($candidate !== '');
if (is_file($candidate)) {
$files[] = $candidate;
continue;
}
if (is_dir($candidate)) {
$files = array_merge($files, (new Facade)->getFilesAsArray($candidate, '.php'));
}
}
if (empty($files)) {
print 'No files found to analyse' . PHP_EOL;
return 1;
}
$files = array_values(array_unique($files));
if ($configuration->hasPaths()) {
return $this->handlePaths($files, $configuration->paths());
}
return $this->handleAnalysis($files);
}
private function printVersion(): void
{
printf(
'foal %s by Sebastian Bergmann.' . PHP_EOL,
Version::id(),
);
}
private function help(): void
{
print <<<'EOT'
Usage:
foal [options] <directory|file> ...
--paths <directory> Write execution paths before/after bytecode optimization to files in DOT format
-h|--help Prints this usage information and exits
--version Prints the version and exits
EOT;
if (defined('__FOAL_PHAR__')) {
print <<<'EOT'
--manifest Prints Software Bill of Materials (SBOM) in plain-text format and exits
--sbom Prints Software Bill of Materials (SBOM) in CycloneDX XML format and exits
--composer-lock Prints the composer.lock file used to build the PHAR and exits
EOT;
}
}
/**
* @param non-empty-list<non-empty-string> $files
* @param non-empty-string $target
*/
private function handlePaths(array $files, string $target): int
{
if (count($files) !== 1) {
print 'The --paths option only operates on a source single file' . PHP_EOL;
return 1;
}
$unoptimizedFile = $target . '/unoptimized.dot';
file_put_contents($unoptimizedFile, $this->disassembler->pathsBeforeOptimization($files[0]));
printf(
'Wrote execution paths for %s to %s' . PHP_EOL,
$files[0],
$unoptimizedFile,
);
$optimizedFile = $target . '/optimized.dot';
file_put_contents($optimizedFile, $this->disassembler->pathsAfterOptimization($files[0]));
printf(
'Wrote optimized execution paths for %s to %s' . PHP_EOL,
$files[0],
$optimizedFile,
);
return 0;
}
/**
* @param non-empty-list<non-empty-string> $files
*/
private function handleAnalysis(array $files): int
{
$files = $this->analyser->analyse($files);
$renderer = new TextRenderer;
$first = true;
foreach ($files as $file) {
if (!$first) {
print PHP_EOL;
}
print $renderer->render($file);
$first = false;
}
return 0;
}
}
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/src/cli/Configuration.php | src/cli/Configuration.php | <?php declare(strict_types=1);
/*
* This file is part of FOAL.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\FOAL\CLI;
/**
* @internal This class is not covered by the backward compatibility promise for FOAL
*/
final readonly class Configuration
{
/**
* @var list<non-empty-string>
*/
private array $arguments;
/**
* @var ?non-empty-string
*/
private ?string $paths;
private bool $help;
private bool $version;
/**
* @param list<non-empty-string> $arguments
* @param ?non-empty-string $paths
*/
public function __construct(array $arguments, ?string $paths, bool $help, bool $version)
{
$this->arguments = $arguments;
$this->help = $help;
$this->paths = $paths;
$this->version = $version;
}
/**
* @return list<non-empty-string>
*/
public function arguments(): array
{
return $this->arguments;
}
/**
* @phpstan-assert-if-true !null $this->paths
*/
public function hasPaths(): bool
{
return $this->paths !== null;
}
/**
* @throws PathsNotConfiguredException
*
* @return non-empty-string
*/
public function paths(): string
{
if ($this->paths === null) {
// @codeCoverageIgnoreStart
throw new PathsNotConfiguredException;
// @codeCoverageIgnoreEnd
}
return $this->paths;
}
public function help(): bool
{
return $this->help;
}
public function version(): bool
{
return $this->version;
}
}
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/src/cli/ConfigurationBuilder.php | src/cli/ConfigurationBuilder.php | <?php declare(strict_types=1);
/*
* This file is part of FOAL.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\FOAL\CLI;
use function assert;
use function is_array;
use SebastianBergmann\CliParser\Exception as CliParserException;
use SebastianBergmann\CliParser\Parser as CliParser;
/**
* @internal This class is not covered by the backward compatibility promise for FOAL
*/
final readonly class ConfigurationBuilder
{
/**
* @param list<non-empty-string> $argv
*
* @throws ConfigurationBuilderException
*/
public function build(array $argv): Configuration
{
try {
$options = (new CliParser)->parse(
$argv,
'hv',
[
'paths=',
'help',
'version',
],
);
// @codeCoverageIgnoreStart
} catch (CliParserException $e) {
throw new ConfigurationBuilderException(
$e->getMessage(),
$e->getCode(),
$e,
);
// @codeCoverageIgnoreEnd
}
$paths = null;
$help = false;
$version = false;
foreach ($options[0] as $option) {
assert(is_array($option));
switch ($option[0]) {
case '--paths':
$paths = (string) $option[1];
assert($paths !== '');
break;
case 'h':
case '--help':
$help = true;
break;
case 'v':
case '--version':
$version = true;
break;
}
}
return new Configuration(
$options[1],
$paths,
$help,
$version,
);
}
}
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/src/cli/Factory.php | src/cli/Factory.php | <?php declare(strict_types=1);
/*
* This file is part of FOAL.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\FOAL\CLI;
use SebastianBergmann\FOAL\Analyser;
use SebastianBergmann\FOAL\VldDisassembler;
use SebastianBergmann\FOAL\VldParser;
/**
* @internal This class is not covered by the backward compatibility promise for FOAL
*/
final readonly class Factory
{
public function createApplication(): Application
{
return new Application(
new Analyser($this->disassembler()),
$this->disassembler(),
);
}
private function disassembler(): VldDisassembler
{
return new VldDisassembler(
new VldParser,
);
}
}
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/tests/fixture/source.php | tests/fixture/source.php | <?php declare(strict_types=1);
function f()
{
$result = 'result';
return $result;
}
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/tests/fixture/source2.php | tests/fixture/source2.php | <?php declare(strict_types=1);
function f()
{
$result = 'result';
return $result;
}
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/tests/unit/TextRendererTest.php | tests/unit/TextRendererTest.php | <?php declare(strict_types=1);
/*
* This file is part of FOAL.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\FOAL;
use function assert;
use function file;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Small;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\Attributes\UsesClass;
use PHPUnit\Framework\TestCase;
#[CoversClass(TextRenderer::class)]
#[UsesClass(File::class)]
#[Small]
#[TestDox('TextRenderer')]
final class TextRendererTest extends TestCase
{
public function testRendersFileAsString(): void
{
$this->assertStringMatchesFormatFile(
__DIR__ . '/../expectations/source.txt',
(new TextRenderer)->render($this->file()),
);
}
private function file(): File
{
$sourceLines = file(__DIR__ . '/../fixture/source.php');
assert($sourceLines !== false);
return new File(
__DIR__ . '/../fixture/source.php',
$sourceLines,
[4, 7],
);
}
}
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/tests/unit/file/FileCollectionTest.php | tests/unit/file/FileCollectionTest.php | <?php declare(strict_types=1);
/*
* This file is part of FOAL.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\FOAL;
use function assert;
use function file;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Small;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\Attributes\UsesClass;
use PHPUnit\Framework\TestCase;
#[CoversClass(FileCollection::class)]
#[CoversClass(FileCollectionIterator::class)]
#[UsesClass(File::class)]
#[Small]
#[TestDox('FileCollection')]
final class FileCollectionTest extends TestCase
{
#[TestDox('Can be created from list of File objects')]
public function testCanBeCreatedFromListOfObjects(): void
{
$file = $this->file();
$collection = FileCollection::from($file);
$this->assertSame([$file], $collection->asArray());
}
public function testCanBeCounted(): void
{
$collection = FileCollection::from($this->file());
$this->assertCount(1, $collection);
$this->assertFalse($collection->isEmpty());
}
public function testCanBeIterated(): void
{
$file = $this->file();
$collection = FileCollection::from($file);
foreach ($collection as $key => $value) {
$this->assertSame(0, $key);
$this->assertSame($file, $value);
}
}
private function file(): File
{
$sourceLines = file(__DIR__ . '/../../fixture/source.php');
assert($sourceLines !== false);
return new File(
__DIR__ . '/../../fixture/source.php',
$sourceLines,
[4, 7],
);
}
}
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/tests/unit/file/FileTest.php | tests/unit/file/FileTest.php | <?php declare(strict_types=1);
/*
* This file is part of FOAL.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\FOAL;
use function assert;
use function file;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Small;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
#[CoversClass(File::class)]
#[Small]
#[TestDox('File')]
final class FileTest extends TestCase
{
public function testHasPath(): void
{
$this->assertSame(
__DIR__ . '/../../fixture/source.php',
$this->file()->path(),
);
}
public function testHasSourceLines(): void
{
$this->assertSame(
file(__DIR__ . '/../../fixture/source.php'),
$this->file()->sourceLines(),
);
}
public function testHasLinesEliminatedByOptimizer(): void
{
$this->assertSame(
[4, 7],
$this->file()->linesEliminatedByOptimizer(),
);
}
private function file(): File
{
$sourceLines = file(__DIR__ . '/../../fixture/source.php');
assert($sourceLines !== false);
return new File(
__DIR__ . '/../../fixture/source.php',
$sourceLines,
[4, 7],
);
}
}
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/tests/unit/bytecode/VldParserTest.php | tests/unit/bytecode/VldParserTest.php | <?php declare(strict_types=1);
/*
* This file is part of FOAL.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\FOAL;
use function assert;
use function file;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Small;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
#[CoversClass(VldParser::class)]
#[Small]
#[TestDox('VldParser')]
final class VldParserTest extends TestCase
{
/**
* @return non-empty-array<non-empty-string, array{0: list<int>, 1: non-empty-string}>
*/
public static function provider(): array
{
return [
'before optimization' => [
[4, 6, 7, 8],
__DIR__ . '/../../fixture/source.bytecode',
],
'after optimization' => [
[6, 8],
__DIR__ . '/../../fixture/source.optimized-bytecode',
],
];
}
/**
* @param list<int> $expected
*/
#[DataProvider('provider')]
#[TestDox('Parses VLD bytecode dump')]
public function testParsesVldBytecodeDump(array $expected, string $filename): void
{
$parser = new VldParser;
$lines = file($filename);
assert($lines !== false);
$this->assertSame($expected, $parser->linesWithOpcodes($lines));
}
}
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/tests/unit/bytecode/VldDisassemblerTest.php | tests/unit/bytecode/VldDisassemblerTest.php | <?php declare(strict_types=1);
/*
* This file is part of FOAL.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\FOAL;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\RequiresPhpExtension;
use PHPUnit\Framework\Attributes\Small;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\Attributes\UsesClass;
use PHPUnit\Framework\TestCase;
#[CoversClass(VldDisassembler::class)]
#[UsesClass(VldParser::class)]
#[Small]
#[TestDox('VldDisassembler')]
#[RequiresPhpExtension('vld')]
#[RequiresPhpExtension('Zend OPcache')]
final class VldDisassemblerTest extends TestCase
{
public function testFindsLinesWithOpcodesBeforeOptimization(): void
{
$this->assertSame(
[4, 6, 7, 8],
$this->disassembler()->linesWithOpcodesBeforeOptimization(__DIR__ . '/../../fixture/source.php'),
);
}
public function testFindsLinesWithOpcodesAfterOptimization(): void
{
$this->assertSame(
[6, 8],
$this->disassembler()->linesWithOpcodesAfterOptimization(__DIR__ . '/../../fixture/source.php'),
);
}
public function testFindsPathsBeforeOptimization(): void
{
$this->assertStringMatchesFormatFile(
__DIR__ . '/../../expectations/before-optimization.dot',
$this->disassembler()->pathsBeforeOptimization(__DIR__ . '/../../fixture/source.php'),
);
}
public function testFindsPathsAfterOptimization(): void
{
$this->assertStringMatchesFormatFile(
__DIR__ . '/../../expectations/after-optimization.dot',
$this->disassembler()->pathsAfterOptimization(__DIR__ . '/../../fixture/source.php'),
);
}
private function disassembler(): VldDisassembler
{
return new VldDisassembler(new VldParser);
}
}
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/build/scripts/phar-version.php | build/scripts/phar-version.php | #!/usr/bin/env php
<?php declare(strict_types=1);
if (!isset($argv[1], $argv[2])) {
exit(1);
}
\file_put_contents(
__DIR__ . '/../tmp/phar/foal/cli/Version.php',
\str_replace(
'private static string $pharVersion = \'\';',
'private static string $pharVersion = \'' . $argv[1] . '\';',
\file_get_contents(__DIR__ . '/../tmp/phar/foal/cli/Version.php')
),
\LOCK_EX
);
if ($argv[2] === 'release') {
print $argv[1];
} else {
print $argv[2];
}
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/build/scripts/version.php | build/scripts/version.php | #!/usr/bin/env php
<?php declare(strict_types=1);
require __DIR__ . '/../../vendor/sebastian/version/src/Version.php';
use SebastianBergmann\Version;
$buffer = \file_get_contents(__DIR__ . '/../../src/cli/Version.php');
$start = \strpos($buffer, 'new VersionId(\'') + \strlen('new VersionId(\'');
$end = \strpos($buffer, '\'', $start);
$version = \substr($buffer, $start, $end - $start);
$version = new Version($version, __DIR__ . '/../../');
print $version->asString();
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/build/scripts/extract-release-notes.php | build/scripts/extract-release-notes.php | #!/usr/bin/env php
<?php declare(strict_types=1);
if ($argc !== 2) {
print $argv[0] . ' <tag>' . PHP_EOL;
exit(1);
}
$version = $argv[1];
$file = __DIR__ . '/../../ChangeLog.md';
if (!is_file($file) || !is_readable($file)) {
print $file . ' cannot be read' . PHP_EOL;
exit(1);
}
$buffer = '';
$append = false;
foreach (file($file) as $line) {
if (str_starts_with($line, '## [' . $version . ']')) {
$append = true;
continue;
}
if ($append && (str_starts_with($line, '## ') || str_starts_with($line, '['))) {
break;
}
if ($append) {
$buffer .= $line;
}
}
$buffer = trim($buffer);
if ($buffer === '') {
print 'Unable to extract release notes' . PHP_EOL;
exit(1);
}
print $buffer . PHP_EOL;
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/build/scripts/phar-manifest.php | build/scripts/phar-manifest.php | #!/usr/bin/env php
<?php declare(strict_types=1);
if ($argc !== 3) {
fwrite(
STDERR,
sprintf(
'%s /path/to/manifest.txt /path/to/sbom.xml' . PHP_EOL,
$argv[0]
)
);
exit(1);
}
$package = package();
$version = version();
$dependencies = dependencies();
manifest($argv[1], $package, $version, $dependencies);
sbom($argv[2], $package, $version, $dependencies);
function manifest(string $outputFilename, array $package, string $version, array $dependencies): void
{
$buffer = sprintf(
'%s/%s: %s' . "\n",
$package['group'],
$package['name'],
$version
);
foreach ($dependencies as $dependency) {
$buffer .= sprintf(
'%s: %s' . "\n",
$dependency['name'],
versionWithReference(
$dependency['version'],
$dependency['source']['reference']
)
);
}
file_put_contents($outputFilename, $buffer);
}
function sbom(string $outputFilename, array $package, string $version, array $dependencies): void
{
$writer = new XMLWriter;
$writer->openMemory();
$writer->setIndent(true);
$writer->startDocument();
$writer->startElement('bom');
$writer->writeAttribute('xmlns', 'http://cyclonedx.org/schema/bom/1.4');
$writer->startElement('components');
writeComponent(
$writer,
$package['group'],
$package['name'],
$version,
$package['description'],
$package['license']
);
foreach ($dependencies as $dependency) {
[$group, $name] = explode('/', $dependency['name']);
writeComponent(
$writer,
$group,
$name,
versionWithReference(
$dependency['version'],
$dependency['source']['reference']
),
$dependency['description'],
$dependency['license']
);
}
$writer->endElement();
$writer->endElement();
$writer->endDocument();
file_put_contents($outputFilename, $writer->outputMemory());
}
function package(): array
{
$data = json_decode(
file_get_contents(
__DIR__ . '/../../composer.json'
),
true
);
[$group, $name] = explode('/', $data['name']);
return [
'group' => $group,
'name' => $name,
'description' => $data['description'],
'license' => [$data['license']],
];
}
function version(): string
{
$tag = @exec('git describe --tags 2>&1');
if (strpos($tag, '-') === false && strpos($tag, 'No names found') === false) {
return $tag;
}
$branch = @exec('git rev-parse --abbrev-ref HEAD');
$hash = @exec('git log -1 --format="%H"');
return $branch . '@' . $hash;
}
function dependencies(): array
{
return json_decode(
file_get_contents(
__DIR__ . '/../../composer.lock'
),
true
)['packages'];
}
function versionWithReference(string $version, string $reference): string
{
if (!preg_match('/^[v= ]*(([0-9]+)(\\.([0-9]+)(\\.([0-9]+)(-([0-9]+))?(-?([a-zA-Z-+][a-zA-Z0-9.\\-:]*)?)?)?)?)$/', $version)) {
$version .= '@' . $reference;
}
return $version;
}
function writeComponent(XMLWriter $writer, string $group, string $name, string $version, string $description, array $licenses): void
{
$writer->startElement('component');
$writer->writeAttribute('type', 'library');
$writer->writeElement('group', $group);
$writer->writeElement('name', $name);
$writer->writeElement('version', $version);
$writer->writeElement('description', $description);
$writer->startElement('licenses');
foreach ($licenses as $license) {
$writer->startElement('license');
$writer->writeElement('id', $license);
$writer->endElement();
}
$writer->endElement();
$writer->writeElement(
'purl',
sprintf(
'pkg:composer/%s/%s@%s',
$group,
$name,
$version
)
);
$writer->endElement();
}
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/build/scripts/phar-set-timestamps/run.php | build/scripts/phar-set-timestamps/run.php | #!/usr/bin/env php
<?php declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
if (!isset($argv[1]) || !is_file($argv[1])) {
exit(1);
}
use Seld\PharUtils\Timestamps;
$util = new Timestamps($argv[1]);
if (is_string(getenv('SOURCE_DATE_EPOCH'))) {
$timestamp = new DateTime;
$timestamp->setTimestamp((int) getenv('SOURCE_DATE_EPOCH'));
} else {
$timestamp = new DateTimeImmutable('now');
}
$util->updateTimestamps($timestamp);
$util->save($argv[1], Phar::SHA512);
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/build/scripts/phar-set-timestamps/vendor/autoload.php | build/scripts/phar-set-timestamps/vendor/autoload.php | <?php
// autoload.php @generated by Composer
if (PHP_VERSION_ID < 50600) {
if (!headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');
}
$err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL;
if (!ini_get('display_errors')) {
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
fwrite(STDERR, $err);
} elseif (!headers_sent()) {
echo $err;
}
}
trigger_error(
$err,
E_USER_ERROR
);
}
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit386a05f6676643b8b2eb49288e20d079::getLoader();
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/build/scripts/phar-set-timestamps/vendor/composer/InstalledVersions.php | build/scripts/phar-set-timestamps/vendor/composer/InstalledVersions.php | <?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer;
use Composer\Autoload\ClassLoader;
use Composer\Semver\VersionParser;
/**
* This class is copied in every Composer installed project and available to all
*
* See also https://getcomposer.org/doc/07-runtime.md#installed-versions
*
* To require its presence, you can require `composer-runtime-api ^2.0`
*
* @final
*/
class InstalledVersions
{
/**
* @var mixed[]|null
* @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}|array{}|null
*/
private static $installed;
/**
* @var bool|null
*/
private static $canGetVendors;
/**
* @var array[]
* @psalm-var array<string, array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
private static $installedByVendor = array();
/**
* Returns a list of all package names which are present, either by being installed, replaced or provided
*
* @return string[]
* @psalm-return list<string>
*/
public static function getInstalledPackages()
{
$packages = array();
foreach (self::getInstalled() as $installed) {
$packages[] = array_keys($installed['versions']);
}
if (1 === \count($packages)) {
return $packages[0];
}
return array_keys(array_flip(\call_user_func_array('array_merge', $packages)));
}
/**
* Returns a list of all package names with a specific type e.g. 'library'
*
* @param string $type
* @return string[]
* @psalm-return list<string>
*/
public static function getInstalledPackagesByType($type)
{
$packagesByType = array();
foreach (self::getInstalled() as $installed) {
foreach ($installed['versions'] as $name => $package) {
if (isset($package['type']) && $package['type'] === $type) {
$packagesByType[] = $name;
}
}
}
return $packagesByType;
}
/**
* Checks whether the given package is installed
*
* This also returns true if the package name is provided or replaced by another package
*
* @param string $packageName
* @param bool $includeDevRequirements
* @return bool
*/
public static function isInstalled($packageName, $includeDevRequirements = true)
{
foreach (self::getInstalled() as $installed) {
if (isset($installed['versions'][$packageName])) {
return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false;
}
}
return false;
}
/**
* Checks whether the given package satisfies a version constraint
*
* e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call:
*
* Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3')
*
* @param VersionParser $parser Install composer/semver to have access to this class and functionality
* @param string $packageName
* @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package
* @return bool
*/
public static function satisfies(VersionParser $parser, $packageName, $constraint)
{
$constraint = $parser->parseConstraints((string) $constraint);
$provided = $parser->parseConstraints(self::getVersionRanges($packageName));
return $provided->matches($constraint);
}
/**
* Returns a version constraint representing all the range(s) which are installed for a given package
*
* It is easier to use this via isInstalled() with the $constraint argument if you need to check
* whether a given version of a package is installed, and not just whether it exists
*
* @param string $packageName
* @return string Version constraint usable with composer/semver
*/
public static function getVersionRanges($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
$ranges = array();
if (isset($installed['versions'][$packageName]['pretty_version'])) {
$ranges[] = $installed['versions'][$packageName]['pretty_version'];
}
if (array_key_exists('aliases', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']);
}
if (array_key_exists('replaced', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']);
}
if (array_key_exists('provided', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']);
}
return implode(' || ', $ranges);
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
*/
public static function getVersion($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['version'])) {
return null;
}
return $installed['versions'][$packageName]['version'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
*/
public static function getPrettyVersion($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['pretty_version'])) {
return null;
}
return $installed['versions'][$packageName]['pretty_version'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference
*/
public static function getReference($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['reference'])) {
return null;
}
return $installed['versions'][$packageName]['reference'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path.
*/
public static function getInstallPath($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null;
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @return array
* @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}
*/
public static function getRootPackage()
{
$installed = self::getInstalled();
return $installed[0]['root'];
}
/**
* Returns the raw installed.php data for custom implementations
*
* @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect.
* @return array[]
* @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}
*/
public static function getRawData()
{
@trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED);
if (null === self::$installed) {
// only require the installed.php file if this file is loaded from its dumped location,
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
if (substr(__DIR__, -8, 1) !== 'C') {
self::$installed = include __DIR__ . '/installed.php';
} else {
self::$installed = array();
}
}
return self::$installed;
}
/**
* Returns the raw data of all installed.php which are currently loaded for custom implementations
*
* @return array[]
* @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
public static function getAllRawData()
{
return self::getInstalled();
}
/**
* Lets you reload the static array from another file
*
* This is only useful for complex integrations in which a project needs to use
* this class but then also needs to execute another project's autoloader in process,
* and wants to ensure both projects have access to their version of installed.php.
*
* A typical case would be PHPUnit, where it would need to make sure it reads all
* the data it needs from this class, then call reload() with
* `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure
* the project in which it runs can then also use this class safely, without
* interference between PHPUnit's dependencies and the project's dependencies.
*
* @param array[] $data A vendor/composer/installed.php data set
* @return void
*
* @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $data
*/
public static function reload($data)
{
self::$installed = $data;
self::$installedByVendor = array();
}
/**
* @return array[]
* @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
private static function getInstalled()
{
if (null === self::$canGetVendors) {
self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders');
}
$installed = array();
if (self::$canGetVendors) {
foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) {
if (isset(self::$installedByVendor[$vendorDir])) {
$installed[] = self::$installedByVendor[$vendorDir];
} elseif (is_file($vendorDir.'/composer/installed.php')) {
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
$required = require $vendorDir.'/composer/installed.php';
$installed[] = self::$installedByVendor[$vendorDir] = $required;
if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) {
self::$installed = $installed[count($installed) - 1];
}
}
}
}
if (null === self::$installed) {
// only require the installed.php file if this file is loaded from its dumped location,
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
if (substr(__DIR__, -8, 1) !== 'C') {
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
$required = require __DIR__ . '/installed.php';
self::$installed = $required;
} else {
self::$installed = array();
}
}
if (self::$installed !== array()) {
$installed[] = self::$installed;
}
return $installed;
}
}
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/build/scripts/phar-set-timestamps/vendor/composer/autoload_real.php | build/scripts/phar-set-timestamps/vendor/composer/autoload_real.php | <?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInit386a05f6676643b8b2eb49288e20d079
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
/**
* @return \Composer\Autoload\ClassLoader
*/
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
require __DIR__ . '/platform_check.php';
spl_autoload_register(array('ComposerAutoloaderInit386a05f6676643b8b2eb49288e20d079', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__));
spl_autoload_unregister(array('ComposerAutoloaderInit386a05f6676643b8b2eb49288e20d079', 'loadClassLoader'));
require __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInit386a05f6676643b8b2eb49288e20d079::getInitializer($loader));
$loader->register(true);
return $loader;
}
}
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/build/scripts/phar-set-timestamps/vendor/composer/autoload_namespaces.php | build/scripts/phar-set-timestamps/vendor/composer/autoload_namespaces.php | <?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
);
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/build/scripts/phar-set-timestamps/vendor/composer/autoload_psr4.php | build/scripts/phar-set-timestamps/vendor/composer/autoload_psr4.php | <?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'Seld\\PharUtils\\' => array($vendorDir . '/seld/phar-utils/src'),
);
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/build/scripts/phar-set-timestamps/vendor/composer/autoload_static.php | build/scripts/phar-set-timestamps/vendor/composer/autoload_static.php | <?php
// autoload_static.php @generated by Composer
namespace Composer\Autoload;
class ComposerStaticInit386a05f6676643b8b2eb49288e20d079
{
public static $prefixLengthsPsr4 = array (
'S' =>
array (
'Seld\\PharUtils\\' => 15,
),
);
public static $prefixDirsPsr4 = array (
'Seld\\PharUtils\\' =>
array (
0 => __DIR__ . '/..' . '/seld/phar-utils/src',
),
);
public static $classMap = array (
'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php',
'Seld\\PharUtils\\Linter' => __DIR__ . '/..' . '/seld/phar-utils/src/Linter.php',
'Seld\\PharUtils\\Timestamps' => __DIR__ . '/..' . '/seld/phar-utils/src/Timestamps.php',
);
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInit386a05f6676643b8b2eb49288e20d079::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit386a05f6676643b8b2eb49288e20d079::$prefixDirsPsr4;
$loader->classMap = ComposerStaticInit386a05f6676643b8b2eb49288e20d079::$classMap;
}, null, ClassLoader::class);
}
}
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/build/scripts/phar-set-timestamps/vendor/composer/installed.php | build/scripts/phar-set-timestamps/vendor/composer/installed.php | <?php return array(
'root' => array(
'name' => '__root__',
'pretty_version' => '8.5.x-dev',
'version' => '8.5.9999999.9999999-dev',
'reference' => 'aca96fcd8b6799ead1066524b2b91c5184ece78f',
'type' => 'library',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'dev' => true,
),
'versions' => array(
'__root__' => array(
'pretty_version' => '8.5.x-dev',
'version' => '8.5.9999999.9999999-dev',
'reference' => 'aca96fcd8b6799ead1066524b2b91c5184ece78f',
'type' => 'library',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'dev_requirement' => false,
),
'seld/phar-utils' => array(
'pretty_version' => '1.2.1',
'version' => '1.2.1.0',
'reference' => 'ea2f4014f163c1be4c601b9b7bd6af81ba8d701c',
'type' => 'library',
'install_path' => __DIR__ . '/../seld/phar-utils',
'aliases' => array(),
'dev_requirement' => false,
),
),
);
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/build/scripts/phar-set-timestamps/vendor/composer/ClassLoader.php | build/scripts/phar-set-timestamps/vendor/composer/ClassLoader.php | <?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Autoload;
/**
* ClassLoader implements a PSR-0, PSR-4 and classmap class loader.
*
* $loader = new \Composer\Autoload\ClassLoader();
*
* // register classes with namespaces
* $loader->add('Symfony\Component', __DIR__.'/component');
* $loader->add('Symfony', __DIR__.'/framework');
*
* // activate the autoloader
* $loader->register();
*
* // to enable searching the include path (eg. for PEAR packages)
* $loader->setUseIncludePath(true);
*
* In this example, if you try to use a class in the Symfony\Component
* namespace or one of its children (Symfony\Component\Console for instance),
* the autoloader will first look for the class under the component/
* directory, and it will then fallback to the framework/ directory if not
* found before giving up.
*
* This class is loosely based on the Symfony UniversalClassLoader.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @see https://www.php-fig.org/psr/psr-0/
* @see https://www.php-fig.org/psr/psr-4/
*/
class ClassLoader
{
/** @var \Closure(string):void */
private static $includeFile;
/** @var string|null */
private $vendorDir;
// PSR-4
/**
* @var array<string, array<string, int>>
*/
private $prefixLengthsPsr4 = array();
/**
* @var array<string, list<string>>
*/
private $prefixDirsPsr4 = array();
/**
* @var list<string>
*/
private $fallbackDirsPsr4 = array();
// PSR-0
/**
* List of PSR-0 prefixes
*
* Structured as array('F (first letter)' => array('Foo\Bar (full prefix)' => array('path', 'path2')))
*
* @var array<string, array<string, list<string>>>
*/
private $prefixesPsr0 = array();
/**
* @var list<string>
*/
private $fallbackDirsPsr0 = array();
/** @var bool */
private $useIncludePath = false;
/**
* @var array<string, string>
*/
private $classMap = array();
/** @var bool */
private $classMapAuthoritative = false;
/**
* @var array<string, bool>
*/
private $missingClasses = array();
/** @var string|null */
private $apcuPrefix;
/**
* @var array<string, self>
*/
private static $registeredLoaders = array();
/**
* @param string|null $vendorDir
*/
public function __construct($vendorDir = null)
{
$this->vendorDir = $vendorDir;
self::initializeIncludeClosure();
}
/**
* @return array<string, list<string>>
*/
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
}
return array();
}
/**
* @return array<string, list<string>>
*/
public function getPrefixesPsr4()
{
return $this->prefixDirsPsr4;
}
/**
* @return list<string>
*/
public function getFallbackDirs()
{
return $this->fallbackDirsPsr0;
}
/**
* @return list<string>
*/
public function getFallbackDirsPsr4()
{
return $this->fallbackDirsPsr4;
}
/**
* @return array<string, string> Array of classname => path
*/
public function getClassMap()
{
return $this->classMap;
}
/**
* @param array<string, string> $classMap Class to filename map
*
* @return void
*/
public function addClassMap(array $classMap)
{
if ($this->classMap) {
$this->classMap = array_merge($this->classMap, $classMap);
} else {
$this->classMap = $classMap;
}
}
/**
* Registers a set of PSR-0 directories for a given prefix, either
* appending or prepending to the ones previously set for this prefix.
*
* @param string $prefix The prefix
* @param list<string>|string $paths The PSR-0 root directories
* @param bool $prepend Whether to prepend the directories
*
* @return void
*/
public function add($prefix, $paths, $prepend = false)
{
$paths = (array) $paths;
if (!$prefix) {
if ($prepend) {
$this->fallbackDirsPsr0 = array_merge(
$paths,
$this->fallbackDirsPsr0
);
} else {
$this->fallbackDirsPsr0 = array_merge(
$this->fallbackDirsPsr0,
$paths
);
}
return;
}
$first = $prefix[0];
if (!isset($this->prefixesPsr0[$first][$prefix])) {
$this->prefixesPsr0[$first][$prefix] = $paths;
return;
}
if ($prepend) {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$paths,
$this->prefixesPsr0[$first][$prefix]
);
} else {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$this->prefixesPsr0[$first][$prefix],
$paths
);
}
}
/**
* Registers a set of PSR-4 directories for a given namespace, either
* appending or prepending to the ones previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param list<string>|string $paths The PSR-4 base directories
* @param bool $prepend Whether to prepend the directories
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function addPsr4($prefix, $paths, $prepend = false)
{
$paths = (array) $paths;
if (!$prefix) {
// Register directories for the root namespace.
if ($prepend) {
$this->fallbackDirsPsr4 = array_merge(
$paths,
$this->fallbackDirsPsr4
);
} else {
$this->fallbackDirsPsr4 = array_merge(
$this->fallbackDirsPsr4,
$paths
);
}
} elseif (!isset($this->prefixDirsPsr4[$prefix])) {
// Register directories for a new namespace.
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = $paths;
} elseif ($prepend) {
// Prepend directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$paths,
$this->prefixDirsPsr4[$prefix]
);
} else {
// Append directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$this->prefixDirsPsr4[$prefix],
$paths
);
}
}
/**
* Registers a set of PSR-0 directories for a given prefix,
* replacing any others previously set for this prefix.
*
* @param string $prefix The prefix
* @param list<string>|string $paths The PSR-0 base directories
*
* @return void
*/
public function set($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr0 = (array) $paths;
} else {
$this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
}
}
/**
* Registers a set of PSR-4 directories for a given namespace,
* replacing any others previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param list<string>|string $paths The PSR-4 base directories
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function setPsr4($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr4 = (array) $paths;
} else {
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
}
}
/**
* Turns on searching the include path for class files.
*
* @param bool $useIncludePath
*
* @return void
*/
public function setUseIncludePath($useIncludePath)
{
$this->useIncludePath = $useIncludePath;
}
/**
* Can be used to check if the autoloader uses the include path to check
* for classes.
*
* @return bool
*/
public function getUseIncludePath()
{
return $this->useIncludePath;
}
/**
* Turns off searching the prefix and fallback directories for classes
* that have not been registered with the class map.
*
* @param bool $classMapAuthoritative
*
* @return void
*/
public function setClassMapAuthoritative($classMapAuthoritative)
{
$this->classMapAuthoritative = $classMapAuthoritative;
}
/**
* Should class lookup fail if not found in the current class map?
*
* @return bool
*/
public function isClassMapAuthoritative()
{
return $this->classMapAuthoritative;
}
/**
* APCu prefix to use to cache found/not-found classes, if the extension is enabled.
*
* @param string|null $apcuPrefix
*
* @return void
*/
public function setApcuPrefix($apcuPrefix)
{
$this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null;
}
/**
* The APCu prefix in use, or null if APCu caching is not enabled.
*
* @return string|null
*/
public function getApcuPrefix()
{
return $this->apcuPrefix;
}
/**
* Registers this instance as an autoloader.
*
* @param bool $prepend Whether to prepend the autoloader or not
*
* @return void
*/
public function register($prepend = false)
{
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
if (null === $this->vendorDir) {
return;
}
if ($prepend) {
self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders;
} else {
unset(self::$registeredLoaders[$this->vendorDir]);
self::$registeredLoaders[$this->vendorDir] = $this;
}
}
/**
* Unregisters this instance as an autoloader.
*
* @return void
*/
public function unregister()
{
spl_autoload_unregister(array($this, 'loadClass'));
if (null !== $this->vendorDir) {
unset(self::$registeredLoaders[$this->vendorDir]);
}
}
/**
* Loads the given class or interface.
*
* @param string $class The name of the class
* @return true|null True if loaded, null otherwise
*/
public function loadClass($class)
{
if ($file = $this->findFile($class)) {
$includeFile = self::$includeFile;
$includeFile($file);
return true;
}
return null;
}
/**
* Finds the path to the file where the class is defined.
*
* @param string $class The name of the class
*
* @return string|false The path if found, false otherwise
*/
public function findFile($class)
{
// class map lookup
if (isset($this->classMap[$class])) {
return $this->classMap[$class];
}
if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
return false;
}
if (null !== $this->apcuPrefix) {
$file = apcu_fetch($this->apcuPrefix.$class, $hit);
if ($hit) {
return $file;
}
}
$file = $this->findFileWithExtension($class, '.php');
// Search for Hack files if we are running on HHVM
if (false === $file && defined('HHVM_VERSION')) {
$file = $this->findFileWithExtension($class, '.hh');
}
if (null !== $this->apcuPrefix) {
apcu_add($this->apcuPrefix.$class, $file);
}
if (false === $file) {
// Remember that this class does not exist.
$this->missingClasses[$class] = true;
}
return $file;
}
/**
* Returns the currently registered loaders keyed by their corresponding vendor directories.
*
* @return array<string, self>
*/
public static function getRegisteredLoaders()
{
return self::$registeredLoaders;
}
/**
* @param string $class
* @param string $ext
* @return string|false
*/
private function findFileWithExtension($class, $ext)
{
// PSR-4 lookup
$logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
$first = $class[0];
if (isset($this->prefixLengthsPsr4[$first])) {
$subPath = $class;
while (false !== $lastPos = strrpos($subPath, '\\')) {
$subPath = substr($subPath, 0, $lastPos);
$search = $subPath . '\\';
if (isset($this->prefixDirsPsr4[$search])) {
$pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
foreach ($this->prefixDirsPsr4[$search] as $dir) {
if (file_exists($file = $dir . $pathEnd)) {
return $file;
}
}
}
}
}
// PSR-4 fallback dirs
foreach ($this->fallbackDirsPsr4 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
return $file;
}
}
// PSR-0 lookup
if (false !== $pos = strrpos($class, '\\')) {
// namespaced class name
$logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
. strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
} else {
// PEAR-like class name
$logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
}
if (isset($this->prefixesPsr0[$first])) {
foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
if (0 === strpos($class, $prefix)) {
foreach ($dirs as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
}
}
}
// PSR-0 fallback dirs
foreach ($this->fallbackDirsPsr0 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
// PSR-0 include paths.
if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
return $file;
}
return false;
}
/**
* @return void
*/
private static function initializeIncludeClosure()
{
if (self::$includeFile !== null) {
return;
}
/**
* Scope isolated include.
*
* Prevents access to $this/self from included files.
*
* @param string $file
* @return void
*/
self::$includeFile = \Closure::bind(static function($file) {
include $file;
}, null, null);
}
}
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/build/scripts/phar-set-timestamps/vendor/composer/autoload_classmap.php | build/scripts/phar-set-timestamps/vendor/composer/autoload_classmap.php | <?php
// autoload_classmap.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php',
'Seld\\PharUtils\\Linter' => $vendorDir . '/seld/phar-utils/src/Linter.php',
'Seld\\PharUtils\\Timestamps' => $vendorDir . '/seld/phar-utils/src/Timestamps.php',
);
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/build/scripts/phar-set-timestamps/vendor/composer/platform_check.php | build/scripts/phar-set-timestamps/vendor/composer/platform_check.php | <?php
// platform_check.php @generated by Composer
$issues = array();
if (!(PHP_VERSION_ID >= 50300)) {
$issues[] = 'Your Composer dependencies require a PHP version ">= 5.3.0". You are running ' . PHP_VERSION . '.';
}
if ($issues) {
if (!headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');
}
if (!ini_get('display_errors')) {
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL);
} elseif (!headers_sent()) {
echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL;
}
}
trigger_error(
'Composer detected issues in your platform: ' . implode(' ', $issues),
E_USER_ERROR
);
}
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/build/scripts/phar-set-timestamps/vendor/seld/phar-utils/src/Timestamps.php | build/scripts/phar-set-timestamps/vendor/seld/phar-utils/src/Timestamps.php | <?php
/*
* This file is part of PHAR Utils.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Seld\PharUtils;
class Timestamps
{
private $contents;
/**
* @param string $file path to the phar file to use
*/
public function __construct($file)
{
$this->contents = file_get_contents($file);
}
/**
* Updates each file's unix timestamps in the PHAR
*
* The PHAR signature can then be produced in a reproducible manner.
*
* @param int|\DateTimeInterface|string $timestamp Date string or DateTime or unix timestamp to use
*/
public function updateTimestamps($timestamp = null)
{
if ($timestamp instanceof \DateTime || $timestamp instanceof \DateTimeInterface) {
$timestamp = $timestamp->getTimestamp();
} elseif (is_string($timestamp)) {
$timestamp = strtotime($timestamp);
} elseif (!is_int($timestamp)) {
$timestamp = strtotime('1984-12-24T00:00:00Z');
}
// detect manifest offset / end of stub
if (!preg_match('{__HALT_COMPILER\(\);(?: +\?>)?\r?\n}', $this->contents, $match, PREG_OFFSET_CAPTURE)) {
throw new \RuntimeException('Could not detect the stub\'s end in the phar');
}
// set starting position and skip past manifest length
$pos = $match[0][1] + strlen($match[0][0]);
$stubEnd = $pos + $this->readUint($pos, 4);
$pos += 4;
$numFiles = $this->readUint($pos, 4);
$pos += 4;
// skip API version (YOLO)
$pos += 2;
// skip PHAR flags
$pos += 4;
$aliasLength = $this->readUint($pos, 4);
$pos += 4 + $aliasLength;
$metadataLength = $this->readUint($pos, 4);
$pos += 4 + $metadataLength;
while ($pos < $stubEnd) {
$filenameLength = $this->readUint($pos, 4);
$pos += 4 + $filenameLength;
// skip filesize
$pos += 4;
// update timestamp to a fixed value
$timeStampBytes = pack('L', $timestamp);
$this->contents[$pos + 0] = $timeStampBytes[0];
$this->contents[$pos + 1] = $timeStampBytes[1];
$this->contents[$pos + 2] = $timeStampBytes[2];
$this->contents[$pos + 3] = $timeStampBytes[3];
// skip timestamp, compressed file size, crc32 checksum and file flags
$pos += 4*4;
$metadataLength = $this->readUint($pos, 4);
$pos += 4 + $metadataLength;
$numFiles--;
}
if ($numFiles !== 0) {
throw new \LogicException('All files were not processed, something must have gone wrong');
}
}
/**
* Saves the updated phar file, optionally with an updated signature.
*
* @param string $path
* @param int $signatureAlgo One of Phar::MD5, Phar::SHA1, Phar::SHA256 or Phar::SHA512
* @return bool
*/
public function save($path, $signatureAlgo)
{
$pos = $this->determineSignatureBegin();
$algos = array(
\Phar::MD5 => 'md5',
\Phar::SHA1 => 'sha1',
\Phar::SHA256 => 'sha256',
\Phar::SHA512 => 'sha512',
);
if (!isset($algos[$signatureAlgo])) {
throw new \UnexpectedValueException('Invalid hash algorithm given: '.$signatureAlgo.' expected one of Phar::MD5, Phar::SHA1, Phar::SHA256 or Phar::SHA512');
}
$algo = $algos[$signatureAlgo];
// re-sign phar
// signature
$signature = hash($algo, substr($this->contents, 0, $pos), true)
// sig type
. pack('L', $signatureAlgo)
// ohai Greg & Marcus
. 'GBMB';
$this->contents = substr($this->contents, 0, $pos) . $signature;
return file_put_contents($path, $this->contents);
}
private function readUint($pos, $bytes)
{
$res = unpack('V', substr($this->contents, $pos, $bytes));
return $res[1];
}
/**
* Determine the beginning of the signature.
*
* @return int
*/
private function determineSignatureBegin()
{
// detect signature position
if (!preg_match('{__HALT_COMPILER\(\);(?: +\?>)?\r?\n}', $this->contents, $match, PREG_OFFSET_CAPTURE)) {
throw new \RuntimeException('Could not detect the stub\'s end in the phar');
}
// set starting position and skip past manifest length
$pos = $match[0][1] + strlen($match[0][0]);
$manifestEnd = $pos + 4 + $this->readUint($pos, 4);
$pos += 4;
$numFiles = $this->readUint($pos, 4);
$pos += 4;
// skip API version (YOLO)
$pos += 2;
// skip PHAR flags
$pos += 4;
$aliasLength = $this->readUint($pos, 4);
$pos += 4 + $aliasLength;
$metadataLength = $this->readUint($pos, 4);
$pos += 4 + $metadataLength;
$compressedSizes = 0;
while (($numFiles > 0) && ($pos < $manifestEnd - 24)) {
$filenameLength = $this->readUint($pos, 4);
$pos += 4 + $filenameLength;
// skip filesize and timestamp
$pos += 2*4;
$compressedSizes += $this->readUint($pos, 4);
// skip compressed file size, crc32 checksum and file flags
$pos += 3*4;
$metadataLength = $this->readUint($pos, 4);
$pos += 4 + $metadataLength;
$numFiles--;
}
if ($numFiles !== 0) {
throw new \LogicException('All files were not processed, something must have gone wrong');
}
return $manifestEnd + $compressedSizes;
}
}
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/build/scripts/phar-set-timestamps/vendor/seld/phar-utils/src/Linter.php | build/scripts/phar-set-timestamps/vendor/seld/phar-utils/src/Linter.php | <?php
/*
* This file is part of PHAR Utils.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Seld\PharUtils;
class Linter
{
/**
* Lints all php files inside a given phar with the current PHP version
*
* @param string $path Phar file path
* @param list<string> $excludedPaths Paths which should be skipped by the linter
*/
public static function lint($path, array $excludedPaths = array())
{
$php = defined('PHP_BINARY') ? PHP_BINARY : 'php';
if ($isWindows = defined('PHP_WINDOWS_VERSION_BUILD')) {
$tmpFile = @tempnam(sys_get_temp_dir(), '');
if (!$tmpFile || !is_writable($tmpFile)) {
throw new \RuntimeException('Unable to create temp file');
}
$php = self::escapeWindowsPath($php);
$tmpFile = self::escapeWindowsPath($tmpFile);
// PHP 8 encloses the command in double-quotes
if (PHP_VERSION_ID >= 80000) {
$format = '%s -l %s';
} else {
$format = '"%s -l %s"';
}
$command = sprintf($format, $php, $tmpFile);
} else {
$command = "'".$php."' -l";
}
$descriptorspec = array(
0 => array('pipe', 'r'),
1 => array('pipe', 'w'),
2 => array('pipe', 'w')
);
// path to phar + phar:// + trailing slash
$baseLen = strlen(realpath($path)) + 7 + 1;
foreach (new \RecursiveIteratorIterator(new \Phar($path)) as $file) {
if ($file->isDir()) {
continue;
}
if (substr($file, -4) === '.php') {
$filename = (string) $file;
if (in_array(substr($filename, $baseLen), $excludedPaths, true)) {
continue;
}
if ($isWindows) {
file_put_contents($tmpFile, file_get_contents($filename));
}
$process = proc_open($command, $descriptorspec, $pipes);
if (is_resource($process)) {
if (!$isWindows) {
fwrite($pipes[0], file_get_contents($filename));
}
fclose($pipes[0]);
$stdout = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[2]);
$exitCode = proc_close($process);
if ($exitCode !== 0) {
if ($isWindows) {
$stderr = str_replace($tmpFile, $filename, $stderr);
}
throw new \UnexpectedValueException('Failed linting '.$file.': '.$stderr);
}
} else {
throw new \RuntimeException('Could not start linter process');
}
}
}
if ($isWindows) {
@unlink($tmpFile);
}
}
/**
* Escapes a Windows file path
*
* @param string $path
* @return string The escaped path
*/
private static function escapeWindowsPath($path)
{
// Quote if path contains spaces or brackets
if (strpbrk($path, " ()") !== false) {
$path = '"'.$path.'"';
}
return $path;
}
}
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
sebastianbergmann/foal | https://github.com/sebastianbergmann/foal/blob/5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8/build/config/php-scoper.php | build/config/php-scoper.php | <?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
return [
];
| php | BSD-3-Clause | 5bc5ed43be2b5e36a411bad5fbbe7ef8a881efd8 | 2026-01-05T04:43:58.906971Z | false |
maurobonfietti/slim4-api-skeleton | https://github.com/maurobonfietti/slim4-api-skeleton/blob/081a50ee6d85f1ff01e89d0a63562b571b7f9543/post-create-project-command.php | post-create-project-command.php | <?php
declare(strict_types=1);
echo <<<EOF
_____ _ _ _ _
/ ____| (_) | || |
| (___ | |_ _ __ ___ | || |_
\___ \| | | '_ ` _ \ |__ _|
____) | | | | | | | | | |
|_____/|_|_|_| |_| |_| |_| _
| __ \ | | /\ (_)
| |__) |___ ___| |_ / \ _ __ _
| _ // _ \/ __| __| / /\ \ | '_ \| |
| | \ \ __/\__ \ |_ / ____ \| |_) | |
|_|__\_\___||___/\__/_/ _ \_\ .__/|_|
/ ____| | | | | | | |
| (___ | | _____| | ___| |_ _|_| _ __
\___ \| |/ / _ \ |/ _ \ __/ _ \| '_ \
____) | < __/ | __/ || (_) | | | |
|_____/|_|\_\___|_|\___|\__\___/|_| |_|
\033[36m*************************************************************\033[37m
Project: https://github.com/maurobonfietti/slim4-api-skeleton
\033[36m*************************************************************\033[37m
\033[32mSuccessfully created project!\033[37m
Get started with the following commands:
$ cd [your-api-name]
$ composer test
$ composer start
\033[33mRemember!\033[37m
You need to set the MySQL connection in your dotenv file: '.env'.
\033[32mThanks for installing this project!\033[37m
\033[32mDonate:\033[37m https://ko-fi.com/maurobonfietti
Now go build a cool RESTful API ;-)
EOF;
unlink('.coveralls.yml');
unlink('.travis.yml');
unlink('post-create-project-command.php');
| php | MIT | 081a50ee6d85f1ff01e89d0a63562b571b7f9543 | 2026-01-05T04:44:09.079647Z | false |
maurobonfietti/slim4-api-skeleton | https://github.com/maurobonfietti/slim4-api-skeleton/blob/081a50ee6d85f1ff01e89d0a63562b571b7f9543/src/Controller/Home.php | src/Controller/Home.php | <?php
declare(strict_types=1);
namespace App\Controller;
use App\CustomResponse as Response;
use Pimple\Psr11\Container;
use Psr\Http\Message\ServerRequestInterface as Request;
final class Home
{
private const API_NAME = 'slim4-api-skeleton';
private const API_VERSION = '1.1.0';
private Container $container;
public function __construct(Container $container)
{
$this->container = $container;
}
public function getHelp(Request $request, Response $response): Response
{
$message = [
'api' => self::API_NAME,
'version' => self::API_VERSION,
'timestamp' => time(),
];
return $response->withJson($message);
}
public function getStatus(Request $request, Response $response): Response
{
$this->container->get('db');
$status = [
'status' => [
'database' => 'OK',
],
'api' => self::API_NAME,
'version' => self::API_VERSION,
'timestamp' => time(),
];
return $response->withJson($status);
}
}
| php | MIT | 081a50ee6d85f1ff01e89d0a63562b571b7f9543 | 2026-01-05T04:44:09.079647Z | false |
maurobonfietti/slim4-api-skeleton | https://github.com/maurobonfietti/slim4-api-skeleton/blob/081a50ee6d85f1ff01e89d0a63562b571b7f9543/src/App/Cors.php | src/App/Cors.php | <?php
declare(strict_types=1);
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\App;
return static function (App $app): void {
$app->options('/{routes:.+}', function (Request $request, Response $response) {
return $response;
});
$app->add(function (Request $request, $handler): Response {
$response = $handler->handle($request);
return $response
->withHeader('Access-Control-Allow-Origin', '*')
->withHeader(
'Access-Control-Allow-Headers',
'X-Requested-With, Content-Type, Accept, Origin, Authorization'
)
->withHeader(
'Access-Control-Allow-Methods',
'GET, POST, PUT, DELETE, PATCH, OPTIONS'
);
});
};
| php | MIT | 081a50ee6d85f1ff01e89d0a63562b571b7f9543 | 2026-01-05T04:44:09.079647Z | false |
maurobonfietti/slim4-api-skeleton | https://github.com/maurobonfietti/slim4-api-skeleton/blob/081a50ee6d85f1ff01e89d0a63562b571b7f9543/src/App/Database.php | src/App/Database.php | <?php
declare(strict_types=1);
$container['db'] = static function (): PDO {
$dsn = sprintf(
'mysql:host=%s;dbname=%s;port=%s;charset=utf8',
getenv('DB_HOST'),
getenv('DB_NAME'),
getenv('DB_PORT')
);
$pdo = new PDO($dsn, getenv('DB_USER'), getenv('DB_PASS'));
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
return $pdo;
};
| php | MIT | 081a50ee6d85f1ff01e89d0a63562b571b7f9543 | 2026-01-05T04:44:09.079647Z | false |
maurobonfietti/slim4-api-skeleton | https://github.com/maurobonfietti/slim4-api-skeleton/blob/081a50ee6d85f1ff01e89d0a63562b571b7f9543/src/App/Repositories.php | src/App/Repositories.php | <?php
declare(strict_types=1);
| php | MIT | 081a50ee6d85f1ff01e89d0a63562b571b7f9543 | 2026-01-05T04:44:09.079647Z | false |
maurobonfietti/slim4-api-skeleton | https://github.com/maurobonfietti/slim4-api-skeleton/blob/081a50ee6d85f1ff01e89d0a63562b571b7f9543/src/App/NotFound.php | src/App/NotFound.php | <?php
declare(strict_types=1);
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\App;
return static function (App $app): void {
$app->map(
['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
'/{routes:.+}',
function (Request $request): void {
throw new Slim\Exception\HttpNotFoundException($request);
}
);
};
| php | MIT | 081a50ee6d85f1ff01e89d0a63562b571b7f9543 | 2026-01-05T04:44:09.079647Z | false |
maurobonfietti/slim4-api-skeleton | https://github.com/maurobonfietti/slim4-api-skeleton/blob/081a50ee6d85f1ff01e89d0a63562b571b7f9543/src/App/Container.php | src/App/Container.php | <?php
declare(strict_types=1);
use Pimple\Container;
use Pimple\Psr11\Container as Psr11Container;
use Slim\Factory\AppFactory;
$container = new Container();
return AppFactory::create(
new ResponseFactory(),
new Psr11Container($container)
);
| php | MIT | 081a50ee6d85f1ff01e89d0a63562b571b7f9543 | 2026-01-05T04:44:09.079647Z | false |
maurobonfietti/slim4-api-skeleton | https://github.com/maurobonfietti/slim4-api-skeleton/blob/081a50ee6d85f1ff01e89d0a63562b571b7f9543/src/App/ResponseFactory.php | src/App/ResponseFactory.php | <?php
declare(strict_types=1);
use App\CustomResponse;
use Fig\Http\Message\StatusCodeInterface;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface as Response;
final class ResponseFactory implements ResponseFactoryInterface
{
public function createResponse(
int $code = StatusCodeInterface::STATUS_OK,
string $reasonPhrase = ''
): Response {
return (new CustomResponse())->withStatus($code, $reasonPhrase);
}
}
| php | MIT | 081a50ee6d85f1ff01e89d0a63562b571b7f9543 | 2026-01-05T04:44:09.079647Z | false |
maurobonfietti/slim4-api-skeleton | https://github.com/maurobonfietti/slim4-api-skeleton/blob/081a50ee6d85f1ff01e89d0a63562b571b7f9543/src/App/ErrorHandler.php | src/App/ErrorHandler.php | <?php
declare(strict_types=1);
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface;
return function (
ServerRequestInterface $request,
Throwable $exception,
bool $displayErrorDetails,
bool $logErrors,
bool $logErrorDetails
) use ($app): Response {
$statusCode = 500;
if (is_int($exception->getCode()) &&
$exception->getCode() >= 400 &&
$exception->getCode() <= 500
) {
$statusCode = $exception->getCode();
}
$className = new \ReflectionClass($exception::class);
$data = [
'message' => $exception->getMessage(),
'class' => $className->getShortName(),
'status' => 'error',
'code' => $statusCode,
];
$body = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
$response = $app->getResponseFactory()->createResponse();
$response->getBody()->write($body);
return $response
->withStatus($statusCode)
->withHeader('Content-type', 'application/problem+json');
};
| php | MIT | 081a50ee6d85f1ff01e89d0a63562b571b7f9543 | 2026-01-05T04:44:09.079647Z | false |
maurobonfietti/slim4-api-skeleton | https://github.com/maurobonfietti/slim4-api-skeleton/blob/081a50ee6d85f1ff01e89d0a63562b571b7f9543/src/App/App.php | src/App/App.php | <?php
declare(strict_types=1);
require __DIR__ . '/../../vendor/autoload.php';
require __DIR__ . '/DotEnv.php';
require_once __DIR__.'/CustomResponse.php';
require_once __DIR__.'/ResponseFactory.php';
$app = require __DIR__ . '/Container.php';
$customErrorHandler = require __DIR__ . '/ErrorHandler.php';
(require __DIR__ . '/Middlewares.php')($app, $customErrorHandler);
(require __DIR__ . '/Cors.php')($app);
(require __DIR__ . '/Database.php');
(require __DIR__ . '/Services.php');
(require __DIR__ . '/Repositories.php');
(require __DIR__ . '/Routes.php');
(require __DIR__ . '/NotFound.php')($app);
return $app;
| php | MIT | 081a50ee6d85f1ff01e89d0a63562b571b7f9543 | 2026-01-05T04:44:09.079647Z | false |
maurobonfietti/slim4-api-skeleton | https://github.com/maurobonfietti/slim4-api-skeleton/blob/081a50ee6d85f1ff01e89d0a63562b571b7f9543/src/App/DotEnv.php | src/App/DotEnv.php | <?php
declare(strict_types=1);
$baseDir = __DIR__ . '/../../';
$dotenv = Dotenv\Dotenv::createUnsafeImmutable($baseDir);
if (file_exists($baseDir . '.env')) {
$dotenv->load();
}
$dotenv->required(['DB_HOST', 'DB_NAME', 'DB_USER', 'DB_PASS', 'DB_PORT']);
| php | MIT | 081a50ee6d85f1ff01e89d0a63562b571b7f9543 | 2026-01-05T04:44:09.079647Z | false |
maurobonfietti/slim4-api-skeleton | https://github.com/maurobonfietti/slim4-api-skeleton/blob/081a50ee6d85f1ff01e89d0a63562b571b7f9543/src/App/CustomResponse.php | src/App/CustomResponse.php | <?php
declare(strict_types=1);
namespace App;
use Slim\Psr7\Response as ResponseBase;
final class CustomResponse extends ResponseBase
{
public function withJson(
$data,
int $status = 200,
int $encodingOptions = 0
): self {
$json = json_encode($data, $encodingOptions);
if ($json === false) {
throw new \RuntimeException(
json_last_error_msg(),
json_last_error()
);
}
$this->getBody()->write($json);
$responseWithJson = $this->withHeader(
'Content-Type',
'application/json;charset=utf-8'
);
if (isset($status)) {
return $responseWithJson->withStatus($status);
}
return $responseWithJson;
}
}
| php | MIT | 081a50ee6d85f1ff01e89d0a63562b571b7f9543 | 2026-01-05T04:44:09.079647Z | false |
maurobonfietti/slim4-api-skeleton | https://github.com/maurobonfietti/slim4-api-skeleton/blob/081a50ee6d85f1ff01e89d0a63562b571b7f9543/src/App/Routes.php | src/App/Routes.php | <?php
declare(strict_types=1);
$app->get('/', 'App\Controller\Home:getHelp');
$app->get('/status', 'App\Controller\Home:getStatus');
| php | MIT | 081a50ee6d85f1ff01e89d0a63562b571b7f9543 | 2026-01-05T04:44:09.079647Z | false |
maurobonfietti/slim4-api-skeleton | https://github.com/maurobonfietti/slim4-api-skeleton/blob/081a50ee6d85f1ff01e89d0a63562b571b7f9543/src/App/Services.php | src/App/Services.php | <?php
declare(strict_types=1);
| php | MIT | 081a50ee6d85f1ff01e89d0a63562b571b7f9543 | 2026-01-05T04:44:09.079647Z | false |
maurobonfietti/slim4-api-skeleton | https://github.com/maurobonfietti/slim4-api-skeleton/blob/081a50ee6d85f1ff01e89d0a63562b571b7f9543/src/App/Middlewares.php | src/App/Middlewares.php | <?php
declare(strict_types=1);
use Slim\App;
return static function (App $app, Closure $customErrorHandler): void {
$path = $_SERVER['SLIM_BASE_PATH'] ?? '';
$app->setBasePath($path);
$app->addRoutingMiddleware();
$app->addBodyParsingMiddleware();
$displayError = filter_var(
$_SERVER['DISPLAY_ERROR_DETAILS'] ?? false,
FILTER_VALIDATE_BOOLEAN
);
$errorMiddleware = $app->addErrorMiddleware($displayError, true, true);
$errorMiddleware->setDefaultErrorHandler($customErrorHandler);
};
| php | MIT | 081a50ee6d85f1ff01e89d0a63562b571b7f9543 | 2026-01-05T04:44:09.079647Z | false |
maurobonfietti/slim4-api-skeleton | https://github.com/maurobonfietti/slim4-api-skeleton/blob/081a50ee6d85f1ff01e89d0a63562b571b7f9543/tests/integration/TestCase.php | tests/integration/TestCase.php | <?php
declare(strict_types=1);
namespace Tests\integration;
use PHPUnit\Framework\TestCase as PHPUnit_TestCase;
use Slim\App;
use Slim\Psr7\Factory\StreamFactory;
use Slim\Psr7\Headers;
use Slim\Psr7\Request as SlimRequest;
use Slim\Psr7\Uri;
class TestCase extends PHPUnit_TestCase
{
protected function getAppInstance(): App
{
return require __DIR__ . '/../../src/App/App.php';
}
protected function createRequest(
string $method,
string $path,
string $query = '',
array $headers = ['HTTP_ACCEPT' => 'application/json'],
array $cookies = [],
array $serverParams = []
): SlimRequest {
$uri = new Uri('', '', 80, $path, $query);
$handle = fopen('php://temp', 'w+');
$stream = (new StreamFactory())->createStreamFromResource($handle);
$h = new Headers();
foreach ($headers as $name => $value) {
$h->addHeader($name, $value);
}
return new SlimRequest($method, $uri, $h, $cookies, $serverParams, $stream);
}
}
| php | MIT | 081a50ee6d85f1ff01e89d0a63562b571b7f9543 | 2026-01-05T04:44:09.079647Z | false |
maurobonfietti/slim4-api-skeleton | https://github.com/maurobonfietti/slim4-api-skeleton/blob/081a50ee6d85f1ff01e89d0a63562b571b7f9543/tests/integration/HomeTest.php | tests/integration/HomeTest.php | <?php
declare(strict_types=1);
namespace Tests\integration;
use Fig\Http\Message\StatusCodeInterface;
class HomeTest extends TestCase
{
public function testGetHelp(): void
{
$request = $this->createRequest('GET', '/');
$response = $this->getAppInstance()->handle($request);
$result = (string) $response->getBody();
$this->assertEquals(StatusCodeInterface::STATUS_OK, $response->getStatusCode());
$this->assertStringContainsString('api', $result);
$this->assertStringContainsString('version', $result);
$this->assertStringContainsString('time', $result);
$this->assertStringNotContainsString('error', $result);
}
public function testGetStatus(): void
{
$request = $this->createRequest('GET', '/status');
$response = $this->getAppInstance()->handle($request);
$result = (string) $response->getBody();
$this->assertEquals(StatusCodeInterface::STATUS_OK, $response->getStatusCode());
$this->assertStringContainsString('api', $result);
$this->assertStringContainsString('version', $result);
$this->assertStringContainsString('time', $result);
$this->assertStringContainsString('database', $result);
$this->assertStringNotContainsString('error', $result);
$this->assertStringNotContainsString('failed', $result);
$this->assertStringNotContainsString('PDOException', $result);
}
public function testPreflightOptions(): void
{
$request = $this->createRequest('OPTIONS', '/status');
$response = $this->getAppInstance()->handle($request);
$this->assertEquals(StatusCodeInterface::STATUS_OK, $response->getStatusCode());
}
public function testRouteNotFoundException(): void
{
$request = $this->createRequest('GET', '/notfound');
$response = $this->getAppInstance()->handle($request);
$result = (string) $response->getBody();
$this->assertEquals(StatusCodeInterface::STATUS_NOT_FOUND, $response->getStatusCode());
$this->assertStringContainsString('error', $result);
$this->assertStringContainsString('Not found.', $result);
$this->assertStringContainsString('HttpNotFoundException', $result);
}
}
| php | MIT | 081a50ee6d85f1ff01e89d0a63562b571b7f9543 | 2026-01-05T04:44:09.079647Z | false |
maurobonfietti/slim4-api-skeleton | https://github.com/maurobonfietti/slim4-api-skeleton/blob/081a50ee6d85f1ff01e89d0a63562b571b7f9543/tests/integration/CustomResponseTest.php | tests/integration/CustomResponseTest.php | <?php
namespace Tests\integration;
require_once __DIR__.'/../../src/App/CustomResponse.php';
require_once __DIR__.'/../../src/App/ResponseFactory.php';
use App\CustomResponse as Response;
use Slim\Factory\AppFactory;
use Psr\Http\Message\ServerRequestInterface as Request;
class CustomResponseTest extends TestCase
{
public function testWithJson()
{
$app = AppFactory::create(new \ResponseFactory());
$data = ['foo' => 'bar1&bar2'];
$app->get('/path', function (Request $request, Response $response) use ($data): Response {
return $response->withJson($data, 201);
});
$request = $this->createRequest('GET', '/path');
$response = $app->handle($request);
$this->assertEquals(201, $response->getStatusCode());
$this->assertEquals('application/json;charset=utf-8', $response->getHeaderLine('Content-Type'));
$body = $response->getBody();
$body->rewind();
$dataJson = $body->getContents();
$this->assertEquals('{"foo":"bar1&bar2"}', $dataJson);
$this->assertEquals($data['foo'], json_decode($dataJson, true)['foo']);
}
public function testWithJsonEncodingOption()
{
$app = AppFactory::create(new \ResponseFactory());
$data = ['foo' => 'bar1&bar2'];
$app->get('/path', function (Request $request, Response $response) use ($data): Response {
return $response->withJson($data, 200, JSON_HEX_AMP);
});
$request = $this->createRequest('GET', '/path');
$response = $app->handle($request);
$body = $response->getBody();
$body->rewind();
$dataJson = $body->getContents();
$this->assertEquals('{"foo":"bar1\u0026bar2"}', $dataJson);
$this->assertEquals($data['foo'], json_decode($dataJson, true)['foo']);
}
public function testWithJsonThrowsException()
{
$app = AppFactory::create(new \ResponseFactory());
$data = ["text" => "\xB1\x31"];
$app->get('/path', function (Request $request, Response $response) use ($data): Response {
return $response->withJson($data, 200);
});
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('Malformed UTF-8 characters, possibly incorrectly encoded');
$request = $this->createRequest('GET', '/path');
$app->handle($request);
}
}
| php | MIT | 081a50ee6d85f1ff01e89d0a63562b571b7f9543 | 2026-01-05T04:44:09.079647Z | false |
maurobonfietti/slim4-api-skeleton | https://github.com/maurobonfietti/slim4-api-skeleton/blob/081a50ee6d85f1ff01e89d0a63562b571b7f9543/public/index.php | public/index.php | <?php
declare(strict_types=1);
require __DIR__ . '/../src/App/App.php';
$app->run();
| php | MIT | 081a50ee6d85f1ff01e89d0a63562b571b7f9543 | 2026-01-05T04:44:09.079647Z | false |
yllw-digital/laravel-chatgpt-mock-api | https://github.com/yllw-digital/laravel-chatgpt-mock-api/blob/3b5cd52bcc247bef63f11d72a2b74ddebe55972a/src/LaravelChatgptMockApi.php | src/LaravelChatgptMockApi.php | <?php
namespace YellowDigital\LaravelChatgptMockApi;
use Illuminate\Database\Eloquent\Casts\Json;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Http;
use YellowDigital\LaravelChatgptMockApi\Models\ChatgptMockResponse;
class LaravelChatgptMockApi
{
public function generate(
string $prompt,
int $count = 1,
array $keys,
string $model = 'gpt-3.5-turbo',
bool $cache = true
): JsonResponse {
if($cache && $cachedResponse = $this->getCachedResponse($prompt, $count, $keys, $model)) {
return $cachedResponse;
}
$openAiKey = config('chatgpt-mock-api.openai_key');
if(!$openAiKey) {
throw new \Exception('OpenAI key not set. Please set the OPENAI_API_KEY environment variable.');
}
$implodedKeys = implode(', ', $keys);
$chatGptRequest = Http::withHeaders([
'Authorization' => "Bearer {$openAiKey}",
"Content-Type" => "application/json"
])->post('https://api.openai.com/v1/chat/completions', [
'model' => $model,
'messages' => [
[
'role' => 'user',
'content' => "You are a mock API JSON response generator. I will give you a prompt that the user entered that describes the data he wants, and then the keys that the data should have. Your response should only be the JSON, and must not contain any text before or after (such as: Below is your data). The prompt is: {$prompt}. The keys are: {$implodedKeys}. The number of entries that the JSON should have is: {$count}."
]
]
])->json();
try {
$response = json_decode($chatGptRequest['choices'][0]['message']['content']);
} catch(\Exception $e) {
throw new \Exception('OpenAI returned an invalid response. Please check your prompt and keys. Response: ' . json_encode($chatGptRequest));
}
$this->cacheResponse($prompt, $count, $keys, $model, $response);
return response()->json($response);
}
private function getCachedResponse(
string $prompt,
int $count,
array $keys,
string $model
): ?JsonResponse {
$hashSum = md5($prompt . $count . implode('', $keys) . $model);
$existingChatGptMockResponse = ChatgptMockResponse::where('hashsum', $hashSum)->first();
if($existingChatGptMockResponse) {
return response()->json(json_decode($existingChatGptMockResponse->response));
}
return null;
}
private function cacheResponse(
string $prompt,
int $count,
array $keys,
string $model,
array|object $response
): void {
$hashSum = md5($prompt . $count . implode('', $keys) . $model);
ChatGptMockResponse::where('hashsum', $hashSum)->delete();
ChatgptMockResponse::create([
'hashsum' => $hashSum,
'prompt' => $prompt,
'response' => json_encode($response)
]);
}
}
| php | MIT | 3b5cd52bcc247bef63f11d72a2b74ddebe55972a | 2026-01-05T04:44:26.558138Z | false |
yllw-digital/laravel-chatgpt-mock-api | https://github.com/yllw-digital/laravel-chatgpt-mock-api/blob/3b5cd52bcc247bef63f11d72a2b74ddebe55972a/src/LaravelChatgptMockApiServiceProvider.php | src/LaravelChatgptMockApiServiceProvider.php | <?php
namespace YellowDigital\LaravelChatgptMockApi;
use Spatie\LaravelPackageTools\Package;
use Spatie\LaravelPackageTools\PackageServiceProvider;
use YellowDigital\LaravelChatgptMockApi\Commands\LaravelChatgptMockApiCommand;
class LaravelChatgptMockApiServiceProvider extends PackageServiceProvider
{
public function configurePackage(Package $package): void
{
$package
->name('laravel-chatgpt-mock-api')
->hasConfigFile()
->hasMigration('create_chatgpt_mock_responses_table');
}
}
| php | MIT | 3b5cd52bcc247bef63f11d72a2b74ddebe55972a | 2026-01-05T04:44:26.558138Z | false |
yllw-digital/laravel-chatgpt-mock-api | https://github.com/yllw-digital/laravel-chatgpt-mock-api/blob/3b5cd52bcc247bef63f11d72a2b74ddebe55972a/src/Facades/ChatGPTMockApi.php | src/Facades/ChatGPTMockApi.php | <?php
namespace YellowDigital\LaravelChatgptMockApi\Facades;
use Illuminate\Support\Facades\Facade;
/**
* @see \YellowDigital\LaravelChatgptMockApi\LaravelChatgptMockApi
*/
class ChatGPTMockApi extends Facade
{
protected static function getFacadeAccessor()
{
return \YellowDigital\LaravelChatgptMockApi\LaravelChatgptMockApi::class;
}
}
| php | MIT | 3b5cd52bcc247bef63f11d72a2b74ddebe55972a | 2026-01-05T04:44:26.558138Z | false |
yllw-digital/laravel-chatgpt-mock-api | https://github.com/yllw-digital/laravel-chatgpt-mock-api/blob/3b5cd52bcc247bef63f11d72a2b74ddebe55972a/src/Models/ChatgptMockResponse.php | src/Models/ChatgptMockResponse.php | <?php
namespace YellowDigital\LaravelChatgptMockApi\Models;
use Illuminate\Database\Eloquent\Model;
class ChatgptMockResponse extends Model {
protected $guarded = [];
} | php | MIT | 3b5cd52bcc247bef63f11d72a2b74ddebe55972a | 2026-01-05T04:44:26.558138Z | false |
yllw-digital/laravel-chatgpt-mock-api | https://github.com/yllw-digital/laravel-chatgpt-mock-api/blob/3b5cd52bcc247bef63f11d72a2b74ddebe55972a/config/chatgpt-mock-api.php | config/chatgpt-mock-api.php | <?php
return [
'openai_key' => env('OPENAI_API_KEY', ''),
];
| php | MIT | 3b5cd52bcc247bef63f11d72a2b74ddebe55972a | 2026-01-05T04:44:26.558138Z | false |
johansatge/workflowy-php | https://github.com/johansatge/workflowy-php/blob/8e8f802f492f03b2e7d67f86d70191865978f951/sample.php | sample.php | <?php
/**
* Sample usage
*/
date_default_timezone_set('Europe/Paris');
$sep = str_repeat('-', 20) . "\n";
$date = date('Y-m-d H:i:s');
require_once 'vendor/autoload.php';
use WorkFlowyPHP\WorkFlowy;
use WorkFlowyPHP\WorkFlowyException;
use WorkFlowyPHP\WorkFlowyList;
use WorkFlowyPHP\WorkFlowyAccount;
/**
* Session
*/
echo $sep;
$session_id = null;
try
{
$session_id = WorkFlowy::login('workflowy-php@protonmail.com', require('sample_password.php'));
echo 'Session ID: ' . $session_id . "\n";
}
catch (WorkFlowyException $e)
{
echo 'Connection error: ' . $e->getMessage() . "\n";
}
/**
* Account
*/
$account_request = new WorkFlowyAccount($session_id);
echo $sep;
echo 'Username: ' . $account_request->getUsername() . "\n";
echo 'Email: ' . $account_request->getEmail() . "\n";
echo 'Registration date: ' . $account_request->getRegistrationDate() . "\n";
echo 'Registration time: ' . $account_request->getRegistrationDate('timestamp') . "\n";
echo 'Theme: ' . $account_request->getTheme() . "\n";
echo 'Items created in month: ' . $account_request->getItemsCreatedInMonth() . "\n";
echo 'Monthly quota: ' . $account_request->getMonthlyQuota() . "\n";
/**
* Lists
*/
$list_request = new WorkFlowyList($session_id);
$list = $list_request->getList();
$sublist = $list->searchSublist('#Sample sublist#');
echo $sep;
echo 'List ID: ' . $sublist->getID() . "\n";
echo 'List name: ' . $sublist->getName() . "\n";
echo 'List modified date: ' . date('Y-m-d H:i:s', $sublist->getLastModifiedTime()) . "\n";
echo 'List description: ' . $sublist->getDescription() . "\n";
echo 'List is completed: ' . ($sublist->isComplete() ? 'yes' : 'no') . "\n";
echo 'List completion time: ' . date('Y-m-d H:i:s', $sublist->getCompletedTime()) . "\n";
echo $sep;
echo 'List OPML: ' . $sublist->getOPML() . "\n";
$sublist->createSublist('Sample created sublist', 'With sample description ' . $date, 999);
$sublist->setName('Sample sublist ' . $date);
$sublist->setDescription('Sample description ' . $date);
// var_dump($sublist->getParent());
// var_dump($sublist->getOPML());
// var_dump($sublist->getSublists());
// $sublist->setParent($list, 2);
// $sublist->setComplete(true || false);
| php | MIT | 8e8f802f492f03b2e7d67f86d70191865978f951 | 2026-01-05T04:44:38.278253Z | false |
johansatge/workflowy-php | https://github.com/johansatge/workflowy-php/blob/8e8f802f492f03b2e7d67f86d70191865978f951/src/autoload.php | src/autoload.php | <?php
/* WorkFlowyPHP - https://github.com/johansatge/workflowy-php */
spl_autoload_register(function ($namespaced_class)
{
preg_match_all('/WorkFlowyPHP\\\(WorkFlowy[a-zA-Z]{0,})/ ', $namespaced_class, $class);
$path = rtrim(dirname(__FILE__), '/') . '/WorkFlowyPHP/' . (!empty($class[1][0]) ? $class[1][0] : '') . '.php';
if (is_readable($path))
{
require $path;
}
}); | php | MIT | 8e8f802f492f03b2e7d67f86d70191865978f951 | 2026-01-05T04:44:38.278253Z | false |
johansatge/workflowy-php | https://github.com/johansatge/workflowy-php/blob/8e8f802f492f03b2e7d67f86d70191865978f951/src/WorkFlowyPHP/WorkFlowyOPML.php | src/WorkFlowyPHP/WorkFlowyOPML.php | <?php
/* WorkFlowyPHP - https://github.com/johansatge/workflowy-php */
namespace WorkFlowyPHP;
class WorkFlowyOPML
{
private $sublist;
/**
* Builds an OPML exporter by using the given list
* @param WorkFlowySublist $sublist
* @throws WorkFlowyException
*/
public function __construct($sublist)
{
if (!is_a($sublist, '\WorkFlowyPHP\WorkFlowySublist'))
{
throw new WorkFlowyException('Sublist must be a WorkFlowySublist instance');
}
$this->sublist = $sublist;
}
/**
* Exports the given list
* @param int $depth
* @return string
*/
public function export($depth = 0)
{
$depth = intval($depth);
return $this->getHeader($depth) . $this->getBody($depth) . $this->getFooter($depth);
}
/**
* Gets the OPML header
* @param int $depth
* @return string
*/
private function getHeader($depth)
{
$opml = '';
if ($depth == 0)
{
$opml .= '<?xml version="1.0"?>' . "\n" . '<opml version="2.0">' . "\n" . '<head>' . "\n" . '<ownerEmail></ownerEmail>' . "\n" . '</head>' . "\n" . '<body>' . "\n";
}
if ($this->sublist->getParent() !== false)
{
$tag = '<outline%s text="%s" _note="%s"' . (count($this->sublist->getSublists()) == 0 ? ' />' : '>') . "\n";
$opml .= sprintf($tag, $this->sublist->isComplete() ? ' _complete="true"' : '', $this->esc($this->sublist->getName()), $this->esc($this->sublist->getDescription()));
}
return $opml;
}
/**
* Gets the OPML body
* @param int $depth
* @return string
*/
private function getBody($depth)
{
$opml = '';
foreach ($this->sublist->getSublists() as $sublist)
{
$exporter = new WorkFlowyOPML($sublist);
$opml .= $exporter->export($depth + 1);
}
return $opml;
}
/**
* Gets the OPML footer
* @param int $depth
* @return string
*/
private function getFooter($depth)
{
$opml = '';
if ($this->sublist->getParent() !== false)
{
$opml .= count($this->sublist->getSublists()) > 0 ? '</outline>' . "\n" : '';
}
if ($depth == 0)
{
$opml .= '</body>' . "\n" . '</opml>';
}
return $opml;
}
/**
* Escapes the given string
* @param string $string
* @return string
*/
private function esc($string)
{
return htmlspecialchars($string);
}
}
| php | MIT | 8e8f802f492f03b2e7d67f86d70191865978f951 | 2026-01-05T04:44:38.278253Z | false |
johansatge/workflowy-php | https://github.com/johansatge/workflowy-php/blob/8e8f802f492f03b2e7d67f86d70191865978f951/src/WorkFlowyPHP/WorkFlowy.php | src/WorkFlowyPHP/WorkFlowy.php | <?php
/* WorkFlowyPHP - https://github.com/johansatge/workflowy-php */
namespace WorkFlowyPHP;
class WorkFlowy
{
/**
* Tries to login using the given credentials
* @param string $username
* @param string $password
* @throws WorkFlowyException
* @return string
*/
public static function login($username, $password)
{
$transport = new WorkFlowyTransport();
$answer = $transport->loginRequest($username, $password);
if ($answer !== false)
{
return $answer;
}
throw new WorkFlowyException('Could not open the session with those credentials');
}
}
| php | MIT | 8e8f802f492f03b2e7d67f86d70191865978f951 | 2026-01-05T04:44:38.278253Z | false |
johansatge/workflowy-php | https://github.com/johansatge/workflowy-php/blob/8e8f802f492f03b2e7d67f86d70191865978f951/src/WorkFlowyPHP/WorkFlowyList.php | src/WorkFlowyPHP/WorkFlowyList.php | <?php
/* WorkFlowyPHP - https://github.com/johansatge/workflowy-php */
namespace WorkFlowyPHP;
class WorkFlowyList
{
private $transport;
private $parents;
private $sublists;
private $dateJoinedTimestampInSeconds = 0;
/**
* Builds a WorkFlowy list
* The class holds the hierarchic relations between all its sublists (parents / children)
* @param string $session_id
* @throws WorkFlowyException
*/
public function __construct($session_id)
{
$this->transport = new WorkFlowyTransport($session_id);
}
/**
* Returns the main list
* @return WorkFlowySublist
*/
public function getList()
{
$data = $this->transport->apiRequest('get_initialization_data');
$raw_lists = array();
if (!empty($data['projectTreeData']['mainProjectTreeInfo']['rootProjectChildren']))
{
$raw_lists = $data['projectTreeData']['mainProjectTreeInfo']['rootProjectChildren'];
}
if (!empty($data['projectTreeData']['mainProjectTreeInfo']['dateJoinedTimestampInSeconds']))
{
$this->dateJoinedTimestampInSeconds = $data['projectTreeData']['mainProjectTreeInfo']['dateJoinedTimestampInSeconds'];
}
$this->parents = array();
$this->sublists = array();
return $this->parseList(array('id' => 'None', 'nm' => null, 'no' => null, 'cp' => null, 'lm' => 0, 'ch' => $raw_lists), false);
}
/**
* Recursively parses the given list and builds an object
* @param array $raw_list
* @param string $parent_id
* @return WorkFlowyList
*/
private function parseList($raw_list, $parent_id)
{
$id = !empty($raw_list['id']) ? $raw_list['id'] : '';
$name = !empty($raw_list['nm']) ? $raw_list['nm'] : '';
$description = !empty($raw_list['no']) ? $raw_list['no'] : '';
$raw_sublists = !empty($raw_list['ch']) && is_array($raw_list['ch']) ? $raw_list['ch'] : array();
// Complete & last modified dates are offsets, starting at the user's registration date (in seconds)
$complete = !empty($raw_list['cp']) ? $this->dateJoinedTimestampInSeconds + $raw_list['cp'] : false;
$last_modified = !empty($raw_list['lm']) ? $this->dateJoinedTimestampInSeconds + $raw_list['lm'] : 0;
$sublists = array();
foreach ($raw_sublists as $raw_sublist)
{
$sublists[] = $this->parseList($raw_sublist, $id);
}
$sublist = new WorkFlowySublist($id, $name, $description, $complete, $last_modified, $sublists, $this, $this->transport);
if (!empty($parent_id))
{
$this->parents[$id] = $parent_id;
}
$this->sublists[$id] = $sublist;
return $sublist;
}
/**
* Tries to return the parent of the given sublist ID
* @param string $id
* @return bool
*/
public function getSublistParent($id)
{
$parent_id = is_string($id) && !empty($this->parents[$id]) ? $this->parents[$id] : false;
return !empty($this->sublists[$parent_id]) ? $this->sublists[$parent_id] : false;
}
}
| php | MIT | 8e8f802f492f03b2e7d67f86d70191865978f951 | 2026-01-05T04:44:38.278253Z | false |
johansatge/workflowy-php | https://github.com/johansatge/workflowy-php/blob/8e8f802f492f03b2e7d67f86d70191865978f951/src/WorkFlowyPHP/WorkFlowyTransport.php | src/WorkFlowyPHP/WorkFlowyTransport.php | <?php
/* WorkFlowyPHP - https://github.com/johansatge/workflowy-php */
namespace WorkFlowyPHP;
class WorkFlowyTransport
{
const LOGIN_URL = 'https://workflowy.com/ajax_login';
const API_URL = 'https://workflowy.com/%s';
const TIMEOUT = 5;
private $sessionID;
private $clientID;
private $mostRecentOperationTransactionId;
/**
* Builds a transport object, by using the providden session ID if needed
* The class manages all communications with the server (login, CRUD list requests, account requests..)
* @param bool $session_id
* @throws WorkFlowyException
*/
public function __construct($session_id = false)
{
if ($session_id !== false && (!is_string($session_id) || !preg_match('/^[a-z0-9]{32}$/', $session_id)))
{
throw new WorkFlowyException('Invalid session ID');
}
$this->sessionID = $session_id;
}
/**
* Performs a list request
* @param string $action
* @param array $data
* @throws WorkFlowyException
* @return array
*/
public function listRequest($action, $data)
{
if (!is_string($action) || !is_array($data))
{
throw new WorkFlowyException('Invalid list request');
}
$this->apiRequest('push_and_poll', array(
'client_id' => $this->clientID,
'client_version' => 14,
'push_poll_id' => 'MSQBGpdw', // @todo make this dynamic
'push_poll_data' => json_encode(array((object)array(
'most_recent_operation_transaction_id' => $this->mostRecentOperationTransactionId,
'operations' => array((object)array('type' => $action, 'data' => (object)$data))
)))
));
}
/**
* Makes an API request and returns the answer
* @param string $method
* @param array $data
* @throws WorkFlowyException
* @return array
*/
public function apiRequest($method, $data = array())
{
if (empty($this->sessionID))
{
throw new WorkFlowyException('A session ID is needed to make API calls');
}
if (!is_string($method) || !is_array($data))
{
throw new WorkFlowyException('Invalid API request');
}
$raw_data = $this->curl(sprintf(self::API_URL, $method), $data);
$json = json_decode($raw_data, true);
if ($json === null)
{
throw new WorkFlowyException('Could not decode JSON');
}
if (!empty($json['projectTreeData']['mainProjectTreeInfo']['initialMostRecentOperationTransactionId']))
{
$this->mostRecentOperationTransactionId = $json['projectTreeData']['mainProjectTreeInfo']['initialMostRecentOperationTransactionId'];
$this->clientID = $json['projectTreeData']['clientId'];
}
if (!empty($json['results'][0]['new_most_recent_operation_transaction_id']))
{
$this->mostRecentOperationTransactionId = $json['results'][0]['new_most_recent_operation_transaction_id'];
}
if (!empty($json['results'][0]['error']))
{
throw new WorkFlowyException('An error occurred when executing the API request');
}
return $json;
}
/**
* Makes a login request and returns the session ID on success
* @param string $username
* @param string $password
* @throws WorkFlowyException
* @return bool
*/
public function loginRequest($username, $password)
{
if (empty($username) || empty($password) || !is_string($username) || !is_string($password))
{
throw new WorkFlowyException('You must provide credentials as strings');
}
$headers = [];
$raw_data = $this->curl(
self::LOGIN_URL,
array('username' => $username, 'password' => $password, 'next' => ''),
$headers
);
if (!empty($headers['set-cookie']) && is_array($headers['set-cookie'])) {
foreach ($headers['set-cookie'] as $cookie) {
$matches = [];
if (preg_match('`^sessionid=([a-z0-9]+);`mis', $cookie, $matches)) {
return $matches[1];
}
}
}
return false;
}
/**
* Sends a CURL request to the server, by using the given POST data
* @param string $url
* @param array $post_fields
* @throws WorkFlowyException
* @return array|string
*/
private function curl($url, $post_fields, &$headers = [])
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, self::TIMEOUT);
$headers = [];
// Code from https://stackoverflow.com/a/41135574/696517
// This function is called by curl for each header received
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($curl, $header) use (&$headers) {
$len = strlen($header);
$header = explode(':', $header, 2);
if (count($header) < 2) { // ignore invalid headers
return $len;
}
$name = strtolower(trim($header[0]));
if (!array_key_exists($name, $headers)) {
$headers[$name] = [trim($header[1])];
} else {
$headers[$name][] = trim($header[1]);
}
return $len;
});
if (count($post_fields) > 0)
{
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
}
if (!empty($this->sessionID))
{
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Cookie: sessionid=' . $this->sessionID));
}
$raw_data = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
if (!empty($error))
{
throw new WorkFlowyException($error);
}
return $raw_data;
}
}
| php | MIT | 8e8f802f492f03b2e7d67f86d70191865978f951 | 2026-01-05T04:44:38.278253Z | false |
johansatge/workflowy-php | https://github.com/johansatge/workflowy-php/blob/8e8f802f492f03b2e7d67f86d70191865978f951/src/WorkFlowyPHP/WorkFlowyAccount.php | src/WorkFlowyPHP/WorkFlowyAccount.php | <?php
/* WorkFlowyPHP - https://github.com/johansatge/workflowy-php */
namespace WorkFlowyPHP;
class WorkFlowyAccount
{
private $transport;
private $username;
private $theme;
private $email;
private $itemsCreatedInMonth;
private $monthlyQuota;
private $registrationDate;
/**
* Builds a WorkFlowy account
* The class holds the account informations associated to the given session
* @param string $session_id
* @throws WorkFlowyException
*/
public function __construct($session_id)
{
$this->transport = new WorkFlowyTransport($session_id);
$data = $this->transport->apiRequest('get_initialization_data');
$this->username = !empty($data['settings']['username']) ? $data['settings']['username'] : '';
$this->theme = !empty($data['settings']['theme']) ? $data['settings']['theme'] : '';
$this->email = !empty($data['settings']['email']) ? $data['settings']['email'] : '';
$this->itemsCreatedInMonth = !empty($data['projectTreeData']['mainProjectTreeInfo']['itemsCreatedInCurrentMonth']) ? intval($data['projectTreeData']['mainProjectTreeInfo']['itemsCreatedInCurrentMonth']) : 0;
$this->monthlyQuota = !empty($data['projectTreeData']['mainProjectTreeInfo']['monthlyItemQuota']) ? intval($data['projectTreeData']['mainProjectTreeInfo']['monthlyItemQuota']) : 0;
$this->registrationDate = !empty($data['projectTreeData']['mainProjectTreeInfo']['dateJoinedTimestampInSeconds']) ? intval($data['projectTreeData']['mainProjectTreeInfo']['dateJoinedTimestampInSeconds']) : 0;
}
/**
* Returns the username
* @return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Returns the current theme name
* @return string
*/
public function getTheme()
{
return $this->theme;
}
/**
* Returns the email address
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Returns the number of items created on the current month
* @return int
*/
public function getItemsCreatedInMonth()
{
return $this->itemsCreatedInMonth;
}
/**
* Gets the user monthly quota
* @return int
*/
public function getMonthlyQuota()
{
return $this->monthlyQuota;
}
/**
* Gets the user registration date
* Takes a date format, or "timestamp" to get the raw value
* @param string $format
* @throws WorkFlowyException
* @return string
*/
public function getRegistrationDate($format = 'Y-m-d H:i:s')
{
if (is_string($format) && !empty($format))
{
return $format == 'timestamp' ? $this->registrationDate : date($format, $this->registrationDate);
}
throw new WorkFlowyException('Invalid date format');
}
}
| php | MIT | 8e8f802f492f03b2e7d67f86d70191865978f951 | 2026-01-05T04:44:38.278253Z | false |
johansatge/workflowy-php | https://github.com/johansatge/workflowy-php/blob/8e8f802f492f03b2e7d67f86d70191865978f951/src/WorkFlowyPHP/WorkFlowySublist.php | src/WorkFlowyPHP/WorkFlowySublist.php | <?php
/* WorkFlowyPHP - https://github.com/johansatge/workflowy-php */
namespace WorkFlowyPHP;
class WorkFlowySublist
{
private $id;
private $name;
private $complete;
private $description;
private $lastModified;
private $sublists;
private $list;
private $transport;
/**
* Builds a recursive list
* This class is used to read a list content or update it
* /!\ Keep in mind than on update, the list content will not be impacted
* For instance, when modyfing the description, the getDescription method will still return the old value
* @param string $id
* @param string $name
* @param string $description
* @param bool $complete
* @param int $last_modified
* @param array $sublists
* @param WorkFlowyList $list
* @param WorkFlowyTransport $transport
* @throws WorkFlowyException
*/
public function __construct($id, $name, $description, $complete, $last_modified, $sublists, $list, $transport)
{
$this->id = is_string($id) ? $id : '';
$this->name = is_string($name) ? $name : '';
$this->description = is_string($description) ? $description : '';
$this->lastModified = is_numeric($last_modified) ? $last_modified : 0;
$this->complete = is_numeric($complete) ? $complete : false;
$this->sublists = array();
if (is_array($sublists))
{
foreach ($sublists as $sublist)
{
if (!is_a($sublist, '\WorkFlowyPHP\WorkFlowySublist'))
{
throw new WorkFlowyException('Sublists must be WorkFlowySublist instances');
}
$this->sublists[] = $sublist;
}
}
if (!is_a($list, '\WorkFlowyPHP\WorkFlowyList'))
{
throw new WorkFlowyException('List must be a WorkFlowyList instance');
}
$this->list = $list;
if (!is_a($transport, '\WorkFlowyPHP\WorkFlowyTransport'))
{
throw new WorkFlowyException('Transport must be a WorkFlowyTransport instance');
}
$this->transport = $transport;
}
/**
* Returns the list ID
* @return string
*/
public function getID()
{
return $this->id;
}
/**
* Returns the list name
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Returns the list description
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Returns the last modification time
* @return int
*/
public function getLastModifiedTime()
{
return $this->lastModified;
}
/**
* Returns the completed time (if available, false otherwise)
* @return int|bool
*/
public function getCompletedTime()
{
return $this->complete;
}
/**
* Returns the parent of the list
* @return bool|WorkFlowySublist
*/
public function getParent()
{
return $this->list->getSublistParent($this->id);
}
/**
* Returns the completion status of the list
* @return bool
*/
public function isComplete()
{
return $this->complete !== false;
}
/**
* Returns the OPML view
* @return string
*/
public function getOPML()
{
$exporter = new WorkFlowyOPML($this);
return $exporter->export();
}
/**
* Returns an array of sublists
* @return array
*/
public function getSublists()
{
return $this->sublists;
}
/**
* Search recursively if the list name matches the given expression
* @param string $expression
* @param array $params
* @throws WorkFlowyException
* @return bool|WorkFlowySublist
*/
public function searchSublist($expression, $params = array())
{
if (!is_string($expression) || preg_match($expression, null) === false)
{
throw new WorkFlowyException('Search expression must be a valid regular expression');
}
$get_all = is_array($params) && !empty($params['get_all']) && $params['get_all'] ? true : false;
$matches = array();
if (preg_match($expression, $this->name))
{
if (!$get_all)
{
return $this;
}
$matches[] = $this;
}
foreach ($this->sublists as $child)
{
$match = $child->searchSublist($expression, array('get_all' => $get_all));
if ($match !== false && !$get_all)
{
return $match;
}
if ($get_all)
{
$matches = array_merge($matches, $match);
}
}
return $get_all ? $matches : false;
}
/**
* Sets the list name
* @param string $name
* @throws WorkFlowyException
*/
public function setName($name)
{
if (!is_string($name))
{
throw new WorkFlowyException('Name must be a string');
}
$this->transport->listRequest('edit', array('projectid' => $this->id, 'name' => $name));
}
/**
* Sets the list description
* @param string $description
* @throws WorkFlowyException
*/
public function setDescription($description)
{
if (!is_string($description))
{
throw new WorkFlowyException('Description must be a string');
}
$this->transport->listRequest('edit', array('projectid' => $this->id, 'description' => $description));
}
/**
* Sets the list completion status
* @param bool $complete
* @throws WorkFlowyException
*/
public function setComplete($complete)
{
if (!is_bool($complete))
{
throw new WorkFlowyException('Completion status must be boolean');
}
$this->transport->listRequest(($complete ? 'complete' : 'uncomplete'), array('projectid' => $this->id));
}
/**
* Sets the parent and priority of the list
* @param WorkFlowySublist $parent_sublist
* @param int $priority
* @throws WorkFlowyException
*/
public function setParent($parent_sublist, $priority)
{
if (empty($parent_sublist) || !is_a($parent_sublist, __CLASS__))
{
throw new WorkFlowyException('Parent sublist must be a ' . __CLASS__ . ' instance');
}
$this->transport->listRequest('move', array(
'projectid' => $this->id,
'parentid' => $parent_sublist->getID(),
'priority' => intval($priority)
));
}
/**
* Delets the current sublist
* This will also delete its children
*/
public function delete()
{
$this->transport->listRequest('delete', array('projectid' => $this->id));
}
/**
* Creates a sublist
* @param string $name
* @param string $description
* @param int $priority
* @throws WorkFlowyException
*/
public function createSublist($name, $description, $priority)
{
if ((!empty($name) && !is_string($name)) || (!empty($description) && !is_string($description)))
{
throw new WorkFlowyException('Name and description must be strings');
}
$new_id = $this->generateID();
$this->transport->listRequest('create', array(
'projectid' => $new_id,
'parentid' => $this->id,
'priority' => intval($priority)
));
if (!empty($name))
{
$this->transport->listRequest('edit', array('projectid' => $new_id, 'name' => $name));
}
if (!empty($description))
{
$this->transport->listRequest('edit', array('projectid' => $new_id, 'description' => $description));
}
}
private function generateID()
{
//return((1+Math.random())*65536|0).toString(16).substring(1)
// k()+k()+" - "+k()+" - "+k()+" - "+k()+" - "+k()+k()+k()
return preg_replace_callback('#r#', function ()
{
return substr(base_convert((1 + ((float)rand() / (float)getrandmax())) * 65536 | 0, 10, 16), 1);
}, 'rr-r-r-r-rrr');
}
}
| php | MIT | 8e8f802f492f03b2e7d67f86d70191865978f951 | 2026-01-05T04:44:38.278253Z | false |
johansatge/workflowy-php | https://github.com/johansatge/workflowy-php/blob/8e8f802f492f03b2e7d67f86d70191865978f951/src/WorkFlowyPHP/WorkFlowyException.php | src/WorkFlowyPHP/WorkFlowyException.php | <?php
/* WorkFlowyPHP - https://github.com/johansatge/workflowy-php */
namespace WorkFlowyPHP;
class WorkFlowyException extends \Exception
{
protected $message;
protected $code;
/**
* Builds a custom WorkFlowy exception
* For now, uses the \Exception behavior
* @param string $message
* @param int $code
*/
public function __construct($message, $code = 0)
{
$this->message = is_string($message) ? $message : '';
$this->code = is_int($code) ? $code : 0;
}
}
| php | MIT | 8e8f802f492f03b2e7d67f86d70191865978f951 | 2026-01-05T04:44:38.278253Z | false |
imanghafoori1/laravel-decorator | https://github.com/imanghafoori1/laravel-decorator/blob/b6d69dc8cd94d3cc37796dfefe734017db4233d1/src/DecoratableFacade.php | src/DecoratableFacade.php | <?php
namespace Imanghafoori\Decorator;
use Illuminate\Support\Facades\Facade;
class DecoratableFacade extends Facade
{
use IamDecoratable;
}
| php | MIT | b6d69dc8cd94d3cc37796dfefe734017db4233d1 | 2026-01-05T04:44:39.081554Z | false |
imanghafoori1/laravel-decorator | https://github.com/imanghafoori1/laravel-decorator/blob/b6d69dc8cd94d3cc37796dfefe734017db4233d1/src/DecoratorServiceProvider.php | src/DecoratorServiceProvider.php | <?php
namespace Imanghafoori\Decorator;
use Illuminate\Support\ServiceProvider;
use Imanghafoori\Decorator\Decorators\DecoratorFactory;
class DecoratorServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton(DecoratorFactory::class);
$this->app->singleton(Decorator::class);
$this->app->singleton('decorator', Decorator::class);
}
}
| php | MIT | b6d69dc8cd94d3cc37796dfefe734017db4233d1 | 2026-01-05T04:44:39.081554Z | false |
imanghafoori1/laravel-decorator | https://github.com/imanghafoori1/laravel-decorator/blob/b6d69dc8cd94d3cc37796dfefe734017db4233d1/src/Decorator.php | src/Decorator.php | <?php
namespace Imanghafoori\Decorator;
use Illuminate\Container\Container;
use ReflectionFunction;
use ReflectionMethod;
class Decorator
{
/**
* All the decorators for method calls.
*
* @var array<string, array>
*/
protected $globalDecorators = [];
/**
* All the decorator names and definitions.
*
* @var array<string, array>
*/
protected $decorations = [];
/**
* Defines a new decorator with name.
*
* @param string $name
* @param callable $callback
* @return void
*/
public function define($name, $callback)
{
$this->globalDecorators[$name] = $callback;
}
/**
* @param $name
* @return mixed|null
*/
public function getGlobalDecorator($name)
{
return $this->globalDecorators[$name] ?? null;
}
public function getDecorationsFor($callback)
{
return $this->decorations[$callback] ?? [];
}
/**
* Decorates a callable with a defined decorator name.
*
* @param string $callback
* @param mixed $decorator
* @return void
*/
public function decorate($callback, $decorator)
{
$this->decorations[$callback][] = $decorator;
}
/**
* Calls a class@method with it's specified decorators.
*
* @param string $callback
* @param array $parameters
* @param string|null $defaultMethod
* @return mixed
*/
public function call($callback, array $parameters = [], $defaultMethod = null)
{
if (is_array($callback)) {
$callback = $this->normalizeMethod($callback);
}
$decorators = $this->getDecorationsFor($callback);
$callback = $this->decorateWith($callback, $decorators);
$parameters = $this->getCallParams($callback, $parameters);
return Container::getInstance()->call($callback, $parameters, $defaultMethod);
}
public function unDecorate($decorated, $decorator = null)
{
if (is_null($decorator)) {
unset($this->decorations[$decorated]);
} else {
$this->decorations[$decorated] = array_diff($this->decorations[$decorated], [$decorator]);
}
}
private function normalizeMethod($callback)
{
$class = is_string($callback[0]) ? $callback[0] : get_class($callback[0]);
return "{$class}@{$callback[1]}";
}
/**
* @param $callable
* @param array $decorators
* @return mixed
*
* @throws \ReflectionException
*/
public function decorateWith($callable, array $decorators)
{
foreach ($decorators as $decorator) {
if (is_string($decorator) && ! self::contains($decorator, '@')) {
$decorator = $this->globalDecorators[$decorator];
}
is_array($decorator)
? $params = $this->getCallParams($this->normalizeMethod($decorator), [$callable])
: $params = $this->getCallParams($decorator, [$callable]);
$callable = Container::getInstance()->call($decorator, $params);
}
return $callable;
}
/**
* @param $callable
* @param $decorators
* @param $params
* @return mixed
*/
public function callOnlyWith($callable, $decorators, $params)
{
$callable = $this->decorateWith($callable, $decorators);
return Container::getInstance()->make($callable, $params);
}
/**
* get App::Call Callable Parameters.
*
* @param $callable
* @param array $params
* @return array
*
* @throws \ReflectionException
*/
public function getCallParams($callable, array $params)
{
if (is_callable($callable)) {
$argName = $this->getFunctionArgNames($callable);
} else {
$class = explode('@', $callable);
$argName = $this->getMethodArgNames($class[0], $class[1]);
}
$parameters = array_map(function ($MArgName, $Parameters) use ($argName) {
return [$MArgName ?? $argName[count($argName) - 1] => $Parameters];
}, $argName, $params);
count($parameters) == 1
? $parameters = $parameters[0]
: $parameters = array_merge_recursive($parameters[0], $parameters[1]);
return $parameters;
}
/**
* @throws \ReflectionException
* @throws \ReflectionException
*/
private function getMethodArgNames($className, $methodName)
{
return $this->getParameterNames(new ReflectionMethod($className, $methodName));
}
/**
* @throws \ReflectionException
*/
private function getFunctionArgNames($funcName)
{
return $this->getParameterNames(new ReflectionFunction($funcName));
}
private static function contains($haystack, $needle)
{
return mb_strpos($haystack, $needle) !== false;
}
private function getParameterNames($reflection)
{
return array_map(fn ($param) => $param->name, $reflection->getParameters());
}
}
| php | MIT | b6d69dc8cd94d3cc37796dfefe734017db4233d1 | 2026-01-05T04:44:39.081554Z | false |
imanghafoori1/laravel-decorator | https://github.com/imanghafoori1/laravel-decorator/blob/b6d69dc8cd94d3cc37796dfefe734017db4233d1/src/IamDecoratable.php | src/IamDecoratable.php | <?php
namespace Imanghafoori\Decorator;
use Illuminate\Container\Container;
trait IamDecoratable
{
/**
* The decorators for resolved object instances of the facade.
*
* @var array<string, array>
*/
protected static $decorations = [];
/**
* The decorators for all the methods.
*
* @var array
*/
protected static $classDecorations = [];
public static function decorateMethod($method, $decorator)
{
foreach ((array) $method as $m) {
static::$decorations[$m][] = $decorator;
}
}
public static function decorateAll($decorator)
{
foreach ((array) $decorator as $d) {
static::$classDecorations[] = $d;
}
}
public static function getDecorations($method)
{
return static::$decorations[$method] ?? [];
}
public static function forgetDecorations($method = null)
{
if ($method) {
unset(static::$decorations[$method]);
} elseif (is_null($method)) {
static::$decorations = [];
static::$classDecorations = [];
}
}
/**
* Handle dynamic, static calls to the object.
*
* @param string $method
* @param array $args
* @return mixed
*
* @throws \RuntimeException
*/
public static function __callStatic($method, $args)
{
$callback = fn (...$args) => parent::__callStatic($method, $args);
$decorators = self::getDecorations($method) + static::$classDecorations;
$callback = Container::getInstance()->make(Decorator::class)->decorateWith($callback, $decorators);
return $callback(...$args);
}
}
| php | MIT | b6d69dc8cd94d3cc37796dfefe734017db4233d1 | 2026-01-05T04:44:39.081554Z | false |
imanghafoori1/laravel-decorator | https://github.com/imanghafoori1/laravel-decorator/blob/b6d69dc8cd94d3cc37796dfefe734017db4233d1/src/Facade/Decorator.php | src/Facade/Decorator.php | <?php
namespace Imanghafoori\Decorator\Facade;
use Illuminate\Support\Facades\Facade as LaravelFacade;
/**
* Class Decorator.
*
* @method static define($name, $callback)
* @method static decorate($callback, $decorator)
* @method static call($callback, array $parameters = [], $defaultMethod = null)
* @method static unDecorate($decorated, $decorator = null)
*/
class Decorator extends LaravelFacade
{
protected static function getFacadeAccessor()
{
return 'decorator';
}
}
| php | MIT | b6d69dc8cd94d3cc37796dfefe734017db4233d1 | 2026-01-05T04:44:39.081554Z | false |
imanghafoori1/laravel-decorator | https://github.com/imanghafoori1/laravel-decorator/blob/b6d69dc8cd94d3cc37796dfefe734017db4233d1/src/Decorators/DecoratorFactory.php | src/Decorators/DecoratorFactory.php | <?php
namespace Imanghafoori\Decorator\Decorators;
use Closure;
use Illuminate\Container\Container;
class DecoratorFactory
{
public static function cache($key, $minutes = 1)
{
return self::getDecoratorFactory($key, 'remember', $minutes);
}
public static function foreverCache($key)
{
return self::getDecoratorFactory($key, 'rememberForever');
}
public static function variadicParam()
{
return fn ($callable) => function (...$param) use ($callable) {
return Container::getInstance()->call($callable, is_array($param[0]) ? $param[0] : $param);
};
}
/**
* @param $key
* @param $minutes
* @param $remember
* @return \Closure
*/
private static function getDecoratorFactory($key, $remember, $minutes = null): Closure
{
return fn ($callable) => fn (...$params) => DecoratorFactory::call($callable, $params, $key, $minutes, $remember);
}
private static function call($callable, array $params, $key, $minutes, $remember)
{
$caller = fn () => Container::getInstance()->call($callable, $params);
if (is_callable($key)) {
$key = $key(...$params);
}
$args = array_filter([$key, $minutes, $caller], fn ($value) => ! is_null($value));
return Container::getInstance()->make('cache')->$remember(...$args);
}
}
| php | MIT | b6d69dc8cd94d3cc37796dfefe734017db4233d1 | 2026-01-05T04:44:39.081554Z | false |
imanghafoori1/laravel-decorator | https://github.com/imanghafoori1/laravel-decorator/blob/b6d69dc8cd94d3cc37796dfefe734017db4233d1/tests/CacheResultDecoratorTest.php | tests/CacheResultDecoratorTest.php | <?php
use Illuminate\Container\Container;
use Imanghafoori\Decorator\Decorators\DecoratorFactory;
class CacheResultDecoratorTest extends TestCase
{
public function testCacheResultDecorator()
{
Container::getInstance()->singleton('abc', cachee::class);
\MyFacade::forgetDecorations('getGiven');
\MyFacade::decorateMethod('getGiven', DecoratorFactory::cache('hello', 2));
$this->assertEquals('We may never know?!', \MyFacade::getGiven(1));
$this->assertEquals('We may never know?!', \MyFacade::getGiven(1));
$this->assertEquals('We may never know?!', \MyFacade::getGiven(1));
$this->assertEquals(1, cachee::$counter);
\MyFacade::forgetDecorations('getGiven');
// clean up:
cachee::$counter = 0;
}
public function testPermanentCacheResultDecorator()
{
Container::getInstance()->singleton('abc', cachee::class);
\MyFacade::forgetDecorations('getGiven');
\MyFacade::decorateMethod('getGiven', DecoratorFactory::foreverCache(
fn ($a) => 'cache_key_'.$a)
);
cachee::$counter = 0;
$this->assertEquals('We may never know?!', \MyFacade::getGiven(1));
$this->assertEquals('We may never know?!', \MyFacade::getGiven(1));
$this->assertEquals('We may never know?!', \MyFacade::getGiven(2));
$this->assertEquals('We may never know?!', \MyFacade::getGiven(1));
$this->assertEquals('We may never know?!', \MyFacade::getGiven(2));
$this->assertEquals('We may never know?!', \MyFacade::getGiven(2));
$this->assertEquals('We may never know?!', \MyFacade::getGiven(1));
$this->assertEquals(2, cachee::$counter);
\MyFacade::forgetDecorations('getGiven');
}
}
class cachee
{
public static $counter = 0;
public function getGiven()
{
self::$counter++;
return 'We may never know?!';
}
}
| php | MIT | b6d69dc8cd94d3cc37796dfefe734017db4233d1 | 2026-01-05T04:44:39.081554Z | false |
imanghafoori1/laravel-decorator | https://github.com/imanghafoori1/laravel-decorator/blob/b6d69dc8cd94d3cc37796dfefe734017db4233d1/tests/FrameworkIntegrationTest.php | tests/FrameworkIntegrationTest.php | <?php
use Imanghafoori\Decorator\Facade\Decorator;
class FrameworkIntegrationTest extends TestCase
{
public function testDecoratableFacade()
{
Decorator::define('stringifyResult', ResultCasterDecorator::class.'@_toString');
Decorator::decorate(Calculator::class.'@add', 'stringifyResult');
$result = Decorator::call(Calculator::class.'@add', [-10, -10]);
$this->assertIsString($result);
$this->assertEquals('-20', $result);
}
}
| php | MIT | b6d69dc8cd94d3cc37796dfefe734017db4233d1 | 2026-01-05T04:44:39.081554Z | false |
imanghafoori1/laravel-decorator | https://github.com/imanghafoori1/laravel-decorator/blob/b6d69dc8cd94d3cc37796dfefe734017db4233d1/tests/DecoratableFacadeTest.php | tests/DecoratableFacadeTest.php | <?php
use Illuminate\Container\Container;
use Imanghafoori\Decorator\Decorator;
use Imanghafoori\Decorator\IamDecoratable;
class DecoratableFacadeTest extends TestCase
{
public function testDecoratableFacade()
{
Container::getInstance()->singleton('abc', abc::class);
\MyFacade::forgetDecorations('getGiven');
\MyFacade::decorateMethod('getGiven', function ($f) {
return function () {
};
});
$this->assertNull(\MyFacade::getGiven(1));
$this->assertNull(\MyFacade::getGiven(2));
\MyFacade::decorateMethod('getGiven', function ($f) {
return function () {
return 'hello;';
};
});
$this->assertEquals('hello;', \MyFacade::getGiven('hello;'));
\MyFacade::forgetDecorations();
}
public function testDecoratableFacade2()
{
Container::getInstance()->singleton('abc', abc::class);
Container::getInstance()->make(Decorator::class)->define('stringifyResult', [ResultCasterDecorator::class, 'toStringStaticDecorator']);
\MyFacade::forgetDecorations();
\MyFacade::decorateMethod('getGiven', 'stringifyResult');
$this->assertIsString(\MyFacade::getGiven(1));
$this->assertEquals('2', \MyFacade::getGiven(2));
\MyFacade::forgetDecorations('getGiven');
}
public function testStaticMethodsAsDecoratorsOnFacades()
{
Container::getInstance()->singleton('abc', abc::class);
\MyFacade::decorateMethod('getGiven', ResultCasterDecorator::class.'@toStringDecorator');
$this->assertIsString(\MyFacade::getGiven(1));
$this->assertEquals('2', \MyFacade::getGiven(2));
\MyFacade::forgetDecorations('getGiven');
}
public function testFacadeClassDecorators()
{
Container::getInstance()->singleton('abc', abc::class);
\MyFacade::decorateAll(ResultCasterDecorator::class.'@minimumParamZero');
\MyFacade::decorateAll(ResultCasterDecorator::class.'@toStringDecorator');
$this->assertEquals('1', \MyFacade::getGiven(1));
$this->assertEquals('0', \MyFacade::getGiven(-2));
$this->assertIsString(\MyFacade::getGiven(-11));
\MyFacade::forgetDecorations('getGiven');
}
public function testFacadeClassDecoratorsCombination()
{
Container::getInstance()->singleton('abc', abc::class);
\MyFacade::decorateMethod('getGiven', ResultCasterDecorator::class.'@minimumParamZero');
\MyFacade::decorateAll(ResultCasterDecorator::class.'@toStringDecorator');
$this->assertEquals('1', \MyFacade::getGiven(1));
$this->assertEquals('0', \MyFacade::getGiven(-2));
$this->assertIsString(\MyFacade::getGiven(-2));
$this->assertIsString(\MyFacade::getGiven(-11));
\MyFacade::forgetDecorations('getGiven');
}
}
class MyFacade extends \Imanghafoori\Decorator\DecoratableFacade
{
protected static function getFacadeAccessor()
{
return 'abc';
}
}
class MyFacadeWithTrait extends \Illuminate\Support\Facades\Facade
{
use IamDecoratable;
protected static function getFacadeAccessor()
{
return 'abc';
}
}
class abc
{
public function getGiven($a)
{
return $a;
}
}
| php | MIT | b6d69dc8cd94d3cc37796dfefe734017db4233d1 | 2026-01-05T04:44:39.081554Z | false |
imanghafoori1/laravel-decorator | https://github.com/imanghafoori1/laravel-decorator/blob/b6d69dc8cd94d3cc37796dfefe734017db4233d1/tests/TestCase.php | tests/TestCase.php | <?php
abstract class TestCase extends Orchestra\Testbench\TestCase
{
protected function getPackageProviders($app)
{
return [\Imanghafoori\Decorator\DecoratorServiceProvider::class];
}
}
| php | MIT | b6d69dc8cd94d3cc37796dfefe734017db4233d1 | 2026-01-05T04:44:39.081554Z | false |
imanghafoori1/laravel-decorator | https://github.com/imanghafoori1/laravel-decorator/blob/b6d69dc8cd94d3cc37796dfefe734017db4233d1/tests/DecoratorTest.php | tests/DecoratorTest.php | <?php
use Illuminate\Container\Container;
use Imanghafoori\Decorator\Decorator;
class DecoratorTest extends TestCase
{
public function testSimpleDecorator()
{
$decorator = new Decorator();
$decorator->define('stringifyResult', ResultCasterDecorator::class.'@_toString');
$decorator->decorate(Calculator::class.'@add', 'stringifyResult');
$result = $decorator->call(Calculator::class.'@add', [-10, -10]);
$this->assertIsString($result);
$this->assertEquals('-20', $result);
$result = $decorator->call([Calculator::class, 'add'], [-10, -10]);
$this->assertIsString($result);
$this->assertEquals('-20', $result);
$result = $decorator->call([new Calculator(), 'add'], [-10, -10]);
$this->assertIsString($result);
$this->assertEquals('-20', $result);
$decorator->unDecorate(Calculator::class.'@add', 'stringifyResult');
$result = $decorator->call(Calculator::class.'@add', [-10, -10]);
$this->assertEquals(-20, $result);
$this->assertIsInt($result);
$decorator->decorate(Calculator::class.'@add', 'stringifyResult');
$decorator->unDecorate(Calculator::class.'@add');
$result = $decorator->call(Calculator::class.'@add', [-10, -10]);
$this->assertEquals(-20, $result);
$this->assertIsInt($result);
}
public function testDecoratedWithCallbacks()
{
$decorator = new Decorator();
$decorator->decorate(Calculator::class.'@add', $this->getResultCasterDecorator());
$result = $decorator->call([new Calculator(), 'add'], [-10, -10]);
$this->assertIsString($result);
$this->assertEquals('-20', $result);
$decorator = new Decorator();
$decorator->decorate(Calculator::class.'@add', ResultCasterDecorator::class.'@toStringDecorator');
$result = $decorator->call([new Calculator(), 'add'], [-10, -10]);
$this->assertIsString($result);
$this->assertEquals('-20', $result);
$decorator = new Decorator();
$decorator->decorate(Calculator::class.'@addToStr', [ResultCasterDecorator::class, 'toInt']);
$result = $decorator->call([new Calculator(), 'addToStr'], [-10, -10]);
$this->assertIsInt($result);
$this->assertEquals(-20, $result);
$decorator = new Decorator();
$decorator->decorate(Calculator::class.'@addToStr', ResultCasterDecorator::class.'@toInt');
$result = $decorator->call([new Calculator(), 'addToStr'], [-10, -10]);
$this->assertIsInt($result);
$this->assertEquals(-20, $result);
}
public function testSimpleDecoratorOnInterface()
{
$decorator = new Decorator();
$decorator->define('stringifyResult', $this->getResultCasterDecorator());
$decorator->decorate(ICalculator::class.'@add', 'stringifyResult');
Container::getInstance()->bind(ICalculator::class, Calculator::class);
$result = $decorator->call(ICalculator::class.'@add', [10, 10]);
$this->assertIsString($result);
$this->assertEquals('20', $result);
}
public function testTwoDecorators()
{
$decorator = new Decorator();
$stringifyDecorator = function ($decorated) {
return function (...$params) use ($decorated) {
return (string) Container::getInstance()->call($decorated, Container::getInstance()->make('decorator')->getCallParams($decorated, $params[0]));
};
};
$intifyParamsDecorator = function ($decorated) {
return function ($x, $y) use ($decorated) {
return Container::getInstance()->call($decorated, Container::getInstance()->make('decorator')->getCallParams($decorated, [(int) $x, (int) $y]));
};
};
$decorator->define('stringifyResult', $stringifyDecorator);
$decorator->define('intifyParams', $intifyParamsDecorator);
$decorator->decorate(Calculator::class.'@add', 'intifyParams');
$decorator->decorate(Calculator::class.'@add', 'stringifyResult');
$result = $decorator->call(Calculator::class.'@add', ['-10', '-10']);
$this->assertIsString($result);
$this->assertEquals('-20', $result);
}
public function testMultipleDecorators()
{
$decorator = new Decorator();
$decorator->define('minParam:-20', function ($callback) {
return function ($x, $y) use ($callback) {
$x = ($x < -20) ? -20 : $x;
$y = ($y < -20) ? -20 : $y;
return Container::getInstance()->call($callback, Container::getInstance()->make('decorator')->getCallParams($callback, [$x, $y]));
};
});
$decorator->define('maxResult:20', $this->maxResult(20));
$decorator->define('stringifyResult', $this->getResultCasterDecorator());
$decorator->decorate(Calculator::class.'@add', 'minParam:-20');
$decorator->decorate(Calculator::class.'@add', 'maxResult:20');
$decorator->decorate(Calculator::class.'@add', 'stringifyResult');
$result = $decorator->call(Calculator::class.'@add', ['x' => 2, 'y' => 2]);
$this->assertEquals('4', $result);
$this->assertIsString($result);
$result = $decorator->call(Calculator::class.'@add', ['x' => 20, 'y' => 20]);
$this->assertEquals('20', $result);
$this->assertIsString($result);
$result = $decorator->call(Calculator::class.'@add', ['x' => -200, 'y' => -200]);
$this->assertEquals('-40', $result);
$this->assertIsString($result);
$result = $decorator->call(Calculator::class.'@add', ['x' => -100, 'y' => -100]);
$this->assertEquals('-40', $result);
$this->assertIsString($result);
}
/**
* @return \Closure
*/
public function getResultCasterDecorator()
{
return function ($callable) {
return function (...$params) use ($callable) {
return (string) Container::getInstance()->call($callable, Container::getInstance()->make('decorator')->getCallParams($callable, $params[0]));
};
};
}
/**
* @param int $max
* @return \Closure
*/
private function maxResult(int $max): Closure
{
return function ($callable) use ($max) {
return function (...$params) use ($callable, $max) {
$result = Container::getInstance()->call($callable, Container::getInstance()->make('decorator')->getCallParams($callable, $params[0]));
return ($result > $max) ? $max : $result;
};
};
}
}
interface ICalculator
{
public function add(int $x, int $y): int;
}
class Calculator implements ICalculator
{
public function add(int $x, int $y): int
{
return $x + $y;
}
public function addToStr(int $x, int $y): string
{
return (string) ($x + $y);
}
}
class ResultCasterDecorator
{
public function toStringDecorator($callable)
{
return function (...$params) use ($callable) {
return (string) Container::getInstance()->call($callable, Container::getInstance()->make('decorator')->getCallParams($callable, is_array($params[0]) ? $params[0] : $params));
};
}
public function minimumParamZero($callable)
{
return function (...$params) use ($callable) {
foreach ($params as $i => $param) {
if ($param < 0) {
$params[$i] = 0;
}
}
return Container::getInstance()->call($callable, $params);
};
}
public static function toStringStaticDecorator($callable)
{
return function (...$params) use ($callable) {
return (string) Container::getInstance()->call($callable, $params);
};
}
public static function toInt($callable)
{
return function (...$params) use ($callable) {
return (int) Container::getInstance()->call($callable, Container::getInstance()->make('decorator')->getCallParams($callable, is_array($params[0]) ? $params[0] : $params));
};
}
public function _toString($callable)
{
return function (...$params) use ($callable) {
return (string) Container::getInstance()->call($callable, ['x' => $params[0][0], 'y' => $params[0][1]]);
};
}
}
| php | MIT | b6d69dc8cd94d3cc37796dfefe734017db4233d1 | 2026-01-05T04:44:39.081554Z | false |
TheSoftwareHouse/fogger | https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Kernel.php | src/Kernel.php | <?php
namespace App;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\Routing\RouteCollectionBuilder;
class Kernel extends BaseKernel
{
use MicroKernelTrait;
const CONFIG_EXTS = '.{php,xml,yaml,yml}';
public function getCacheDir()
{
return $this->getProjectDir().'/var/cache/'.$this->environment;
}
public function getLogDir()
{
return $this->getProjectDir().'/var/log';
}
public function registerBundles()
{
$contents = require $this->getProjectDir().'/config/bundles.php';
foreach ($contents as $class => $envs) {
if (isset($envs['all']) || isset($envs[$this->environment])) {
yield new $class();
}
}
}
protected function configureContainer(ContainerBuilder $container, LoaderInterface $loader)
{
$container->addResource(new FileResource($this->getProjectDir().'/config/bundles.php'));
// Feel free to remove the "container.autowiring.strict_mode" parameter
// if you are using symfony/dependency-injection 4.0+ as it's the default behavior
$container->setParameter('container.autowiring.strict_mode', true);
$container->setParameter('container.dumper.inline_class_loader', true);
$confDir = $this->getProjectDir().'/config';
$loader->load($confDir.'/{packages}/*'.self::CONFIG_EXTS, 'glob');
$loader->load($confDir.'/{packages}/'.$this->environment.'/**/*'.self::CONFIG_EXTS, 'glob');
$loader->load($confDir.'/{services}'.self::CONFIG_EXTS, 'glob');
$loader->load($confDir.'/{services}_'.$this->environment.self::CONFIG_EXTS, 'glob');
}
protected function configureRoutes(RouteCollectionBuilder $routes)
{
$confDir = $this->getProjectDir().'/config';
$routes->import($confDir.'/{routes}/*'.self::CONFIG_EXTS, '/', 'glob');
$routes->import($confDir.'/{routes}/'.$this->environment.'/**/*'.self::CONFIG_EXTS, '/', 'glob');
$routes->import($confDir.'/{routes}'.self::CONFIG_EXTS, '/', 'glob');
}
}
| php | MIT | 733ebda8ad9bec0a903f8252da8e242525de24f6 | 2026-01-05T04:45:10.065464Z | false |
TheSoftwareHouse/fogger | https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Config/ConfigFactory.php | src/Config/ConfigFactory.php | <?php
namespace App\Config;
use App\Config\Model\Config;
use Doctrine\DBAL\Connection;
class ConfigFactory
{
private $sourceSchemaManager;
private $tableConfigFactory;
public function __construct(Connection $connection, TableConfigFactory $tableConfigFactory)
{
$this->sourceSchemaManager = $connection->getSchemaManager();
$this->tableConfigFactory = $tableConfigFactory;
}
public function createFromDBAL()
{
$dbalTables = $this->sourceSchemaManager->listTables();
$config = new Config();
foreach ($dbalTables as $dbalTable) {
$config->addTable($dbalTable->getName(), $this->tableConfigFactory->createFromDBALTable($dbalTable));
}
return $config;
}
}
| php | MIT | 733ebda8ad9bec0a903f8252da8e242525de24f6 | 2026-01-05T04:45:10.065464Z | false |
TheSoftwareHouse/fogger | https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Config/TableConfigFactory.php | src/Config/TableConfigFactory.php | <?php
namespace App\Config;
use App\Config\Model\TableConfig;
use Doctrine\DBAL\Schema as DBAL;
class TableConfigFactory
{
private $columnConfigFactory;
public function __construct(ColumnConfigFactory $columnConfigFactory)
{
$this->columnConfigFactory = $columnConfigFactory;
}
public function createFromDBALTable(DBAL\Table $dbalTable)
{
$table = new TableConfig();
foreach ($dbalTable->getColumns() as $dbalColumn) {
$table->addColumn(
$dbalColumn->getName(),
$this->columnConfigFactory->createFromDBALColumn($dbalColumn)
);
}
return $table;
}
}
| php | MIT | 733ebda8ad9bec0a903f8252da8e242525de24f6 | 2026-01-05T04:45:10.065464Z | false |
TheSoftwareHouse/fogger | https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Config/ConfigLoader.php | src/Config/ConfigLoader.php | <?php
namespace App\Config;
use App\Config\Model\Config;
use Symfony\Component\Serializer\Encoder\YamlEncoder;
use Symfony\Component\Serializer\SerializerInterface;
class ConfigLoader
{
public const DEFAULT_FILENAME = 'fogger.yaml';
public const DIRECTORY = '/fogger';
private $serializer;
public function __construct(SerializerInterface $serializer)
{
$this->serializer = $serializer;
}
public static function forgePath(string $filename): string
{
return sprintf("%s/%s", self::DIRECTORY, $filename ?? self::DEFAULT_FILENAME);
}
public function save(Config $config, ?string $filename = null)
{
file_put_contents(
self::forgePath($filename),
$this->serializer->serialize($config, YamlEncoder::FORMAT, ['yaml_inline' => 4])
);
}
public function load(string $filename): Config
{
/** @var Config $config */
$config = $this->serializer->deserialize(
file_get_contents(self::forgePath($filename)),
Config::class,
YamlEncoder::FORMAT
);
return $config;
}
}
| php | MIT | 733ebda8ad9bec0a903f8252da8e242525de24f6 | 2026-01-05T04:45:10.065464Z | false |
TheSoftwareHouse/fogger | https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Config/StrategyExtractor.php | src/Config/StrategyExtractor.php | <?php
namespace App\Config;
use App\Config\Model\ColumnConfig;
class StrategyExtractor
{
private const PATTERN = '/fogger::(\w+)({.*})*/';
public function extract(string $comment = null): ColumnConfig
{
preg_match(self::PATTERN, $comment, $matches);
$name = $matches[1] ?? 'none';
$options = json_decode($matches[2] ?? '[]', true);
return new ColumnConfig($name, $options);
}
}
| php | MIT | 733ebda8ad9bec0a903f8252da8e242525de24f6 | 2026-01-05T04:45:10.065464Z | false |
TheSoftwareHouse/fogger | https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Config/ColumnConfigFactory.php | src/Config/ColumnConfigFactory.php | <?php
namespace App\Config;
use App\Config\Model\ColumnConfig;
use Doctrine\DBAL\Schema as DBAL;
class ColumnConfigFactory
{
private $extractor;
public function __construct(StrategyExtractor $extractor)
{
$this->extractor = $extractor;
}
public function createFromDBALColumn(DBAL\Column $dbalColumn): ColumnConfig
{
return $this->extractor->extract($dbalColumn->getComment());
}
}
| php | MIT | 733ebda8ad9bec0a903f8252da8e242525de24f6 | 2026-01-05T04:45:10.065464Z | false |
TheSoftwareHouse/fogger | https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Config/Model/ColumnConfig.php | src/Config/Model/ColumnConfig.php | <?php
namespace App\Config\Model;
class ColumnConfig
{
const NONE_STRATEGY = 'none';
private $maskStrategy;
private $options;
public function __construct(string $maskStrategy = self::NONE_STRATEGY, array $options = [])
{
$this->maskStrategy = $maskStrategy;
$this->options = $options;
}
public function getMaskStrategy(): string
{
return $this->maskStrategy;
}
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/Config/Model/TableConfig.php | src/Config/Model/TableConfig.php | <?php
namespace App\Config\Model;
class TableConfig
{
private $columns = [];
private $subsetStrategy = null;
private $subsetOptions = [];
public function getColumns(): array
{
return $this->columns;
}
public function getColumn(string $name): ?ColumnConfig
{
return $this->columns[$name] ?? null;
}
public function addColumn(string $name, ColumnConfig $column)
{
$this->columns[$name] = $column;
}
public function getSubsetStrategy(): ?string
{
return $this->subsetStrategy;
}
public function getSubsetOptions(): array
{
return $this->subsetOptions;
}
public function setSubsetStrategy(string $name, array $options)
{
$this->subsetStrategy = $name;
$this->subsetOptions = $options;
}
}
| php | MIT | 733ebda8ad9bec0a903f8252da8e242525de24f6 | 2026-01-05T04:45:10.065464Z | false |
TheSoftwareHouse/fogger | https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Config/Model/Config.php | src/Config/Model/Config.php | <?php
namespace App\Config\Model;
class Config
{
private $tables = [];
private $excludes = [];
/**
* @return TableConfig[]
*/
public function getTables(): array
{
return $this->tables;
}
public function addTable(string $name, TableConfig $table)
{
$this->tables[$name] = $table;
}
public function getTable($name): ?TableConfig
{
return $this->tables[$name] ?? null;
}
public function setExcludes(array $excludes)
{
$this->excludes = $excludes;
}
public function getExcludes(): array
{
return $this->excludes;
}
}
| php | MIT | 733ebda8ad9bec0a903f8252da8e242525de24f6 | 2026-01-05T04:45:10.065464Z | false |
TheSoftwareHouse/fogger | https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Config/Serializer/TableConfigDenormalizer.php | src/Config/Serializer/TableConfigDenormalizer.php | <?php
namespace App\Config\Serializer;
use App\Config\Model\ColumnConfig;
use App\Config\Model\TableConfig;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
class TableConfigDenormalizer implements DenormalizerInterface
{
use DenormalizerAwareTrait;
public function supportsDenormalization($data, $type, $format = null)
{
return $type == TableConfig::class;
}
public function denormalize($data, $class, $format = null, array $context = array())
{
$table = new TableConfig();
foreach ($data['columns'] ?? [] as $key => $column) {
/** @var ColumnConfig $columnConfig */
$columnConfig = $this->denormalizer->denormalize($column, ColumnConfig::class, $format, $context);
$table->addColumn($key, $columnConfig);
}
if (isset($data['subsetStrategy'])) {
$table->setSubsetStrategy($data['subsetStrategy'], $data['subsetOptions'] ?? []);
}
return $table;
}
}
| php | MIT | 733ebda8ad9bec0a903f8252da8e242525de24f6 | 2026-01-05T04:45:10.065464Z | false |
TheSoftwareHouse/fogger | https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Config/Serializer/ConfigDenormalizer.php | src/Config/Serializer/ConfigDenormalizer.php | <?php
namespace App\Config\Serializer;
use App\Config\Model\Config;
use App\Config\Model\TableConfig;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
class ConfigDenormalizer implements DenormalizerInterface
{
use DenormalizerAwareTrait;
public function supportsDenormalization($data, $type, $format = null)
{
return $type == Config::class;
}
public function denormalize($data, $class, $format = null, array $context = array())
{
$config = new Config();
foreach ($data['tables'] ?? [] as $key => $table) {
/** @var TableConfig $tableConfig */
$tableConfig = $this->denormalizer->denormalize($table, TableConfig::class, $format, $context);
$config->addTable($key, $tableConfig);
}
$config->setExcludes($data['excludes'] ?? []);
return $config;
}
}
| php | MIT | 733ebda8ad9bec0a903f8252da8e242525de24f6 | 2026-01-05T04:45:10.065464Z | false |
TheSoftwareHouse/fogger | https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Schema/SchemaManipulator.php | src/Fogger/Schema/SchemaManipulator.php | <?php
namespace App\Fogger\Schema;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Schema as DBAL;
class SchemaManipulator
{
private $sourceSchema;
private $targetSchema;
public function __construct(Connection $source, Connection $target)
{
$this->sourceSchema = $source->getSchemaManager();
$this->targetSchema = $target->getSchemaManager();
}
/**
* @throws DBAL\SchemaException
*/
public function copySchemaDroppingIndexesAndForeignKeys()
{
$sourceTables = $this->sourceSchema->listTables();
/** @var DBAL\Table $table */
foreach ($sourceTables as $table) {
foreach ($table->getColumns() as $column) {
$column->setAutoincrement(false);
}
foreach ($table->getForeignKeys() as $fk) {
$table->removeForeignKey($fk->getName());
}
foreach ($table->getIndexes() as $index) {
$table->dropIndex($index->getName());
}
$this->targetSchema->createTable($table);
}
}
private function recreateIndexesOnTable(DBAL\Table $table)
{
foreach ($table->getIndexes() as $index) {
echo(sprintf(
" - %s's index %s on %s\n",
$table->getName(),
$index->getName(),
implode(', ', $index->getColumns())
));
$this->targetSchema->createIndex($index, $table->getName());
}
/** @var DBAL\Column $column */
foreach ($table->getColumns() as $column) {
if ($column->getAutoincrement()) {
$this->targetSchema->alterTable(
new DBAL\TableDiff($table->getName(), [], [new DBAL\ColumnDiff($column->getName(), $column)])
);
}
}
}
private function recreateForeignKeysOnTable(DBAL\Table $table)
{
foreach ($table->getForeignKeys() as $fk) {
echo(sprintf(
" - %s.%s => %s.%s\n",
$fk->getLocalTableName(),
implode('_', $fk->getLocalColumns()),
$fk->getForeignTableName(),
implode('_', $fk->getForeignColumns())
));
$this->targetSchema->createForeignKey($fk, $table->getName());
}
}
public function recreateIndexes()
{
$sourceTables = $this->sourceSchema->listTables();
foreach ($sourceTables as $table) {
$this->recreateIndexesOnTable($table);
}
}
public function recreateForeignKeys()
{
$sourceTables = $this->sourceSchema->listTables();
foreach ($sourceTables as $table) {
$this->recreateForeignKeysOnTable($table);
}
}
}
| php | MIT | 733ebda8ad9bec0a903f8252da8e242525de24f6 | 2026-01-05T04:45:10.065464Z | false |
TheSoftwareHouse/fogger | https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Schema/ForeignKeysExtractor.php | src/Fogger/Schema/ForeignKeysExtractor.php | <?php
namespace App\Fogger\Schema;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Schema as Schema;
class ForeignKeysExtractor
{
private $source;
public function __construct(Connection $source)
{
$this->source = $source->getSchemaManager();
}
public function findForeignKeysReferencingTable(string $tableName): array
{
$foreignKeys = [];
/** @var Schema\Table $table */
foreach ($this->source->listTables() as $table) {
/** @var Schema\ForeignKeyConstraint $foreignKeyConstraint */
foreach ($table->getForeignKeys() as $foreignKeyConstraint) {
if ($foreignKeyConstraint->getForeignTableName() === $tableName) {
$foreignKeys[] = $foreignKeyConstraint;
}
}
}
return $foreignKeys;
}
/**
* @param Schema\ForeignKeyConstraint $foreignKey
* @return bool
* @throws Schema\SchemaException
*/
public function isLocalColumnNullable(Schema\ForeignKeyConstraint $foreignKey): bool
{
$localColumn = $foreignKey->getLocalColumns()[0];
$localTable = $foreignKey->getLocalTableName();
$table = $this->source->listTableDetails($localTable);
$column = $table->getColumn($localColumn);
return !$column->getNotnull();
}
}
| php | MIT | 733ebda8ad9bec0a903f8252da8e242525de24f6 | 2026-01-05T04:45:10.065464Z | false |
TheSoftwareHouse/fogger | https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Schema/RelationGroupsFactory.php | src/Fogger/Schema/RelationGroupsFactory.php | <?php
namespace App\Fogger\Schema;
use App\Fogger\Schema\RelationGroups\RelationsGroups;
use Doctrine\DBAL\Connection;
class RelationGroupsFactory
{
private $sourceSchema;
public function __construct(Connection $connection)
{
$this->sourceSchema = $connection->getSchemaManager();
}
public function createFromDBAL()
{
$groups = new RelationsGroups();
foreach ($this->sourceSchema->listTables() as $table) {
foreach ($table->getForeignKeys() as $foreignKey) {
$groups->addForeignKey($foreignKey);
}
}
return $groups;
}
}
| php | MIT | 733ebda8ad9bec0a903f8252da8e242525de24f6 | 2026-01-05T04:45:10.065464Z | false |
TheSoftwareHouse/fogger | https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Schema/RelationGroups/RelationColumn.php | src/Fogger/Schema/RelationGroups/RelationColumn.php | <?php
namespace App\Fogger\Schema\RelationGroups;
class RelationColumn
{
const DESCRIPTOR_PATTERN = '%s.%s';
private $table;
private $columns;
public function __construct(string $table, array $columns)
{
$this->table = $table;
$this->columns = $columns;
}
public function getTable(): string
{
return $this->table;
}
public function getColumns(): array
{
return $this->columns;
}
public function getDescriptor()
{
return sprintf(
self::DESCRIPTOR_PATTERN,
$this->table,
implode('|', $this->columns)
);
}
}
| php | MIT | 733ebda8ad9bec0a903f8252da8e242525de24f6 | 2026-01-05T04:45:10.065464Z | false |
TheSoftwareHouse/fogger | https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Schema/RelationGroups/RelationsGroups.php | src/Fogger/Schema/RelationGroups/RelationsGroups.php | <?php
namespace App\Fogger\Schema\RelationGroups;
use Doctrine\DBAL\Schema\ForeignKeyConstraint;
class RelationsGroups
{
private $groups = [];
private function getGroupContainingColumn(RelationColumn $column)
{
/** @var GrouppedRelationColumns $group */
foreach ($this->groups as $group) {
if ($group->contains($column)) {
return $group;
}
}
return null;
}
private function newGroup()
{
$group = new GrouppedRelationColumns();
$this->groups[] = $group;
return $group;
}
public function addForeignKey(ForeignKeyConstraint $foreignKeyConstraint)
{
$local = new RelationColumn(
$foreignKeyConstraint->getLocalTableName(),
$foreignKeyConstraint->getLocalColumns()
);
$foreign = new RelationColumn(
$foreignKeyConstraint->getForeignTableName(),
$foreignKeyConstraint->getForeignColumns()
);
$g1 = $this->getGroupContainingColumn($local);
$g2 = $this->getGroupContainingColumn($foreign);
$group = $g1 ?? $g2 ?? $this->newGroup();
$group->addRelationColumn($local);
$group->addRelationColumn($foreign);
}
public function getGroupByTableAndColumn(string $table, string $column): ?GrouppedRelationColumns
{
foreach ($this->groups as $group) {
if ($group->containsByKey(
sprintf
(
RelationColumn::DESCRIPTOR_PATTERN,
$table,
$column
)
)) {
return $group;
}
}
return null;
}
}
| php | MIT | 733ebda8ad9bec0a903f8252da8e242525de24f6 | 2026-01-05T04:45:10.065464Z | false |
TheSoftwareHouse/fogger | https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Schema/RelationGroups/GrouppedRelationColumns.php | src/Fogger/Schema/RelationGroups/GrouppedRelationColumns.php | <?php
namespace App\Fogger\Schema\RelationGroups;
class GrouppedRelationColumns
{
private $columns = [];
public function addRelationColumn(RelationColumn $column)
{
if ($this->contains($column)) {
return;
}
$this->columns[$column->getDescriptor()] = $column;
}
public function contains(RelationColumn $column)
{
return $this->containsByKey($column->getDescriptor());
}
public function containsByKey(string $key)
{
return isset($this->columns[$key]);
}
/**
* @return RelationColumn[]
*/
public function getColumns(): array
{
return $this->columns;
}
}
| php | MIT | 733ebda8ad9bec0a903f8252da8e242525de24f6 | 2026-01-05T04:45:10.065464Z | false |
TheSoftwareHouse/fogger | https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Refine/Refiner.php | src/Fogger/Refine/Refiner.php | <?php
namespace App\Fogger\Refine;
use App\Fogger\Recipe\Recipe;
use App\Fogger\Recipe\Table;
use App\Fogger\Schema\ForeignKeysExtractor;
use App\Fogger\Subset\NoSubset;
use Doctrine\DBAL\Schema as Schema;
class Refiner
{
private $extractor;
private $refineExecutor;
public function __construct(
ForeignKeysExtractor $extractor,
RefineExecutor $refineExecutor
) {
$this->extractor = $extractor;
$this->refineExecutor = $refineExecutor;
}
/**
* @param Table $table
* @throws Schema\SchemaException
*/
private function refineIfSubsetted(Table $table): void
{
if ($table->getSubsetName() === NoSubset::STRATEGY_NAME) {
return;
}
$this->refineTable($table->getName());
}
/**
* @param Schema\ForeignKeyConstraint $foreignKey
* @throws Schema\SchemaException
*/
private function runQueryFor(Schema\ForeignKeyConstraint $foreignKey)
{
echo(sprintf(
" - %s.%s => %s.%s\n",
$foreignKey->getLocalTableName(),
implode('_', $foreignKey->getLocalColumns()),
$foreignKey->getForeignTableName(),
implode('_', $foreignKey->getForeignColumns())
));
if ($this->extractor->isLocalColumnNullable($foreignKey)) {
$this->refineExecutor->setNulls($foreignKey);
return;
}
if ($this->refineExecutor->delete($foreignKey)) {
$this->refineTable($foreignKey->getLocalTableName());
}
}
/**
* @param string $tabletableName
* @throws Schema\SchemaException
*/
private function refineTable(string $tabletableName)
{
echo(' - refining '.$tabletableName."\n");
/** @var Schema\ForeignKeyConstraint $foreignKey */
foreach ($this->extractor->findForeignKeysReferencingTable($tabletableName) as $foreignKey) {
$this->runQueryFor($foreignKey);
}
}
/**
* @param Recipe $recipe
* @throws Schema\SchemaException
*/
public function refine(Recipe $recipe)
{
/** @var Table $table */
foreach ($recipe->getTables() as $table) {
$this->refineIfSubsetted($table);
}
foreach ($recipe->getExcludes() as $excluded) {
$this->refineTable($excluded);
}
}
}
| php | MIT | 733ebda8ad9bec0a903f8252da8e242525de24f6 | 2026-01-05T04:45:10.065464Z | false |
TheSoftwareHouse/fogger | https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Refine/RefineExecutor.php | src/Fogger/Refine/RefineExecutor.php | <?php
namespace App\Fogger\Refine;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Schema as Schema;
class RefineExecutor
{
private $target;
public function __construct(Connection $target)
{
$this->target = $target;
}
private function innerSelectFromCopiedTable(Schema\ForeignKeyConstraint $foreignKey)
{
return $this->target->createQueryBuilder()
->select($this->target->quoteIdentifier('__tmp.'.$foreignKey->getForeignColumns()[0]))
->from(
'('.$this->target->createQueryBuilder()
->select($this->target->quoteIdentifier($foreignKey->getForeignColumns()[0]))
->from($this->target->quoteIdentifier($foreignKey->getForeignTableName()))
->getSql().')',
'__tmp'
)
->getSQL();
}
public function delete(Schema\ForeignKeyConstraint $foreignKey): int
{
return $this->target->createQueryBuilder()
->delete($this->target->quoteIdentifier($foreignKey->getLocalTableName()))
->where(
$this->target->createQueryBuilder()->expr()->notIn(
$this->target->quoteIdentifier($foreignKey->getLocalColumns()[0]),
$this->innerSelectFromCopiedTable($foreignKey)
)
)
->execute();
}
public function setNulls(Schema\ForeignKeyConstraint $foreignKey)
{
$this->target->createQueryBuilder()
->update($this->target->quoteIdentifier($foreignKey->getLocalTableName()))
->set($this->target->quoteIdentifier($foreignKey->getLocalColumns()[0]), ':val')
->where(
$this->target->createQueryBuilder()->expr()->notIn(
$this->target->quoteIdentifier($foreignKey->getLocalColumns()[0]),
$this->innerSelectFromCopiedTable($foreignKey)
)
)
->setParameter('val', null)
->execute();
}
}
| php | MIT | 733ebda8ad9bec0a903f8252da8e242525de24f6 | 2026-01-05T04:45:10.065464Z | false |
TheSoftwareHouse/fogger | https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Subset/AbstractSubset.php | src/Fogger/Subset/AbstractSubset.php | <?php
namespace App\Fogger\Subset;
use App\Fogger\Subset\Exception\RequiredOptionMissingException;
abstract class AbstractSubset implements SubsetStrategyInterface
{
abstract protected function getSubsetStrategyName(): string;
public function supports(string $name): bool
{
return $name === $this->getSubsetStrategyName();
}
/**
* @param array $options
* @param $option
* @throws RequiredOptionMissingException
*/
protected function ensureOptionIsSet(array $options, $option)
{
if (!isset($options[$option])) {
throw new RequiredOptionMissingException(
sprintf(
'Strategy %s requires option "%s" to be set',
$this->getSubsetStrategyName(),
$option
)
);
}
}
}
| php | MIT | 733ebda8ad9bec0a903f8252da8e242525de24f6 | 2026-01-05T04:45:10.065464Z | false |
TheSoftwareHouse/fogger | https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Subset/TailSubset.php | src/Fogger/Subset/TailSubset.php | <?php
namespace App\Fogger\Subset;
use App\Fogger\Recipe\Table;
use Doctrine\DBAL\Query\QueryBuilder;
class TailSubset extends AbstratctHeadOrTailSubset
{
/**
* @param QueryBuilder $queryBuilder
* @param Table $table
* @return QueryBuilder
* @throws Exception\RequiredOptionMissingException
* @throws Exception\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, true));
}
public function getSubsetStrategyName(): string
{
return 'tail';
}
}
| php | MIT | 733ebda8ad9bec0a903f8252da8e242525de24f6 | 2026-01-05T04:45:10.065464Z | false |
TheSoftwareHouse/fogger | https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Subset/SubsetStrategyProvider.php | src/Fogger/Subset/SubsetStrategyProvider.php | <?php
namespace App\Fogger\Subset;
use App\Fogger\Subset\Exception\UnknownSubsetStrategyException;
class SubsetStrategyProvider
{
private $subsetStrategies = [];
public function __construct(iterable $subsetStrategies)
{
foreach ($subsetStrategies as $subsetStrategy) {
$this->addSubsetStrategy($subsetStrategy);
}
}
private function addSubsetStrategy(SubsetStrategyInterface $subsetStrategy)
{
$this->subsetStrategies[] = $subsetStrategy;
}
/**
* @param string $name
* @return SubsetStrategyInterface
* @throws UnknownSubsetStrategyException
*/
public function getSubsetStrategy(?string $name = 'noSubset'): SubsetStrategyInterface
{
foreach ($this->subsetStrategies as $subsetStrategy) {
if ($subsetStrategy->supports($name)) {
return $subsetStrategy;
}
}
throw new UnknownSubsetStrategyException('Unknown subset strategy "'.$name.'".');
}
}
| php | MIT | 733ebda8ad9bec0a903f8252da8e242525de24f6 | 2026-01-05T04:45:10.065464Z | false |
TheSoftwareHouse/fogger | https://github.com/TheSoftwareHouse/fogger/blob/733ebda8ad9bec0a903f8252da8e242525de24f6/src/Fogger/Subset/SubsetStrategyInterface.php | src/Fogger/Subset/SubsetStrategyInterface.php | <?php
namespace App\Fogger\Subset;
use App\Fogger\Recipe\Table;
use Doctrine\DBAL\Query\QueryBuilder;
interface SubsetStrategyInterface
{
public function subsetQuery(QueryBuilder $queryBuilder, Table $table): QueryBuilder;
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/Subset/NoSubset.php | src/Fogger/Subset/NoSubset.php | <?php
namespace App\Fogger\Subset;
use App\Fogger\Recipe\Table;
use Doctrine\DBAL\Query\QueryBuilder;
class NoSubset extends AbstractSubset
{
const STRATEGY_NAME = 'noSubset';
public function subsetQuery(QueryBuilder $queryBuilder, Table $table): QueryBuilder
{
return $queryBuilder;
}
public function getSubsetStrategyName(): string
{
return self::STRATEGY_NAME;
}
}
| php | MIT | 733ebda8ad9bec0a903f8252da8e242525de24f6 | 2026-01-05T04:45:10.065464Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.