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 |
|---|---|---|---|---|---|---|---|---|
Bit-Wasp/bitcoin-lib-php | https://github.com/Bit-Wasp/bitcoin-lib-php/blob/d4e46fdd1edc29fae7b359d2bde952e37d143c45/examples/bip32_sign.php | examples/bip32_sign.php | <?php
use BitWasp\BitcoinLib\BIP32;
use BitWasp\BitcoinLib\BitcoinLib;
use BitWasp\BitcoinLib\RawTransaction;
require_once(__DIR__. '/../vendor/autoload.php');
// Fixed seed and derivation to test with
$seed = '41414141414141414141414141414141414141';
$def = "0'/0";
// Create master key from seed
$master = BIP32::master_key($seed);
echo "\nMaster key\n m : {$master[0]} \n";
// Create derived key from master key + derivation
$key = BIP32::build_key($master, $def);
// Display private extended key and the address that's derived from it.
echo "Generated key: note that all depth=1 keys are hardened. \n {$key[1]} : {$key[0]}\n";
echo " : ".BIP32::key_to_address($key[0])."\n";
// Convert the extended private key to the public key, and display the address that's derived from it.
$pub = BIP32::extended_private_to_public($key);
echo "Public key\n {$pub[1]} : {$pub[0]}\n";
echo " : ".BIP32::key_to_address($pub[0])."\n";
/////////////////////////////
// We're gonna spent the first txout from this tx:
// https://www.blocktrail.com/BTC/tx/4a2231e13182cdb64fa2f9aae38fca46549891e9dc15e8aaf484d82fc6e0a1d8
// Set up inputs here
$inputs = array(
array(
'txid' => '4a2231e13182cdb64fa2f9aae38fca46549891e9dc15e8aaf484d82fc6e0a1d8',
'vout' => 0
)
);
// Set up outputs here
$outputs = array('1KuE17Fbcdsn3Ns5T9Wzi1epurRnKC9qVr' => BitcoinLib::toSatoshi(0.0004));
////////////////////////////
// Parameters for signing.
// Create JSON inputs parameter
// - These can come from bitcoind, or just knowledge of the txid/vout/scriptPubKey,
// and redeemScript if needed.
$json_inputs = json_encode(
array(
array(
'txid' => '4a2231e13182cdb64fa2f9aae38fca46549891e9dc15e8aaf484d82fc6e0a1d8',
'vout' => 0,
// OP_DUP OP_HASH160 push14bytes PkHash OP_EQUALVERIFY OP_CHECKSIG
'scriptPubKey' => '76a914'.'bf012bde5bd12eb7f9a66de5697b241b65a9a3c9'.'88ac')
)
);
// build wallet from private key(s)
$wallet = array();
BIP32::bip32_keys_to_wallet($wallet, array($key), '00');
// Create raw transaction
$raw_transaction = RawTransaction::create($inputs, $outputs);
// Sign the transaction
$signed = RawTransaction::sign($wallet, $raw_transaction, $json_inputs);
print_r($signed); echo "\n";
// Decode and print the TX
// print_r(RawTransaction::decode($sign['hex']));
// To broadcast the transaction onto the network
// - grab the $signed['hex']
// - `bitcoind sendrawtransaction <singed HEX>`
// or use an API that supports sendraw
// This transaction was broadcasted and confirmed here:
// https://www.blocktrail.com/BTC/tx/e04c14270b2a9fcff548bc0bdd16b22ec6c2903ea6aaf9f7656b81f1c4c6153b
| php | Unlicense | d4e46fdd1edc29fae7b359d2bde952e37d143c45 | 2026-01-05T04:49:06.611442Z | false |
spatie/laravel-tinker-tools | https://github.com/spatie/laravel-tinker-tools/blob/3272afa5bdc30f2cac9e437450d9e182a648c046/src/ShortClassNames.php | src/ShortClassNames.php | <?php
namespace Spatie\TinkerTools;
use ReflectionClass;
class ShortClassNames
{
/** @var \Illuminate\Support\Collection */
public $classes;
public static function register(string $classMapPath = null)
{
$classMapPath = $classMapPath ?? base_path('vendor/composer/autoload_classmap.php');
(new static($classMapPath))->registerAutoloader();
}
public function __construct(string $classMapPath)
{
$classFiles = include $classMapPath;
$this->classes = collect($classFiles)
->map(function (string $path, string $fqcn) {
$name = last(explode('\\', $fqcn));
return compact('fqcn', 'name');
})
->filter()
->values();
}
public function registerAutoloader()
{
spl_autoload_register([$this, 'aliasClass']);
}
public function aliasClass($findClass)
{
$class = $this->classes->first(function ($class) use ($findClass) {
if ($class['name'] !== $findClass) {
return false;
}
return ! (new ReflectionClass($class['fqcn']))->isInterface();
});
if (! $class) {
return;
}
class_alias($class['fqcn'], $class['name']);
}
}
| php | MIT | 3272afa5bdc30f2cac9e437450d9e182a648c046 | 2026-01-05T04:49:16.595106Z | false |
spatie/laravel-tinker-tools | https://github.com/spatie/laravel-tinker-tools/blob/3272afa5bdc30f2cac9e437450d9e182a648c046/tests/ShortClassNamesTest.php | tests/ShortClassNamesTest.php | <?php
namespace Spatie\TinkerTools\Test;
use Error;
use PHPUnit\Framework\TestCase;
use Spatie\TinkerTools\ShortClassNames;
class ShortClassNamesTest extends TestCase
{
/** @test */
public function it_can_register_short_name_classes()
{
$foundClass = false;
try {
\NamespacedClass::getGreeting();
$foundClass = true;
} catch (Error $error) {
}
$this->assertFalse($foundClass);
ShortClassNames::register(__DIR__.'/../vendor/composer/autoload_classmap.php');
$this->assertEquals('Oh, hi Mark', \NamespacedClass::getGreeting());
}
}
| php | MIT | 3272afa5bdc30f2cac9e437450d9e182a648c046 | 2026-01-05T04:49:16.595106Z | false |
spatie/laravel-tinker-tools | https://github.com/spatie/laravel-tinker-tools/blob/3272afa5bdc30f2cac9e437450d9e182a648c046/tests/NamespacedClass.php | tests/NamespacedClass.php | <?php
namespace Spatie\TinkerTools\Test;
class NamespacedClass
{
public static function getGreeting(): string
{
return 'Oh, hi Mark';
}
}
| php | MIT | 3272afa5bdc30f2cac9e437450d9e182a648c046 | 2026-01-05T04:49:16.595106Z | false |
spatie/commonmark-highlighter | https://github.com/spatie/commonmark-highlighter/blob/cd96e93aa775d3fac4a3722054b7393f911f54ba/src/CodeBlockHighlighter.php | src/CodeBlockHighlighter.php | <?php
namespace Spatie\CommonMarkHighlighter;
use DomainException;
use Highlight\Highlighter;
use function HighlightUtilities\splitCodeIntoArray;
class CodeBlockHighlighter
{
/** @var \Highlight\Highlighter */
protected $highlighter;
public function __construct(array $autodetectLanguages = [])
{
$this->highlighter = new Highlighter();
$this->highlighter->setAutodetectLanguages($autodetectLanguages);
}
public function highlight(string $codeBlock, ?string $infoLine = null)
{
$codeBlockWithoutTags = strip_tags($codeBlock);
$contents = htmlspecialchars_decode($codeBlockWithoutTags);
$definition = $this->parseLangAndLines($infoLine);
$language = $definition['lang'];
try {
$result = $language
? $this->highlighter->highlight($language, $contents)
: $this->highlighter->highlightAuto($contents);
$code = $result->value;
if (count($definition['lines']) > 0) {
$loc = splitCodeIntoArray($code);
foreach ($loc as $i => $line) {
$loc[$i] = vsprintf('<span class="loc%s">%s</span>', [
isset($definition['lines'][$i + 1]) ? ' highlighted' : '',
$line,
]);
}
$code = implode("\n", $loc);
}
return vsprintf('<code class="%s hljs %s" data-lang="%s">%s</code>', [
'language-'.($language ? $language : $result->language),
$result->language,
$language ? $language : $result->language,
$code,
]);
} catch (DomainException $e) {
return $codeBlock;
}
}
private function parseLangAndLines(?string $language)
{
$parsed = [
'lang' => $language,
'lines' => [],
];
if ($language === null) {
return $parsed;
}
$bracePos = strpos($language, '{');
if ($bracePos === false) {
return $parsed;
}
$parsed['lang'] = substr($language, 0, $bracePos);
$lineDef = substr($language, $bracePos + 1, -1);
$lineNums = explode(',', $lineDef);
foreach ($lineNums as $lineNum) {
if (strpos($lineNum, '-') === false) {
$parsed['lines'][intval($lineNum)] = true;
continue;
}
$extremes = explode('-', $lineNum);
if (count($extremes) !== 2) {
continue;
}
$start = intval($extremes[0]);
$end = intval($extremes[1]);
for ($i = $start; $i <= $end; $i++) {
$parsed['lines'][$i] = true;
}
}
return $parsed;
}
}
| php | MIT | cd96e93aa775d3fac4a3722054b7393f911f54ba | 2026-01-05T04:49:26.291966Z | false |
spatie/commonmark-highlighter | https://github.com/spatie/commonmark-highlighter/blob/cd96e93aa775d3fac4a3722054b7393f911f54ba/src/FencedCodeRenderer.php | src/FencedCodeRenderer.php | <?php
namespace Spatie\CommonMarkHighlighter;
use League\CommonMark\Extension\CommonMark\Node\Block\FencedCode;
use League\CommonMark\Extension\CommonMark\Renderer\Block\FencedCodeRenderer as BaseFencedCodeRenderer;
use League\CommonMark\Node\Node;
use League\CommonMark\Renderer\ChildNodeRendererInterface;
use League\CommonMark\Renderer\NodeRendererInterface;
use League\CommonMark\Util\Xml;
class FencedCodeRenderer implements NodeRendererInterface
{
/** @var \Spatie\CommonMarkHighlighter\CodeBlockHighlighter */
protected $highlighter;
/** @var \League\CommonMark\Extension\CommonMark\Renderer\Block\FencedCodeRenderer */
protected $baseRenderer;
public function __construct(array $autodetectLanguages = [])
{
$this->highlighter = new CodeBlockHighlighter($autodetectLanguages);
$this->baseRenderer = new BaseFencedCodeRenderer();
}
public function render(Node $node, ChildNodeRendererInterface $childRenderer)
{
$element = $this->baseRenderer->render($node, $childRenderer);
$element->setContents(
$this->highlighter->highlight(
$element->getContents(),
$this->getSpecifiedLanguage($node)
)
);
return $element;
}
protected function getSpecifiedLanguage(FencedCode $block): ?string
{
$infoWords = $block->getInfoWords();
if (empty($infoWords) || empty($infoWords[0])) {
return null;
}
return Xml::escape($infoWords[0], true);
}
}
| php | MIT | cd96e93aa775d3fac4a3722054b7393f911f54ba | 2026-01-05T04:49:26.291966Z | false |
spatie/commonmark-highlighter | https://github.com/spatie/commonmark-highlighter/blob/cd96e93aa775d3fac4a3722054b7393f911f54ba/src/IndentedCodeRenderer.php | src/IndentedCodeRenderer.php | <?php
namespace Spatie\CommonMarkHighlighter;
use League\CommonMark\Extension\CommonMark\Renderer\Block\IndentedCodeRenderer as BaseIndentedCodeRenderer;
use League\CommonMark\Node\Node;
use League\CommonMark\Renderer\ChildNodeRendererInterface;
use League\CommonMark\Renderer\NodeRendererInterface;
class IndentedCodeRenderer implements NodeRendererInterface
{
/** @var \Spatie\CommonMarkHighlighter\CodeBlockHighlighter */
protected $highlighter;
/** @var \League\CommonMark\Extension\CommonMark\Renderer\Block\IndentedCodeRenderer */
protected $baseRenderer;
public function __construct(array $autodetectLanguages = [])
{
$this->highlighter = new CodeBlockHighlighter($autodetectLanguages);
$this->baseRenderer = new BaseIndentedCodeRenderer();
}
public function render(Node $node, ChildNodeRendererInterface $childRenderer)
{
$element = $this->baseRenderer->render($node, $childRenderer);
$element->setContents(
$this->highlighter->highlight($element->getContents())
);
return $element;
}
}
| php | MIT | cd96e93aa775d3fac4a3722054b7393f911f54ba | 2026-01-05T04:49:26.291966Z | false |
spatie/commonmark-highlighter | https://github.com/spatie/commonmark-highlighter/blob/cd96e93aa775d3fac4a3722054b7393f911f54ba/tests/IndentedCodeRendererTest.php | tests/IndentedCodeRendererTest.php | <?php
namespace Spatie\CommonMarkHighlighter\Tests;
use League\CommonMark\Environment\Environment;
use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension;
use League\CommonMark\Extension\CommonMark\Node\Block\IndentedCode;
use League\CommonMark\Parser\MarkdownParser;
use League\CommonMark\Renderer\HtmlRenderer;
use PHPUnit\Framework\TestCase;
use Spatie\CommonMarkHighlighter\IndentedCodeRenderer;
use Spatie\Snapshots\MatchesSnapshots;
class IndentedCodeRendererTest extends TestCase
{
use MatchesSnapshots;
/** @test */
public function it_highlights_code_blocks()
{
$markdown = <<<'MARKDOWN'
Which looks like this in use:
<generic-form
:showBackButton="true"
@back="goBack"
></generic-form>
Something feels wrong here.
MARKDOWN;
$environment = new Environment();
$environment->addExtension(new CommonMarkCoreExtension());
$environment->addRenderer(IndentedCode::class, new IndentedCodeRenderer(['html']));
$parser = new MarkdownParser($environment);
$htmlRenderer = new HtmlRenderer($environment);
$document = $parser->parse($markdown);
$html = $htmlRenderer->renderDocument($document);
$this->assertMatchesXmlSnapshot('<div>'.$html.'</div>');
}
}
| php | MIT | cd96e93aa775d3fac4a3722054b7393f911f54ba | 2026-01-05T04:49:26.291966Z | false |
spatie/commonmark-highlighter | https://github.com/spatie/commonmark-highlighter/blob/cd96e93aa775d3fac4a3722054b7393f911f54ba/tests/FencedCodeRendererTest.php | tests/FencedCodeRendererTest.php | <?php
namespace Spatie\CommonMarkHighlighter\Tests;
use League\CommonMark\Environment\Environment;
use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension;
use League\CommonMark\Extension\CommonMark\Node\Block\FencedCode;
use League\CommonMark\Parser\MarkdownParser;
use League\CommonMark\Renderer\HtmlRenderer;
use PHPUnit\Framework\TestCase;
use Spatie\CommonMarkHighlighter\FencedCodeRenderer;
use Spatie\Snapshots\MatchesSnapshots;
class FencedCodeRendererTest extends TestCase
{
use MatchesSnapshots;
/** @test */
public function it_highlights_code_blocks_with_a_specified_language()
{
$markdown = <<<'MARKDOWN'
Which looks like this in use:
```html
<generic-form
:showBackButton="true"
@back="goBack"
></generic-form>
```
Something feels wrong here.
MARKDOWN;
$environment = new Environment();
$environment->addExtension(new CommonMarkCoreExtension());
$environment->addRenderer(FencedCode::class, new FencedCodeRenderer(['html']));
$parser = new MarkdownParser($environment);
$htmlRenderer = new HtmlRenderer($environment);
$document = $parser->parse($markdown);
$html = $htmlRenderer->renderDocument($document);
$this->assertMatchesXmlSnapshot('<div>'.$html.'</div>');
}
/** @test */
public function it_highlights_code_blocks_with_a_specified_language_and_single_line()
{
$markdown = <<<'MARKDOWN'
Which looks like this in use:
```html{5}
<generic-form
:showBackButton="true"
@back="goBack"
>
<input type="text" name="send-to">
<input type="number" name="amount" />
</generic-form>
```
Something feels wrong here.
MARKDOWN;
$environment = new Environment();
$environment->addExtension(new CommonMarkCoreExtension());
$environment->addRenderer(FencedCode::class, new FencedCodeRenderer(['html']));
$parser = new MarkdownParser($environment);
$htmlRenderer = new HtmlRenderer($environment);
$document = $parser->parse($markdown);
$html = $htmlRenderer->renderDocument($document);
$this->assertMatchesXmlSnapshot('<div>'.$html.'</div>');
}
/** @test */
public function it_highlights_code_blocks_with_a_specified_language_and_line_range()
{
$markdown = <<<'MARKDOWN'
Which looks like this in use:
```html{2-3}
<generic-form
:showBackButton="true"
@back="goBack"
>
<input type="text" name="send-to">
<input type="number" name="amount" />
</generic-form>
```
Something feels wrong here.
MARKDOWN;
$environment = new Environment();
$environment->addExtension(new CommonMarkCoreExtension());
$environment->addRenderer(FencedCode::class, new FencedCodeRenderer(['html']));
$parser = new MarkdownParser($environment);
$htmlRenderer = new HtmlRenderer($environment);
$document = $parser->parse($markdown);
$html = $htmlRenderer->renderDocument($document);
$this->assertMatchesXmlSnapshot('<div>'.$html.'</div>');
}
/** @test */
public function it_highlights_code_blocks_with_a_specified_language_and_multiple_line_range()
{
$markdown = <<<'MARKDOWN'
Which looks like this in use:
```html{2-3,5-6}
<generic-form
:showBackButton="true"
@back="goBack"
>
<input type="text" name="send-to">
<input type="number" name="amount" />
</generic-form>
```
Something feels wrong here.
MARKDOWN;
$environment = new Environment();
$environment->addExtension(new CommonMarkCoreExtension());
$environment->addRenderer(FencedCode::class, new FencedCodeRenderer(['html']));
$parser = new MarkdownParser($environment);
$htmlRenderer = new HtmlRenderer($environment);
$document = $parser->parse($markdown);
$html = $htmlRenderer->renderDocument($document);
$this->assertMatchesXmlSnapshot('<div>'.$html.'</div>');
}
/** @test */
public function it_highlights_code_blocks_with_a_specified_language_and_multiple_separate_lines()
{
$markdown = <<<'MARKDOWN'
Which looks like this in use:
```html{1,7}
<generic-form
:showBackButton="true"
@back="goBack"
>
<input type="text" name="send-to">
<input type="number" name="amount" />
</generic-form>
```
Something feels wrong here.
MARKDOWN;
$environment = new Environment();
$environment->addExtension(new CommonMarkCoreExtension());
$environment->addRenderer(FencedCode::class, new FencedCodeRenderer(['html']));
$parser = new MarkdownParser($environment);
$htmlRenderer = new HtmlRenderer($environment);
$document = $parser->parse($markdown);
$html = $htmlRenderer->renderDocument($document);
$this->assertMatchesXmlSnapshot('<div>'.$html.'</div>');
}
/** @test */
public function it_highlights_code_blocks_with_a_specified_language_and_mix_ranges_specific_lines()
{
$markdown = <<<'MARKDOWN'
Which looks like this in use:
```html{1,2-3,5,7}
<generic-form
:showBackButton="true"
@back="goBack"
>
<input type="text" name="send-to">
<input type="number" name="amount" />
</generic-form>
```
Something feels wrong here.
MARKDOWN;
$environment = new Environment();
$environment->addExtension(new CommonMarkCoreExtension());
$environment->addRenderer(FencedCode::class, new FencedCodeRenderer(['html']));
$parser = new MarkdownParser($environment);
$htmlRenderer = new HtmlRenderer($environment);
$document = $parser->parse($markdown);
$html = $htmlRenderer->renderDocument($document);
$this->assertMatchesXmlSnapshot('<div>'.$html.'</div>');
}
/** @test */
public function it_highlights_code_blocks_with_a_specified_language_and_lines_out_of_order()
{
$markdown = <<<'MARKDOWN'
Which looks like this in use:
```html{7,1,3,2}
<generic-form
:showBackButton="true"
@back="goBack"
>
<input type="text" name="send-to">
<input type="number" name="amount" />
</generic-form>
```
Something feels wrong here.
MARKDOWN;
$environment = new Environment();
$environment->addExtension(new CommonMarkCoreExtension());
$environment->addRenderer(FencedCode::class, new FencedCodeRenderer(['html']));
$parser = new MarkdownParser($environment);
$htmlRenderer = new HtmlRenderer($environment);
$document = $parser->parse($markdown);
$html = $htmlRenderer->renderDocument($document);
$this->assertMatchesXmlSnapshot('<div>'.$html.'</div>');
}
/** @test */
public function it_highlights_code_blocks_with_a_specified_language_and_line_range_with_emojis()
{
$markdown = <<<'MARKDOWN'
Which looks like this in use:
```php{2}
// ✅ ...
$isUserPending = $user->isStatus("pending");
```
Something feels wrong here.
MARKDOWN;
$environment = new Environment();
$environment->addExtension(new CommonMarkCoreExtension());
$environment->addRenderer(FencedCode::class, new FencedCodeRenderer(['html']));
$parser = new MarkdownParser($environment);
$htmlRenderer = new HtmlRenderer($environment);
$document = $parser->parse($markdown);
$html = $htmlRenderer->renderDocument($document);
$this->assertMatchesXmlSnapshot('<div>'.$html.'</div>');
}
/** @test */
public function it_highlights_code_blocks_with_an_autodetected_language()
{
$markdown = <<<'MARKDOWN'
Which looks like this in use:
```
<generic-form
:showBackButton="true"
@back="goBack"
></generic-form>
```
Something feels wrong here.
MARKDOWN;
$environment = new Environment();
$environment->addExtension(new CommonMarkCoreExtension());
$environment->addRenderer(FencedCode::class, new FencedCodeRenderer(['html']));
$parser = new MarkdownParser($environment);
$htmlRenderer = new HtmlRenderer($environment);
$document = $parser->parse($markdown);
$html = $htmlRenderer->renderDocument($document);
$this->assertMatchesXmlSnapshot('<div>'.$html.'</div>');
}
}
| php | MIT | cd96e93aa775d3fac4a3722054b7393f911f54ba | 2026-01-05T04:49:26.291966Z | false |
voocx/laravel-referral | https://github.com/voocx/laravel-referral/blob/6c3a7244af09eadad1aeccddc97dfdea938161e1/src/ReferralServiceProvider.php | src/ReferralServiceProvider.php | <?php
/*
* This file is part of questocat/laravel-referral package.
*
* (c) questocat <zhengchaopu@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Questocat\Referral;
use Illuminate\Support\ServiceProvider;
class ReferralServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*/
public function boot()
{
$this->setupConfig();
$this->setupMigrations();
}
/**
* {@inheritdoc}
*/
public function register()
{
}
/**
* Setup the config.
*/
protected function setupConfig()
{
$source = realpath(__DIR__.'/../config/referral.php');
$this->publishes([
$source => config_path('referral.php'),
], 'config');
$this->mergeConfigFrom($source, 'referral');
}
/**
* Setup the migrations.
*/
protected function setupMigrations()
{
$timestamp = date('Y_m_d_His');
$migrationsSource = realpath(__DIR__.'/../database/migrations/add_referral_to_users_table.php');
$migrationsTarget = database_path("/migrations/{$timestamp}_add_referral_to_users_table.php");
$this->publishes([
$migrationsSource => $migrationsTarget,
], 'migrations');
}
}
| php | MIT | 6c3a7244af09eadad1aeccddc97dfdea938161e1 | 2026-01-05T04:49:35.339667Z | false |
voocx/laravel-referral | https://github.com/voocx/laravel-referral/blob/6c3a7244af09eadad1aeccddc97dfdea938161e1/src/Http/Middleware/CheckReferral.php | src/Http/Middleware/CheckReferral.php | <?php
/*
* This file is part of questocat/laravel-referral package.
*
* (c) questocat <zhengchaopu@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Questocat\Referral\Http\Middleware;
use Closure;
class CheckReferral
{
public function handle($request, Closure $next)
{
if ($request->hasCookie('referral')) {
return $next($request);
}
if (($ref = $request->query('ref')) && app(config('referral.user_model', 'App\User'))->referralExists($ref)) {
return redirect($request->fullUrl())->withCookie(cookie()->forever('referral', $ref));
}
return $next($request);
}
}
| php | MIT | 6c3a7244af09eadad1aeccddc97dfdea938161e1 | 2026-01-05T04:49:35.339667Z | false |
voocx/laravel-referral | https://github.com/voocx/laravel-referral/blob/6c3a7244af09eadad1aeccddc97dfdea938161e1/src/Traits/UserReferral.php | src/Traits/UserReferral.php | <?php
/*
* This file is part of questocat/laravel-referral package.
*
* (c) questocat <zhengchaopu@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Questocat\Referral\Traits;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Str;
trait UserReferral
{
public function getReferralLink()
{
return url('/').'/?ref='.$this->affiliate_id;
}
public static function scopeReferralExists(Builder $query, $referral)
{
return $query->whereAffiliateId($referral)->exists();
}
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
if ($referredBy = Cookie::get('referral')) {
$model->referred_by = $referredBy;
}
$model->affiliate_id = self::generateReferral();
});
}
protected static function generateReferral()
{
$length = config('referral.referral_length', 5);
do {
$referral = Str::random($length);
} while (static::referralExists($referral));
return $referral;
}
}
| php | MIT | 6c3a7244af09eadad1aeccddc97dfdea938161e1 | 2026-01-05T04:49:35.339667Z | false |
voocx/laravel-referral | https://github.com/voocx/laravel-referral/blob/6c3a7244af09eadad1aeccddc97dfdea938161e1/config/referral.php | config/referral.php | <?php
/*
* This file is part of questocat/laravel-referral package.
*
* (c) questocat <zhengchaopu@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
return [
/*
* Model class name of users.
*/
'user_model' => 'App\User',
/*
* The length of referral code.
*/
'referral_length' => 5,
];
| php | MIT | 6c3a7244af09eadad1aeccddc97dfdea938161e1 | 2026-01-05T04:49:35.339667Z | false |
voocx/laravel-referral | https://github.com/voocx/laravel-referral/blob/6c3a7244af09eadad1aeccddc97dfdea938161e1/database/migrations/add_referral_to_users_table.php | database/migrations/add_referral_to_users_table.php | <?php
/*
* This file is part of questocat/laravel-referral package.
*
* (c) questocat <zhengchaopu@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddReferralToUsersTable extends Migration
{
/**
* Run the migrations.
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('referred_by')->nullable()->index();
$table->string('affiliate_id')->unique();
});
}
/**
* Reverse the migrations.
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('referred_by');
$table->dropColumn('affiliate_id');
});
}
}
| php | MIT | 6c3a7244af09eadad1aeccddc97dfdea938161e1 | 2026-01-05T04:49:35.339667Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/rector.php | rector.php | <?php
declare(strict_types=1);
use Rector\Config\RectorConfig;
use Rector\Doctrine\Set\DoctrineSetList;
use Rector\Php80\Rector\Class_\ClassPropertyAssignToConstructorPromotionRector;
use Rector\PHPUnit\Set\PHPUnitSetList;
use Rector\Symfony\Set\SymfonySetList;
use Rector\TypeDeclaration\Rector\ClassMethod\AddVoidReturnTypeWhereNoReturnRector;
return RectorConfig::configure()
->withPaths([
__DIR__ . '/config',
__DIR__ . '/migrations',
__DIR__ . '/public',
__DIR__ . '/src',
__DIR__ . '/templates',
__DIR__ . '/tests',
])
->withRootFiles()
->withImportNames(importShortClasses: false)
->withTypeCoverageLevel(0)
->withDeadCodeLevel(0)
->withCodeQualityLevel(0)
->withRules([
AddVoidReturnTypeWhereNoReturnRector::class,
])
->withPhpSets()
->withSets([
DoctrineSetList::ANNOTATIONS_TO_ATTRIBUTES,
SymfonySetList::ANNOTATIONS_TO_ATTRIBUTES,
DoctrineSetList::GEDMO_ANNOTATIONS_TO_ATTRIBUTES,
// PHPUnitSetList::PHPUNIT_110,
])
->withAttributesSets(symfony: true, doctrine: true, gedmo: true, jms: true, sensiolabs: true)
->withComposerBased(twig: true, doctrine: true, phpunit: true, symfony: true)
->withConfiguredRule(ClassPropertyAssignToConstructorPromotionRector::class, [
'inline_public' => true,
])
->withSkip([
ClassPropertyAssignToConstructorPromotionRector::class => [
__DIR__ . '/src/Entity/*',
],
]);
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/.php-cs-fixer.dist.php | .php-cs-fixer.dist.php | <?php
use PhpCsFixer\Finder;
use PhpCsFixer\Config;
$finder = (new Finder())
->in(__DIR__)
->exclude(['vendor', 'var', 'web'])
;
return (new Config())
->setRiskyAllowed(true)
->setRules([
'@Symfony' => true,
'@Symfony:risky' => true,
'array_syntax' => ['syntax' => 'short'],
'combine_consecutive_unsets' => true,
'heredoc_to_nowdoc' => true,
'no_extra_blank_lines' => ['tokens' => ['break', 'continue', 'extra', 'return', 'throw', 'use', 'parenthesis_brace_block', 'square_brace_block', 'curly_brace_block']],
'no_unreachable_default_argument_value' => true,
'no_useless_else' => true,
'no_useless_return' => true,
'ordered_class_elements' => true,
'ordered_imports' => true,
'php_unit_strict' => true,
'phpdoc_order' => true,
// 'psr4' => true,
'strict_comparison' => true,
'strict_param' => true,
'concat_space' => ['spacing' => 'one'],
])
->setFinder($finder)
;
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Kernel.php | src/Kernel.php | <?php
namespace App;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
class Kernel extends BaseKernel
{
use MicroKernelTrait;
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Webfeeds/Webfeeds.php | src/Webfeeds/Webfeeds.php | <?php
namespace App\Webfeeds;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Webfeeds.
*
* @see http://webfeeds.org/rss/1.0
*/
class Webfeeds
{
/**
* @var string|null
*/
#[Assert\Url]
private $logo;
/**
* @var string|null
*/
#[Assert\Url]
private $icon;
/**
* @var string|null
*/
private $accentColor;
public function setLogo(?string $logo): self
{
$this->logo = $logo;
return $this;
}
public function getLogo(): ?string
{
return $this->logo;
}
public function setIcon(?string $icon): self
{
$this->icon = $icon;
return $this;
}
public function getIcon(): ?string
{
return $this->icon;
}
public function setAccentColor(?string $accentColor): self
{
$this->accentColor = $accentColor;
return $this;
}
public function getAccentColor(): ?string
{
return $this->accentColor;
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Webfeeds/WebfeedsWriter.php | src/Webfeeds/WebfeedsWriter.php | <?php
namespace App\Webfeeds;
use MarcW\RssWriter\RssWriter;
use MarcW\RssWriter\WriterRegistererInterface;
/**
* WebfeedsWriter.
*
* Mostly used (or handled) by Feedly.
*
* @see https://blog.feedly.com/10-ways-to-optimize-your-feed-for-feedly/
*/
class WebfeedsWriter implements WriterRegistererInterface
{
public function getRegisteredWriters(): array
{
return [
Webfeeds::class => $this->write(...),
];
}
public function getRegisteredNamespaces(): array
{
return [
'webfeeds' => 'http://webfeeds.org/rss/1.0',
];
}
public function write(RssWriter $rssWriter, Webfeeds $extension): void
{
$writer = $rssWriter->getXmlWriter();
if ($extension->getLogo()) {
$writer->writeElement('webfeeds:logo', $extension->getLogo());
}
if ($extension->getIcon()) {
$writer->writeElement('webfeeds:icon', $extension->getIcon());
}
if ($extension->getAccentColor()) {
$writer->writeElement('webfeeds:accentColor', $extension->getAccentColor());
}
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Entity/Version.php | src/Entity/Version.php | <?php
namespace App\Entity;
use App\Repository\VersionRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* Version
* Which is an alias of Release (because RELEASE is a reserved keywords).
*/
#[ORM\Entity(repositoryClass: VersionRepository::class)]
#[ORM\Table(name: 'version')]
#[ORM\Index(name: 'created_at_idx', columns: ['created_at'])]
#[ORM\Index(name: 'tag_name_name_created_at_prerelease_repo_id', columns: ['tag_name', 'name', 'created_at', 'prerelease', 'repo_id'])]
#[ORM\UniqueConstraint(name: 'repo_version_unique', columns: ['repo_id', 'tag_name'])]
class Version
{
/**
* @var int
*/
#[ORM\Column(name: 'id', type: 'integer')]
#[ORM\Id]
#[ORM\GeneratedValue(strategy: 'AUTO')]
private $id;
/**
* @var string
*/
#[ORM\Column(name: 'tag_name', type: 'string', length: 191)]
private $tagName;
/**
* @var string|null
*/
#[ORM\Column(name: 'name', type: 'string', length: 191, nullable: true)]
private $name;
/**
* @var bool
*/
#[ORM\Column(name: 'prerelease', type: 'boolean')]
private $prerelease;
/**
* @var \DateTime
*/
#[ORM\Column(name: 'created_at', type: 'datetime')]
private $createdAt;
/**
* @var string|null
*/
#[ORM\Column(name: 'body', type: 'text', nullable: true)]
private $body;
public function __construct(
#[ORM\ManyToOne(targetEntity: Repo::class, inversedBy: 'versions')]
#[ORM\JoinColumn(name: 'repo_id', referencedColumnName: 'id', nullable: false)]
private readonly Repo $repo,
) {
}
/**
* Get id.
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set tagName.
*
* @param string $tagName
*
* @return Version
*/
public function setTagName($tagName)
{
$this->tagName = $tagName;
return $this;
}
/**
* Get tagName.
*
* @return string
*/
public function getTagName()
{
return $this->tagName;
}
/**
* Set name.
*
* @param string $name
*
* @return Version
*/
public function setName($name)
{
// hard truncate name
if (mb_strlen($name) > 190) {
$name = mb_substr($name, 0, 190);
}
$this->name = $name;
return $this;
}
/**
* Get name.
*
* @return string
*/
public function getName()
{
return (string) $this->name;
}
/**
* Set prerelease.
*
* @param bool $prerelease
*
* @return Version
*/
public function setPrerelease($prerelease)
{
$this->prerelease = $prerelease;
return $this;
}
/**
* Get prerelease.
*
* @return bool
*/
public function getPrerelease()
{
return $this->prerelease;
}
/**
* Set createdAt.
*
* @param \DateTime $createdAt
*
* @return Version
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt.
*
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set body.
*
* @param string $body
*
* @return Version
*/
public function setBody($body)
{
$this->body = $body;
return $this;
}
/**
* Get body.
*
* @return string
*/
public function getBody()
{
return (string) $this->body;
}
public function hydrateFromGithub(array $data): void
{
$this->setTagName($data['tag_name']);
$this->setName($data['name']);
$this->setPrerelease($data['prerelease']);
$this->setCreatedAt((new \DateTime())->setTimestamp(strtotime((string) $data['published_at'])));
$this->setBody($data['message']);
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Entity/Star.php | src/Entity/Star.php | <?php
namespace App\Entity;
use App\Repository\StarRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* Repo.
*/
#[ORM\Entity(repositoryClass: StarRepository::class)]
#[ORM\Table(name: 'star')]
#[ORM\UniqueConstraint(name: 'user_repo_unique', columns: ['user_id', 'repo_id'])]
class Star
{
/**
* @var int
*/
#[ORM\Column(name: 'id', type: 'integer')]
#[ORM\Id]
#[ORM\GeneratedValue(strategy: 'AUTO')]
private $id;
/**
* @var \DateTime
*/
#[ORM\Column(name: 'created_at', type: 'datetime', nullable: false)]
private $createdAt;
public function __construct(#[ORM\ManyToOne(targetEntity: User::class, inversedBy: 'stars')]
#[ORM\JoinColumn(name: 'user_id', referencedColumnName: 'id', nullable: false)]
private readonly User $user, #[ORM\ManyToOne(targetEntity: Repo::class, inversedBy: 'stars')]
#[ORM\JoinColumn(name: 'repo_id', referencedColumnName: 'id', nullable: false)]
private readonly Repo $repo)
{
$this->createdAt = new \DateTime();
}
/**
* Get id.
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set createdAt.
*
* @param \DateTime $createdAt
*
* @return Star
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt.
*
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Entity/User.php | src/Entity/User.php | <?php
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use League\OAuth2\Client\Provider\GithubResourceOwner;
use Ramsey\Uuid\Uuid;
use Symfony\Component\Security\Core\User\EquatableInterface;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* User.
*/
#[ORM\Entity(repositoryClass: UserRepository::class)]
#[ORM\HasLifecycleCallbacks]
#[ORM\Table(name: 'user')]
#[ORM\UniqueConstraint(name: 'uuid', columns: ['uuid'])]
class User implements UserInterface, EquatableInterface
{
/**
* @var int
*/
#[ORM\Column(name: 'id', type: 'integer')]
#[ORM\Id]
#[ORM\GeneratedValue(strategy: 'NONE')]
private $id;
/**
* @var string
*/
#[ORM\Column(name: 'uuid', type: 'guid', length: 191, unique: true, nullable: false)]
private $uuid;
/**
* @var string
*/
#[ORM\Column(name: 'username', type: 'string', length: 191, unique: true, nullable: false)]
private $username;
/**
* @var string
*/
#[ORM\Column(name: 'avatar', type: 'string', length: 191)]
private $avatar;
/**
* @var string|null
*/
#[ORM\Column(name: 'name', type: 'string', length: 191, nullable: true)]
private $name;
/**
* @var string
*/
#[ORM\Column(name: 'access_token', type: 'string', length: 100, nullable: false)]
private $accessToken;
/**
* @var \DateTime
*/
#[ORM\Column(name: 'created_at', type: 'datetime', nullable: false)]
private $createdAt;
/**
* @var \DateTime
*/
#[ORM\Column(name: 'updated_at', type: 'datetime', nullable: false)]
private $updatedAt;
/**
* @var \DateTime|null
*/
#[ORM\Column(name: 'removed_at', type: 'datetime', nullable: true)]
private $removedAt;
/**
* @var ArrayCollection<int, Star>
*/
#[ORM\OneToMany(targetEntity: Star::class, mappedBy: 'user')]
private $stars;
public function __construct()
{
$this->uuid = Uuid::uuid4()->toString();
$this->stars = new ArrayCollection();
}
/**
* Set id.
*
* @param int $id
*
* @return User
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Get id.
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set username.
*
* @param string $username
*
* @return User
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username.
*
* @return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Get uuid.
*
* @return string
*/
public function getUuid()
{
return $this->uuid;
}
/**
* Set avatar.
*
* @param string $avatar
*
* @return User
*/
public function setAvatar($avatar)
{
$this->avatar = $avatar;
return $this;
}
/**
* Get avatar.
*
* @return string
*/
public function getAvatar()
{
return $this->avatar;
}
/**
* Set name.
*
* @param string $name
*
* @return User
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name.
*
* @return string
*/
public function getName()
{
return (string) $this->name;
}
/**
* Set createdAt.
*
* @param \DateTime $createdAt
*
* @return User
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt.
*
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set updatedAt.
*
* @param \DateTime $updatedAt
*
* @return User
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt.
*
* @return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
#[ORM\PrePersist]
#[ORM\PreUpdate]
public function timestamps(): void
{
if (null === $this->createdAt) {
$this->createdAt = new \DateTime();
}
$this->updatedAt = new \DateTime();
}
/**
* Hydrate a user with data from Github.
*/
public function hydrateFromGithub(GithubResourceOwner $data): void
{
$info = $data->toArray();
$this->setId($info['id']);
$this->setUsername($info['login']);
$this->setAvatar($info['avatar_url']);
$this->setName($info['name']);
}
public function getRoles(): array
{
return ['ROLE_USER'];
}
public function getPassword(): ?string
{
return '';
}
public function getSalt(): ?string
{
return null;
}
public function eraseCredentials(): void
{
}
/**
* Set accessToken.
*
* @param string $accessToken
*
* @return User
*/
public function setAccessToken($accessToken)
{
$this->accessToken = $accessToken;
return $this;
}
/**
* Get accessToken.
*
* @return string
*/
public function getAccessToken()
{
return $this->accessToken;
}
/**
* Set removedAt.
*
* @param \DateTime $removedAt
*
* @return User
*/
public function setRemovedAt($removedAt)
{
$this->removedAt = $removedAt;
return $this;
}
/**
* Get removedAt.
*
* @return \DateTime|null
*/
public function getRemovedAt()
{
return $this->removedAt;
}
/**
* Trying to determine if the user should be logged out because it has changed or not.
*
* @see https://stackoverflow.com/a/47676103/569101
* @see https://symfony.com/doc/4.4/reference/configuration/security.html#logout-on-user-change
*/
public function isEqualTo(UserInterface $user): bool
{
if ($user instanceof self) {
if ($this->accessToken !== $user->getAccessToken()) {
return false;
}
if ($this->uuid !== $user->getUuid()) {
return false;
}
}
if ($this->username !== $user->getUserIdentifier()) {
return false;
}
return true;
}
public function getUserIdentifier(): string
{
return $this->getUsername();
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Entity/Repo.php | src/Entity/Repo.php | <?php
namespace App\Entity;
use App\Repository\RepoRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Repo.
*/
#[ORM\Entity(repositoryClass: RepoRepository::class)]
#[ORM\HasLifecycleCallbacks]
#[ORM\Table(name: 'repo')]
class Repo
{
/**
* @var int
*/
#[ORM\Column(name: 'id', type: 'integer')]
#[ORM\Id]
#[ORM\GeneratedValue(strategy: 'NONE')]
private $id;
/**
* @var string
*/
#[ORM\Column(name: 'name', type: 'string', length: 191)]
private $name;
/**
* @var string
*/
#[ORM\Column(name: 'full_name', type: 'string', length: 191)]
private $fullName;
/**
* @var string|null
*/
#[ORM\Column(name: 'description', type: 'text', nullable: true)]
private $description;
/**
* @var string|null
*/
#[ORM\Column(name: 'homepage', type: 'string', nullable: true)]
private $homepage;
/**
* @var string|null
*/
#[ORM\Column(name: 'language', type: 'string', nullable: true)]
private $language;
/**
* @var string
*/
#[ORM\Column(name: 'owner_avatar', type: 'string', length: 191)]
private $ownerAvatar;
/**
* @var \DateTime
*/
#[ORM\Column(name: 'created_at', type: 'datetime', nullable: false)]
private $createdAt;
/**
* @var \DateTime
*/
#[ORM\Column(name: 'updated_at', type: 'datetime', nullable: false)]
private $updatedAt;
/**
* @var \DateTime|null
*/
#[ORM\Column(name: 'removed_at', type: 'datetime', nullable: true)]
private $removedAt;
/**
* @var ArrayCollection<int, Star>
*/
#[ORM\OneToMany(targetEntity: Star::class, mappedBy: 'repo')]
private $stars;
/**
* @var ArrayCollection<int, Version>
*/
#[ORM\OneToMany(targetEntity: Version::class, mappedBy: 'repo')]
private $versions;
public function __construct()
{
$this->stars = new ArrayCollection();
$this->versions = new ArrayCollection();
}
/**
* Set id.
*
* @param int $id
*
* @return Repo
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Get id.
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name.
*
* @param string $name
*
* @return Repo
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name.
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set fullName.
*
* @param string $fullName
*
* @return Repo
*/
public function setFullName($fullName)
{
$this->fullName = $fullName;
return $this;
}
/**
* Get fullName.
*
* @return string
*/
public function getFullName()
{
return $this->fullName;
}
/**
* Set description.
*
* @param string $description
*
* @return Repo
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description.
*
* @return string
*/
public function getDescription()
{
return (string) $this->description;
}
/**
* Set homepage.
*
* @param string $homepage
*
* @return Repo
*/
public function setHomepage($homepage)
{
$this->homepage = $homepage;
return $this;
}
/**
* Get homepage.
*
* @return string
*/
public function getHomepage()
{
return (string) $this->homepage;
}
/**
* Set language.
*
* @param string $language
*
* @return Repo
*/
public function setLanguage($language)
{
$this->language = $language;
return $this;
}
/**
* Get language.
*
* @return string
*/
public function getLanguage()
{
return (string) $this->language;
}
/**
* Set ownerAvatar.
*
* @param string $ownerAvatar
*
* @return Repo
*/
public function setOwnerAvatar($ownerAvatar)
{
$this->ownerAvatar = $ownerAvatar;
return $this;
}
/**
* Get ownerAvatar.
*
* @return string
*/
public function getOwnerAvatar()
{
return $this->ownerAvatar;
}
/**
* Set createdAt.
*
* @param \DateTime $createdAt
*
* @return Repo
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt.
*
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set updatedAt.
*
* @param \DateTime $updatedAt
*
* @return Repo
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt.
*
* @return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
#[ORM\PrePersist]
#[ORM\PreUpdate]
public function timestamps(): void
{
if (null === $this->createdAt) {
$this->createdAt = new \DateTime();
}
$this->updatedAt = new \DateTime();
}
public function hydrateFromGithub(array $data): void
{
$this->setId($data['id']);
$this->setName($data['name']);
$this->setHomepage($data['homepage']);
$this->setLanguage($data['language']);
$this->setFullName($data['full_name']);
$this->setDescription($data['description']);
$this->setOwnerAvatar($data['owner']['avatar_url']);
}
/**
* Set removedAt.
*
* @param \DateTime $removedAt
*
* @return Repo
*/
public function setRemovedAt($removedAt)
{
$this->removedAt = $removedAt;
return $this;
}
/**
* Get removedAt.
*
* @return \DateTime|null
*/
public function getRemovedAt()
{
return $this->removedAt;
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/MessageHandler/VersionsSyncHandler.php | src/MessageHandler/VersionsSyncHandler.php | <?php
namespace App\MessageHandler;
use App\Entity\Repo;
use App\Entity\Version;
use App\Github\RateLimitTrait;
use App\Message\VersionsSync;
use App\PubSubHubbub\Publisher;
use App\Repository\RepoRepository;
use App\Repository\VersionRepository;
use Doctrine\ORM\EntityManager;
use Doctrine\Persistence\ManagerRegistry;
use Github\Api\GitData;
use Github\Api\Markdown;
use Github\Client;
use Psr\Log\LoggerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
/**
* Consumer message to sync new version from a given repo.
*/
#[AsMessageHandler]
class VersionsSyncHandler
{
use RateLimitTrait;
/**
* Client parameter can be null when no available client were found by the Github Client Discovery.
*/
public function __construct(private ManagerRegistry $doctrine, private RepoRepository $repoRepository, private VersionRepository $versionRepository, private Publisher $pubsubhubbub, private ?Client $client, private LoggerInterface $logger)
{
}
public function __invoke(VersionsSync $message): bool
{
// in case no client with safe RateLimit were found
if (null === $this->client) {
$this->logger->error('No client provided');
return false;
}
$repoId = $message->getRepoId();
/** @var Repo|null */
$repo = $this->repoRepository->find($repoId);
if (null === $repo) {
$this->logger->error('Can not find repo', ['repo' => $repoId]);
return false;
}
$this->logger->info('Consume banditore.sync_versions message', ['repo' => $repo->getFullName()]);
$rateLimit = $this->getRateLimits($this->client, $this->logger);
$this->logger->info('[' . $rateLimit . '] Check <info>' . $repo->getFullName() . '</info> … ');
if (0 === $rateLimit || false === $rateLimit) {
$this->logger->warning('RateLimit reached, stopping.');
return false;
}
// this shouldn't be catched so the worker will die when an exception is thrown
$nbVersions = $this->doSyncVersions($repo);
// notify pubsubhubbub for that repo
if ($nbVersions > 0) {
$this->pubsubhubbub->pingHub([$repoId]);
}
$this->logger->notice('[' . $this->getRateLimits($this->client, $this->logger) . '] <comment>' . $nbVersions . '</comment> new versions for <info>' . $repo->getFullName() . '</info>');
return true;
}
/**
* Do the job to sync repo & star of a user.
*
* @param Repo $repo Repo to work on
*/
private function doSyncVersions(Repo $repo): ?int
{
$newVersion = 0;
/** @var EntityManager */
$em = $this->doctrine->getManager();
/** @var \Github\Api\Repo */
$githubRepoApi = $this->client->api('repo');
// in case of the manager is closed following a previous exception
if (!$em->isOpen()) {
/** @var EntityManager */
$em = $this->doctrine->resetManager();
}
[$username, $repoName] = explode('/', $repo->getFullName());
// this is a simple call to retrieve at least one tag from the selected repo
// using git/refs/tags when repo has no tag throws a 404 which can't be cached
// this query return an empty array when repo has no tag and it can be cached
try {
$tags = $githubRepoApi->tags($username, $repoName, ['per_page' => 1, 'page' => 1]);
} catch (\Exception $e) {
$this->logger->warning('(repo/tags) <error>' . $e->getMessage() . '</error>');
// repo not found OR access blocked? Ignore it in future loops
if (404 === $e->getCode() || 451 === $e->getCode()) {
$repo->setRemovedAt(new \DateTime());
$em->persist($repo);
}
return null;
}
if (empty($tags)) {
return $newVersion;
}
// use git/refs/tags because tags aren't order by date creation (so we retrieve ALL tags every time …)
try {
/** @var GitData */
$githubGitApi = $this->client->api('git');
$tags = $githubGitApi->tags()->all($username, $repoName);
} catch (\Exception $e) {
$this->logger->warning('(git/refs/tags) <error>' . $e->getMessage() . '</error>');
return null;
}
foreach ($tags as $tag) {
// it'll be like `refs/tags/2.2.1`
$tag['name'] = str_replace('refs/tags/', '', $tag['ref']);
$version = $this->versionRepository->findExistingOne($tag['name'], $repo->getId());
if (null !== $version) {
continue;
}
// check for scheduled version to be persisted later
// in rare case where the tag name is almost equal, like "v1.1.0" & "V1.1.0" in might avoid error
foreach ($em->getUnitOfWork()->getScheduledEntityInsertions() as $entity) {
if ($entity instanceof Version && strtolower($entity->getTagName()) === strtolower($tag['name'])) {
$this->logger->info($tag['name'] . ' skipped because it seems to be already scheduled');
continue 2;
}
}
// is there an associated release?
$newRelease = [
'tag_name' => $tag['name'],
];
try {
$newRelease = $githubRepoApi->releases()->tag($username, $repoName, $tag['name']);
// use same key as tag to store the content of the release
$newRelease['message'] = $newRelease['body'];
} catch (\Exception $e) { // it should be `Github\Exception\RuntimeException` but I can't reproduce this exception in test :-(
// when a tag isn't a release, it'll be catched here
switch ($tag['object']['type']) {
// https://api.github.com/repos/ampproject/amphtml/git/tags/694b8cc3983f52209029605300910507bec700b4
case 'tag':
$tagInfo = $githubGitApi->tags()->show($username, $repoName, $tag['object']['sha']);
$newRelease += [
'name' => $tag['name'],
'prerelease' => false,
'published_at' => $tagInfo['tagger']['date'],
'message' => $tagInfo['message'],
];
break;
// https://api.github.com/repos/ampproject/amphtml/git/commits/c0a5834b32ae4b45b4bacf677c391e0f9cca82fb
case 'commit':
$commitInfo = $githubGitApi->commits()->show($username, $repoName, $tag['object']['sha']);
$newRelease += [
'name' => $tag['name'],
'prerelease' => false,
'published_at' => $commitInfo['author']['date'],
'message' => $commitInfo['message'],
];
break;
case 'blob':
$blobInfo = $githubGitApi->blobs()->show($username, $repoName, $tag['object']['sha']);
$newRelease += [
'name' => $tag['name'],
'prerelease' => false,
// we can't retrieve a date for a blob tag, sadly.
'published_at' => date('c'),
'message' => '(blob, size ' . $blobInfo['size'] . ') ' . base64_decode((string) $blobInfo['content'], true),
];
break;
default:
$this->logger->error('<error>Tag object type not supported: ' . $tag['object']['type'] . ' (for: ' . $repo->getFullName() . ')</error>');
continue 2;
}
$newRelease['message'] = $this->removePgpSignature((string) $newRelease['message']);
}
// render markdown in plain html and use default markdown file if it fails
if (isset($newRelease['message']) && '' !== trim($newRelease['message'])) {
try {
/** @var Markdown */
$githubMarkdownApi = $this->client->api('markdown');
$newRelease['message'] = $githubMarkdownApi->render($newRelease['message'], 'gfm', $repo->getFullName());
} catch (\Exception $e) {
$this->logger->warning('<error>Failed to parse markdown: ' . $e->getMessage() . '</error>');
// it is usually a problem from the abuse detection mechanism, to avoid multiple call, we just skip to the next repo
return $newVersion;
}
}
$version = new Version($repo);
$version->hydrateFromGithub($newRelease);
$em->persist($version);
++$newVersion;
// for big repos, flush every 200 versions in case of hitting rate limit
if (0 === ($newVersion % 200)) {
$em->flush();
}
}
$em->flush();
return $newVersion;
}
/**
* Remove PGP signature from commit / tag.
*/
private function removePgpSignature(string $message): string
{
$pos = stripos($message, '-----BEGIN PGP SIGNATURE-----');
if ($pos) {
return trim(substr($message, 0, $pos));
}
return $message;
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/MessageHandler/StarredReposSyncHandler.php | src/MessageHandler/StarredReposSyncHandler.php | <?php
namespace App\MessageHandler;
use App\Entity\Repo;
use App\Entity\Star;
use App\Entity\User;
use App\Github\RateLimitTrait;
use App\Message\StarredReposSync;
use App\Repository\RepoRepository;
use App\Repository\StarRepository;
use App\Repository\UserRepository;
use Doctrine\ORM\EntityManager;
use Doctrine\Persistence\ManagerRegistry;
use Github\Client;
use Github\Exception\RuntimeException;
use Predis\ClientInterface as RedisClientInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
/**
* Consumer message to sync starred repos from user.
*
* It might come from:
* - when user logged in
* - when we periodically sync user starred repos
*/
#[AsMessageHandler]
class StarredReposSyncHandler
{
use RateLimitTrait;
public const DAYS_SINCE_LAST_UPDATE = 1;
/**
* Client parameter can be null when no available client were found by the Github Client Discovery.
*/
public function __construct(private ManagerRegistry $doctrine, private UserRepository $userRepository, private StarRepository $starRepository, private RepoRepository $repoRepository, private ?Client $client, private LoggerInterface $logger, private RedisClientInterface $redis)
{
}
public function __invoke(StarredReposSync $message): bool
{
// in case no client with safe RateLimit were found
if (null === $this->client) {
$this->logger->error('No client provided');
return false;
}
$userId = $message->getUserId();
/** @var User|null */
$user = $this->userRepository->find($userId);
if (null === $user) {
$this->logger->error('Can not find user', ['user' => $userId]);
return false;
}
// to be able to notify user about repos sync (will be remove after 1h to avoid infinite sync notification)
$this->redis->setex('banditore:user-sync:' . $user->getId(), 3600, time());
$this->logger->info('Consume banditore.sync_starred_repos message', ['user' => $user->getUsername()]);
$rateLimit = $this->getRateLimits($this->client, $this->logger);
$this->logger->info('[' . $rateLimit . '] Check <info>' . $user->getUsername() . '</info> … ');
if (0 === $rateLimit || false === $rateLimit) {
$this->logger->warning('RateLimit reached, stopping.');
return false;
}
// this shouldn't be catched so the worker will die when an exception is thrown
$nbRepos = $this->doSyncRepo($user);
$this->logger->notice('[' . $this->getRateLimits($this->client, $this->logger) . '] Synced repos: ' . $nbRepos, ['user' => $user->getUsername()]);
// sync is done, remove notification
$this->redis->del(['banditore:user-sync:' . $user->getId()]);
return true;
}
/**
* Do the job to sync repo & star of a user.
*
* @param User $user User to work on
*/
private function doSyncRepo(User $user): ?int
{
$newStars = [];
$page = 1;
$perPage = 100;
/** @var EntityManager */
$em = $this->doctrine->getManager();
/** @var \Github\Api\User */
$githubUserApi = $this->client->api('user');
// in case of the manager is closed following a previous exception
if (!$em->isOpen()) {
/** @var EntityManager */
$em = $this->doctrine->resetManager();
}
try {
$starredRepos = $githubUserApi->starred($user->getUsername(), $page, $perPage);
} catch (\Exception $e) {
$this->logger->warning('(starred) <error>' . $e->getMessage() . '</error>');
// user got removed from GitHub
if (404 === $e->getCode()) {
$user->setRemovedAt(new \DateTime());
$em->persist($user);
}
return null;
}
$currentStars = $this->starRepository->findAllByUser($user->getId());
do {
$this->logger->info(' sync ' . \count($starredRepos) . ' starred repos', [
'user' => $user->getUsername(),
'rate' => $this->getRateLimits($this->client, $this->logger),
]);
foreach ($starredRepos as $starredRepo) {
/** @var Repo|null */
$repo = $this->repoRepository->find($starredRepo['id']);
// if repo doesn't exist
// OR repo doesn't get updated since XX days
if (null === $repo || $repo->getUpdatedAt()->diff(new \DateTime())->days > self::DAYS_SINCE_LAST_UPDATE) {
if (null === $repo) {
$repo = new Repo();
}
$repo->hydrateFromGithub($starredRepo);
$em->persist($repo);
}
// store current repo id to compare it later when we'll sync removed star
// using `id` instead of `full_name` to be more accurated (full_name can change)
$newStars[] = $repo->getId();
if (false === \in_array($repo->getId(), $currentStars, true)) {
$star = new Star($user, $repo);
$em->persist($star);
}
}
$em->flush();
try {
$starredRepos = $githubUserApi->starred($user->getUsername(), ++$page, $perPage);
} catch (RuntimeException) {
// api limit is reached or whatever other error, we'll try next time
return null;
}
} while (!empty($starredRepos));
// now remove unstarred repos
$this->doCleanOldStar($user, $newStars);
return \count($newStars);
}
/**
* Clean old star.
* When user unstar a repo we also need to remove that association.
*
* @param array $newStars Current starred repos Id of the user
*/
private function doCleanOldStar(User $user, array $newStars): void
{
$currentStars = $this->starRepository->findAllByUser($user->getId());
$repoIdsToRemove = array_diff($currentStars, $newStars);
if (!empty($repoIdsToRemove)) {
$this->logger->info('Removed stars: ' . \count($repoIdsToRemove), ['user' => $user->getUsername()]);
$this->starRepository->removeFromUser($repoIdsToRemove, $user->getId());
}
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Controller/DefaultController.php | src/Controller/DefaultController.php | <?php
namespace App\Controller;
use App\Entity\User;
use App\Pagination\Exception\InvalidPageNumberException;
use App\Pagination\Paginator;
use App\Repository\RepoRepository;
use App\Repository\StarRepository;
use App\Repository\UserRepository;
use App\Repository\VersionRepository;
use App\Rss\Generator;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use MarcW\RssWriter\Bridge\Symfony\HttpFoundation\RssStreamedResponse;
use MarcW\RssWriter\RssWriter;
use Predis\Client as RedisClient;
use Symfony\Bridge\Doctrine\Attribute\MapEntity;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class DefaultController extends AbstractController
{
public function __construct(private readonly VersionRepository $repoVersion, private readonly int $diffInterval, private readonly RedisClient $redis, private readonly Security $security)
{
}
#[Route(path: '/', name: 'homepage')]
public function indexAction(): Response
{
if ($this->security->isGranted('IS_AUTHENTICATED_FULLY')) {
return $this->redirect($this->generateUrl('dashboard'));
}
return $this->render('default/index.html.twig');
}
#[Route(path: '/status', name: 'status')]
public function statusAction(): Response
{
$latest = $this->repoVersion->findLatest();
if (null === $latest) {
return $this->json([]);
}
$diff = (new \DateTime())->getTimestamp() - $latest['createdAt']->getTimestamp();
return $this->json([
'latest' => $latest['createdAt'],
'diff' => $diff,
'is_fresh' => $diff / 60 < $this->diffInterval,
]);
}
#[Route(path: '/dashboard', name: 'dashboard')]
public function dashboardAction(Request $request, Paginator $paginator): Response
{
if (!$this->security->isGranted('IS_AUTHENTICATED_FULLY')) {
return $this->redirect($this->generateUrl('homepage'));
}
/** @var User */
$user = $this->getUser();
$userId = $user->getId();
// Pass the item total
$paginator->setItemTotalCallback(fn () => $this->repoVersion->countForUser($userId));
// Pass the slice
$paginator->setSliceCallback(fn ($offset, $length) => $this->repoVersion->findForUser($userId, $offset, $length));
// Paginate using the current page number
try {
$pagination = $paginator->paginate((int) $request->query->get('page', '1'));
} catch (InvalidPageNumberException $e) {
throw $this->createNotFoundException($e->getMessage());
}
// Avoid displaying empty page when page is too high
if ($request->query->get('page') > $pagination->getTotalNumberOfPages()) {
return $this->redirect($this->generateUrl('dashboard'));
}
return $this->render('default/dashboard.html.twig', [
'pagination' => $pagination,
'sync_status' => $this->redis->get('banditore:user-sync:' . $userId),
]);
}
/**
* Empty callback action.
* The request will be handle by the GithubAuthenticator.
*/
#[Route(path: '/callback', name: 'github_callback')]
public function githubCallbackAction(): RedirectResponse
{
return $this->redirect($this->generateUrl('github_connect'));
}
/**
* Link to this controller to start the "connect" process.
*/
#[Route(path: '/connect', name: 'github_connect')]
public function connectAction(ClientRegistry $oauth): RedirectResponse
{
if ($this->security->isGranted('IS_AUTHENTICATED_FULLY')) {
return $this->redirect($this->generateUrl('dashboard'));
}
return $oauth
->getClient('github')
->redirect(['user:email'], []);
}
#[Route(path: '/{uuid}.atom', name: 'rss_user')]
public function rssAction(
#[MapEntity(expr: 'repository.findOneBy({"uuid": uuid})')]
User $user,
Generator $rssGenerator,
RssWriter $rssWriter,
): RssStreamedResponse {
$channel = $rssGenerator->generate(
$user,
$this->repoVersion->findForUser($user->getId()),
$this->generateUrl('rss_user', ['uuid' => $user->getUuid()], UrlGeneratorInterface::ABSOLUTE_URL)
);
return new RssStreamedResponse($channel, $rssWriter);
}
/**
* Display some global stats.
*/
#[Route(path: '/stats', name: 'stats')]
public function statsAction(RepoRepository $repoRepo, StarRepository $repoStar, UserRepository $repoUser): Response
{
$nbRepos = $repoRepo->countTotal();
$nbReleases = $this->repoVersion->countTotal();
$nbStars = $repoStar->countTotal();
$nbUsers = $repoUser->countTotal();
return $this->render('default/stats.html.twig', [
'counters' => [
'nbRepos' => $nbRepos,
'nbReleases' => $nbReleases,
'avgReleasePerRepo' => ($nbRepos > 0) ? round($nbReleases / $nbRepos, 2) : 0,
'avgStarPerUser' => ($nbUsers > 0) ? round($nbStars / $nbUsers, 2) : 0,
],
'mostReleases' => $repoRepo->mostVersionsPerRepo(),
'lastestReleases' => $this->repoVersion->findLastVersionForEachRepo(20),
]);
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Twig/RepoVersionExtension.php | src/Twig/RepoVersionExtension.php | <?php
namespace App\Twig;
use Twig\Attribute\AsTwigFilter;
/**
* Took a repo with version information to display a link to that version on Github.
*/
class RepoVersionExtension
{
#[AsTwigFilter('link_to_version')]
public function linkToVersion(array $repo): ?string
{
if (!isset($repo['fullName']) || !isset($repo['tagName'])) {
return null;
}
return 'https://github.com/' . $repo['fullName'] . '/releases/' . urlencode($repo['tagName']);
}
public function getName(): string
{
return 'repo_version_extension';
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Twig/PaginationExtension.php | src/Twig/PaginationExtension.php | <?php
namespace App\Twig;
use App\Pagination\Pagination;
use Twig\Environment;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
/**
* Class SimplePaginationExtension.
*
* @author Ashley Dawson <ashley@ashleydawson.co.uk>
*/
class PaginationExtension extends AbstractExtension
{
public function getFunctions(): array
{
return [
new TwigFunction(
'pagination_render',
$this->render(...),
[
'is_safe' => ['html'],
'needs_environment' => true,
]
),
];
}
/**
* Render the pagination.
*/
public function render(Environment $environment, Pagination $pagination, string $routeName, string $pageParameterName = 'page', array $queryParameters = []): string
{
return $environment->render('default/_pagination.html.twig', [
'pagination' => $pagination,
'routeName' => $routeName,
'pageParameterName' => $pageParameterName,
'queryParameters' => $queryParameters,
]);
}
public function getName(): string
{
return 'pagination_extension';
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/PubSubHubbub/Publisher.php | src/PubSubHubbub/Publisher.php | <?php
namespace App\PubSubHubbub;
use App\Repository\UserRepository;
use GuzzleHttp\Client;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
/**
* Publish feed to pubsubhubbub.appspot.com.
*/
class Publisher
{
/**
* Create a new publisher.
*
* @param string $hub A hub (url) to ping
* @param RouterInterface $router Symfony Router to generate the feed xml
* @param Client $client Guzzle client to send the request
* @param string $host Host of the project (used to generate route from a command)
* @param string $scheme Scheme of the project (used to generate route from a command)
*/
public function __construct(protected $hub, protected RouterInterface $router, protected Client $client, protected UserRepository $userRepository, $host, $scheme)
{
// allow generating url from command to use the correct host/scheme (instead of http://localhost)
// @see http://symfony.com/doc/current/console/request_context.html
$context = $this->router->getContext();
$context->setHost($host);
$context->setScheme($scheme);
}
/**
* Ping available hub when new items are cached.
*
* http://nathangrigg.net/2012/09/real-time-publishing/
*
* @param array $repoIds Id of repo from the database
*
* @return bool
*/
public function pingHub(array $repoIds)
{
if (empty($this->hub) || empty($repoIds)) {
return false;
}
$urls = $this->retrieveFeedUrls($repoIds);
// ping publisher
// https://github.com/pubsubhubbub/php-publisher/blob/master/library/Publisher.php
$params = 'hub.mode=publish';
foreach ($urls as $url) {
$params .= '&hub.url=' . $url;
}
$response = $this->client->post(
$this->hub,
[
'http_errors' => false,
'body' => $params,
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
'User-Agent' => 'Banditore/1.0',
],
]
);
// hub should response 204 if everything went fine
return !(204 !== $response->getStatusCode());
}
/**
* Retrieve user feed urls from a list of repository ids.
*
* @return array
*/
private function retrieveFeedUrls(array $repoIds)
{
$users = $this->userRepository->findByRepoIds($repoIds);
$urls = [];
foreach ($users as $user) {
$urls[] = $this->router->generate(
'rss_user',
['uuid' => $user['uuid']],
UrlGeneratorInterface::ABSOLUTE_URL
);
}
return $urls;
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Github/ClientDiscovery.php | src/Github/ClientDiscovery.php | <?php
namespace App\Github;
use App\Cache\CustomRedisCachePool;
use App\Repository\UserRepository;
use Github\AuthMethod;
use Github\Client as GithubClient;
use Predis\Client as RedisClient;
use Psr\Log\LoggerInterface;
/**
* This class aim to find the best authenticated method to avoid hitting the Github rate limit.
* We first try with the default application authentication.
* And if it fails, we'll try each user until we find one with enough rate limit.
* In fact, the more user in database, the bigger chance to never hit the rate limit.
*/
class ClientDiscovery
{
use RateLimitTrait;
public const THRESHOLD_RATE_REMAIN_APP = 200;
public const THRESHOLD_RATE_REMAIN_USER = 2000;
private $client;
public function __construct(private UserRepository $userRepository, private RedisClient $redis, private string $clientId, private string $clientSecret, private LoggerInterface $logger)
{
$this->client = new GithubClient();
}
/**
* Allow to override Github client.
* Only used in test.
*/
public function setGithubClient(GithubClient $client): void
{
$this->client = $client;
}
/**
* Find the best authentication to use:
* - check the rate limit of the application default client (which should be used in most case)
* - if the rate limit is too low for the application client, loop on all user to check their rate limit
* - if none client have enough rate limit, we'll have a problem to perform further request, stop every thing !
*
* @return GithubClient|null
*/
public function find()
{
// attache the cache in anycase
$this->client->addCache(
new CustomRedisCachePool($this->redis),
[
// the default config include "private" to avoid caching request with this header
// since we can use a user token, Github will return a "private" but we want to cache that request
// it's safe because we don't require critical user value
'respect_response_cache_directives' => ['no-cache', 'max-age', 'no-store'],
]
);
// try with the application default client
$this->client->authenticate($this->clientId, $this->clientSecret, AuthMethod::CLIENT_ID);
$remaining = $this->getRateLimits($this->client, $this->logger);
if ($remaining >= self::THRESHOLD_RATE_REMAIN_APP) {
$this->logger->notice('RateLimit ok (' . $remaining . ') with default application');
return $this->client;
}
// if it doesn't work, try with all user tokens
// when at least one is ok, use it!
$users = $this->userRepository->findAllTokens();
foreach ($users as $user) {
$this->client->authenticate($user['accessToken'], null, AuthMethod::ACCESS_TOKEN);
$remaining = $this->getRateLimits($this->client, $this->logger);
if ($remaining >= self::THRESHOLD_RATE_REMAIN_USER) {
$this->logger->notice('RateLimit ok (' . $remaining . ') with user: ' . $user['username']);
return $this->client;
}
}
$this->logger->warning('No way to authenticate a client with enough rate limit remaining :(');
return null;
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Github/RateLimitTrait.php | src/Github/RateLimitTrait.php | <?php
namespace App\Github;
use Github\Api\RateLimit;
use Github\Client;
use Http\Client\Exception\HttpException;
use Psr\Log\LoggerInterface;
trait RateLimitTrait
{
/**
* Retrieve rate limit for the given authenticated client.
* It's in a separate method to be able to catch error in case of glimpse on the Github side.
*
* @return false|int
*/
private function getRateLimits(Client $client, LoggerInterface $logger)
{
try {
/** @var RateLimit */
$rateLimit = $client->api('rate_limit');
$rateLimitResource = $rateLimit->getResource('core');
if (false === $rateLimitResource) {
throw new \Exception('Unable to retrieve "core" resource from RateLimitTrait');
}
return $rateLimitResource->getRemaining();
} catch (HttpException $e) {
$logger->error('RateLimit call goes bad.', ['exception' => $e]);
return false;
} catch (\Exception $e) {
$logger->error('RateLimit call goes REALLY bad.', ['exception' => $e]);
return false;
}
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Message/StarredReposSync.php | src/Message/StarredReposSync.php | <?php
namespace App\Message;
class StarredReposSync
{
public function __construct(private readonly int $userId)
{
}
public function getUserId(): int
{
return $this->userId;
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Message/VersionsSync.php | src/Message/VersionsSync.php | <?php
namespace App\Message;
class VersionsSync
{
public function __construct(private readonly int $repoId)
{
}
public function getRepoId(): int
{
return $this->repoId;
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Cache/HierarchicalCachePoolTrait.php | src/Cache/HierarchicalCachePoolTrait.php | <?php
/*
* This file is part of php-cache organization.
*
* (c) 2015 Aaron Scherer <aequasi@gmail.com>, Tobias Nyholm <tobias.nyholm@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace App\Cache;
use Cache\Adapter\Common\AbstractCachePool;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
trait HierarchicalCachePoolTrait
{
/**
* A temporary cache for keys.
*
* @var array
*/
private $keyCache = [];
/**
* Get a value from the storage.
*
* @param string $name
*/
abstract public function getDirectValue($name);
/**
* Get a key to use with the hierarchy. If the key does not start with HierarchicalPoolInterface::SEPARATOR
* this will return an unalterered key. This function supports a tagged key. Ie "foo:bar".
*
* @param string $key The original key
* @param string &$pathKey A cache key for the path. If this key is changed everything beyond that path is changed.
*
* @return string|array
*/
protected function getHierarchyKey($key, &$pathKey = null)
{
if (!$this->isHierarchyKey($key)) {
return $key;
}
$key = $this->explodeKey($key);
$keyString = '';
// The comments below is for a $key = ["foo!tagHash", "bar!tagHash"]
foreach ($key as $name) {
// 1) $keyString = "foo!tagHash"
// 2) $keyString = "foo!tagHash![foo_index]!bar!tagHash"
$keyString .= (string) $name;
$pathKey = sha1('path' . AbstractCachePool::SEPARATOR_TAG . $keyString);
if (isset($this->keyCache[$pathKey])) {
$index = $this->keyCache[$pathKey];
} else {
$index = $this->getDirectValue($pathKey);
$this->keyCache[$pathKey] = $index;
}
// 1) $keyString = "foo!tagHash![foo_index]!"
// 2) $keyString = "foo!tagHash![foo_index]!bar!tagHash![bar_index]!"
$keyString .= AbstractCachePool::SEPARATOR_TAG . $index . AbstractCachePool::SEPARATOR_TAG;
}
// Assert: $pathKey = "path!foo!tagHash![foo_index]!bar!tagHash"
// Assert: $keyString = "foo!tagHash![foo_index]!bar!tagHash![bar_index]!"
// Make sure we do not get awfully long (>250 chars) keys
return sha1($keyString);
}
/**
* Clear the cache for the keys.
*/
protected function clearHierarchyKeyCache(): void
{
$this->keyCache = [];
}
/**
* A hierarchy key MUST begin with the separator.
*
* @param string $key
*
* @return bool
*/
private function isHierarchyKey($key)
{
return str_starts_with($key, '|');
}
/**
* This will take a hierarchy key ("|foo|bar") with tags ("|foo|bar!tagHash") and return an array with
* each level in the hierarchy appended with the tags. ["foo!tagHash", "bar!tagHash"].
*
* @param string $string
*
* @return array
*/
private function explodeKey($string)
{
[$key, $tag] = explode(AbstractCachePool::SEPARATOR_TAG, $string . AbstractCachePool::SEPARATOR_TAG);
if ('|' === $key) {
$parts = ['root'];
} else {
$parts = explode('|', $key);
// remove first element since it is always empty and replace it with 'root'
$parts[0] = 'root';
}
return array_map(fn ($level) => $level . AbstractCachePool::SEPARATOR_TAG . $tag, $parts);
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Cache/CustomRedisCachePool.php | src/Cache/CustomRedisCachePool.php | <?php
namespace App\Cache;
use Cache\Adapter\Common\PhpCacheItem;
/**
* Store lightweight response from GitHub to avoid having a huge Redis database.
* Stored response will only have what Bandito.re needs. We should use GraphQL to only request fields we want
* but rate limit is still too low for the app.
*
* Affected url from the GitHub API:
* - starred
* - git/refs/tags
* - tag
* - release
*
* All other response are usually for a version and we don't need to store them. They won't be cached.
*/
class CustomRedisCachePool extends PredisCachePool
{
protected function storeItemInCache(PhpCacheItem $item, $ttl): bool
{
if ($ttl < 0) {
return false;
}
$currentItem = $item->get();
if (404 === $currentItem['response']->getStatusCode() || 451 === $currentItem['response']->getStatusCode()) {
return parent::storeItemInCache($item, $ttl);
}
$body = json_decode((string) $currentItem['body'], true);
// we don't need to reduce empty array ^^
if (empty($body)) {
return parent::storeItemInCache($item, $ttl);
}
// do not cache version (ie: release or tag) information
// we don't query them later because the version will be saved and never updated
if (isset($body['committer']) || isset($body['tagger']) || isset($body['prerelease'])) {
return true;
}
if (isset($body[0]['ref']) && str_contains((string) $body[0]['ref'], 'refs/tags/')) {
// response for git/refs/tags
foreach ($body as $key => $element) {
$body[$key] = [
'ref' => $element['ref'],
'object' => [
'sha' => $element['object']['sha'],
'type' => $element['object']['type'],
],
];
}
} elseif (isset($body[0]['zipball_url'])) {
// response for only one tag
$body = [
0 => [
'name' => $body[0]['name'],
],
];
} elseif (isset($body[0]['full_name'])) {
// response for starred repos
foreach ($body as $key => $element) {
$body[$key] = [
'id' => $element['id'],
'name' => $element['name'],
'homepage' => $element['homepage'],
'language' => $element['language'],
'full_name' => $element['full_name'],
'description' => $element['description'],
'owner' => [
'avatar_url' => $element['owner']['avatar_url'],
],
];
}
} else {
$this->log('warning', 'Unmatched response from custom Redis cache', ['body' => $body]);
}
$currentItem['body'] = json_encode($body);
$item->set($currentItem);
return parent::storeItemInCache($item, $ttl);
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Cache/PredisCachePool.php | src/Cache/PredisCachePool.php | <?php
namespace App\Cache;
use Cache\Adapter\Common\AbstractCachePool;
use Cache\Adapter\Common\PhpCacheItem;
use Predis\ClientInterface as Client;
/**
* Kind of copy/pasted from `cache/predis-adapter` because the project looks dead.
*/
class PredisCachePool extends AbstractCachePool
{
use HierarchicalCachePoolTrait;
public function __construct(protected Client $cache)
{
}
protected function fetchObjectFromCache($key): array
{
$value = $this->cache->get($this->getHierarchyKey($key));
if (!$value) {
return [false, null, [], null];
}
$result = unserialize($value);
if (false === $result) {
return [false, null, [], null];
}
return $result;
}
protected function clearAllObjectsFromCache(): bool
{
return 'OK' === $this->cache->flushdb()->getPayload();
}
protected function clearOneObjectFromCache($key): bool
{
$path = null;
$keyString = $this->getHierarchyKey($key, $path);
if ($path) {
$this->cache->incr($path);
}
$this->clearHierarchyKeyCache();
return $this->cache->del($keyString) >= 0;
}
protected function storeItemInCache(PhpCacheItem $item, $ttl): bool
{
if ($ttl < 0) {
return false;
}
$key = $this->getHierarchyKey($item->getKey());
$data = serialize([true, $item->get(), $item->getTags(), $item->getExpirationTimestamp()]);
if (null === $ttl || 0 === $ttl) {
return 'OK' === $this->cache->set($key, $data)->getPayload();
}
return 'OK' === $this->cache->setex($key, $ttl, $data)->getPayload();
}
protected function getDirectValue($key): mixed
{
return $this->cache->get($key);
}
protected function appendListItem($name, $value): void
{
$this->cache->lpush($name, $value);
}
protected function getList($name): array
{
return $this->cache->lrange($name, 0, -1);
}
protected function removeList($name): bool
{
return $this->cache->del($name);
}
protected function removeListItem($name, $key): int
{
return $this->cache->lrem($name, 0, $key);
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Pagination/Pagination.php | src/Pagination/Pagination.php | <?php
namespace App\Pagination;
/**
* Class Pagination.
*
* @implements \IteratorAggregate<int, mixed>
*
* @author Ashley Dawson <ashley@ashleydawson.co.uk>
*/
class Pagination implements \IteratorAggregate, \Countable
{
private array $items = [];
private array $pages = [];
private int $totalNumberOfPages = 0;
private int $currentPageNumber = 0;
private int $firstPageNumber = 0;
private int $lastPageNumber = 0;
private int $previousPageNumber = 0;
private int $nextPageNumber = 0;
private int $itemsPerPage = 0;
private int $totalNumberOfItems = 0;
private int $firstPageNumberInRange = 0;
private int $lastPageNumberInRange = 0;
/**
* Get items.
*/
public function getItems(): array
{
return $this->items;
}
/**
* Set items.
*
* @return $this
*/
public function setItems(array $items)
{
$this->items = $items;
return $this;
}
/**
* Get currentPageNumber.
*
* @return int
*/
public function getCurrentPageNumber()
{
return $this->currentPageNumber;
}
/**
* Set currentPageNumber.
*
* @param int $currentPageNumber
*
* @return $this
*/
public function setCurrentPageNumber($currentPageNumber)
{
$this->currentPageNumber = $currentPageNumber;
return $this;
}
/**
* Get firstPageNumber.
*
* @return int
*/
public function getFirstPageNumber()
{
return $this->firstPageNumber;
}
/**
* Set firstPageNumber.
*
* @param int $firstPageNumber
*
* @return $this
*/
public function setFirstPageNumber($firstPageNumber)
{
$this->firstPageNumber = $firstPageNumber;
return $this;
}
/**
* Get firstPageNumberInRange.
*
* @return int
*/
public function getFirstPageNumberInRange()
{
return $this->firstPageNumberInRange;
}
/**
* Set firstPageNumberInRange.
*
* @param int $firstPageNumberInRange
*
* @return $this
*/
public function setFirstPageNumberInRange($firstPageNumberInRange)
{
$this->firstPageNumberInRange = $firstPageNumberInRange;
return $this;
}
/**
* Get itemsPerPage.
*
* @return int
*/
public function getItemsPerPage()
{
return $this->itemsPerPage;
}
/**
* Set itemsPerPage.
*
* @param int $itemsPerPage
*
* @return $this
*/
public function setItemsPerPage($itemsPerPage)
{
$this->itemsPerPage = $itemsPerPage;
return $this;
}
/**
* Get lastPageNumber.
*
* @return int
*/
public function getLastPageNumber()
{
return $this->lastPageNumber;
}
/**
* Set lastPageNumber.
*
* @param int $lastPageNumber
*
* @return $this
*/
public function setLastPageNumber($lastPageNumber)
{
$this->lastPageNumber = $lastPageNumber;
return $this;
}
/**
* Get lastPageNumberInRange.
*
* @return int
*/
public function getLastPageNumberInRange()
{
return $this->lastPageNumberInRange;
}
/**
* Set lastPageNumberInRange.
*
* @param int $lastPageNumberInRange
*
* @return $this
*/
public function setLastPageNumberInRange($lastPageNumberInRange)
{
$this->lastPageNumberInRange = $lastPageNumberInRange;
return $this;
}
/**
* Get nextPageNumber.
*
* @return int
*/
public function getNextPageNumber()
{
return $this->nextPageNumber;
}
/**
* Set nextPageNumber.
*
* @param int $nextPageNumber
*
* @return $this
*/
public function setNextPageNumber($nextPageNumber)
{
$this->nextPageNumber = $nextPageNumber;
return $this;
}
/**
* Get pages.
*
* @return array
*/
public function getPages()
{
return $this->pages;
}
/**
* Set pages.
*
* @return $this
*/
public function setPages(array $pages)
{
$this->pages = $pages;
return $this;
}
/**
* Get previousPageNumber.
*
* @return int
*/
public function getPreviousPageNumber()
{
return $this->previousPageNumber;
}
/**
* Set previousPageNumber.
*
* @param int $previousPageNumber
*
* @return $this
*/
public function setPreviousPageNumber($previousPageNumber)
{
$this->previousPageNumber = $previousPageNumber;
return $this;
}
/**
* Get totalNumberOfItems.
*
* @return int
*/
public function getTotalNumberOfItems()
{
return $this->totalNumberOfItems;
}
/**
* Set totalNumberOfItems.
*
* @param int $totalNumberOfItems
*
* @return $this
*/
public function setTotalNumberOfItems($totalNumberOfItems)
{
$this->totalNumberOfItems = $totalNumberOfItems;
return $this;
}
/**
* Get totalNumberOfPages.
*
* @return int
*/
public function getTotalNumberOfPages()
{
return $this->totalNumberOfPages;
}
/**
* Set totalNumberOfPages.
*
* @param int $totalNumberOfPages
*
* @return $this
*/
public function setTotalNumberOfPages($totalNumberOfPages)
{
$this->totalNumberOfPages = $totalNumberOfPages;
return $this;
}
public function getIterator(): \Traversable
{
return new \ArrayIterator($this->items);
}
public function count(): int
{
return \count($this->items);
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Pagination/Paginator.php | src/Pagination/Paginator.php | <?php
namespace App\Pagination;
use App\Pagination\Exception\CallbackNotFoundException;
use App\Pagination\Exception\InvalidPageNumberException;
/**
* Class Paginator.
*
* @author Ashley Dawson <ashley@ashleydawson.co.uk>
*/
class Paginator implements PaginatorInterface
{
/**
* @var \Closure
*/
private $itemTotalCallback;
/**
* @var \Closure
*/
private $sliceCallback;
/**
* @var \Closure
*/
private $beforeQueryCallback;
/**
* @var \Closure
*/
private $afterQueryCallback;
/**
* @var int
*/
private $itemsPerPage = 10;
/**
* @var int
*/
private $pagesInRange = 5;
/**
* Constructor - passing optional configuration.
*
* <code>
* $paginator = new Paginator(array(
* 'itemTotalCallback' => function () {
* // ...
* },
* 'sliceCallback' => function ($offset, $length) {
* // ...
* },
* 'itemsPerPage' => 10,
* 'pagesInRange' => 5
* ));
* </code>
*/
public function __construct(?array $config = null)
{
if (\array_key_exists('itemTotalCallback', $config)) {
$this->setItemTotalCallback($config['itemTotalCallback']);
}
if (\array_key_exists('sliceCallback', $config)) {
$this->setSliceCallback($config['sliceCallback']);
}
if (\array_key_exists('itemsPerPage', $config)) {
$this->setItemsPerPage($config['itemsPerPage']);
}
if (\array_key_exists('pagesInRange', $config)) {
$this->setPagesInRange($config['pagesInRange']);
}
}
public function paginate($currentPageNumber = 1)
{
if (!($this->itemTotalCallback instanceof \Closure)) {
throw new CallbackNotFoundException('Item total callback not found, set it using Paginator::setItemTotalCallback()');
}
if (!($this->sliceCallback instanceof \Closure)) {
throw new CallbackNotFoundException('Slice callback not found, set it using Paginator::setSliceCallback()');
}
if (!\is_int($currentPageNumber)) {
throw new \InvalidArgumentException(\sprintf('Current page number must be of type integer, %s given', \gettype($currentPageNumber)));
}
if ($currentPageNumber <= 0) {
throw new InvalidPageNumberException(\sprintf('Current page number must have a value of 1 or more, %s given', $currentPageNumber));
}
$beforeQueryCallback = $this->beforeQueryCallback instanceof \Closure
? $this->beforeQueryCallback
: function (): void {}
;
$afterQueryCallback = $this->afterQueryCallback instanceof \Closure
? $this->afterQueryCallback
: function (): void {}
;
$pagination = new Pagination();
$itemTotalCallback = $this->itemTotalCallback;
$beforeQueryCallback($this, $pagination);
$totalNumberOfItems = (int) $itemTotalCallback($pagination);
$afterQueryCallback($this, $pagination);
$numberOfPages = (int) ceil($totalNumberOfItems / $this->itemsPerPage);
$pagesInRange = $this->pagesInRange;
if ($pagesInRange > $numberOfPages) {
$pagesInRange = $numberOfPages;
}
$change = (int) ceil($pagesInRange / 2);
if (($currentPageNumber - $change) > ($numberOfPages - $pagesInRange)) {
$pages = range(($numberOfPages - $pagesInRange) + 1, $numberOfPages);
} else {
if (($currentPageNumber - $change) < 0) {
$change = $currentPageNumber;
}
$offset = $currentPageNumber - $change;
$pages = range($offset + 1, $offset + $pagesInRange);
}
$offset = ($currentPageNumber - 1) * $this->itemsPerPage;
$sliceCallback = $this->sliceCallback;
$beforeQueryCallback($this, $pagination);
if (-1 === $this->itemsPerPage) {
$items = $sliceCallback(0, 999999999, $pagination);
} else {
$items = $sliceCallback($offset, $this->itemsPerPage, $pagination);
}
if ($items instanceof \Iterator) {
$items = iterator_to_array($items);
}
$afterQueryCallback($this, $pagination);
$pagination
->setItems($items)
->setPages($pages)
->setTotalNumberOfPages($numberOfPages)
->setCurrentPageNumber($currentPageNumber)
->setFirstPageNumber(1)
->setLastPageNumber($numberOfPages)
->setItemsPerPage($this->itemsPerPage)
->setTotalNumberOfItems($totalNumberOfItems)
->setFirstPageNumberInRange(min($pages))
->setLastPageNumberInRange(max($pages))
;
$previousPageNumber = null;
if (($currentPageNumber - 1) > 0) {
$pagination->setPreviousPageNumber($currentPageNumber - 1);
}
$nextPageNumber = null;
if (($currentPageNumber + 1) <= $numberOfPages) {
$pagination->setNextPageNumber($currentPageNumber + 1);
}
return $pagination;
}
public function getSliceCallback()
{
return $this->sliceCallback;
}
public function setSliceCallback(\Closure $sliceCallback)
{
$this->sliceCallback = $sliceCallback;
return $this;
}
public function getItemTotalCallback()
{
return $this->itemTotalCallback;
}
public function getBeforeQueryCallback()
{
return $this->beforeQueryCallback;
}
public function setBeforeQueryCallback(\Closure $beforeQueryCallback)
{
$this->beforeQueryCallback = $beforeQueryCallback;
return $this;
}
public function getAfterQueryCallback()
{
return $this->afterQueryCallback;
}
public function setAfterQueryCallback(\Closure $afterQueryCallback)
{
$this->afterQueryCallback = $afterQueryCallback;
return $this;
}
public function setItemTotalCallback(\Closure $itemTotalCallback)
{
$this->itemTotalCallback = $itemTotalCallback;
return $this;
}
public function getItemsPerPage()
{
return $this->itemsPerPage;
}
public function setItemsPerPage($itemsPerPage)
{
if (!\is_int($itemsPerPage)) {
throw new \InvalidArgumentException(\sprintf('Items per page must be of type integer, %s given', \gettype($itemsPerPage)));
}
$this->itemsPerPage = $itemsPerPage;
return $this;
}
public function getPagesInRange()
{
return $this->pagesInRange;
}
public function setPagesInRange($pagesInRange)
{
if (!\is_int($pagesInRange)) {
throw new \InvalidArgumentException(\sprintf('Pages in range must be of type integer, %s given', \gettype($pagesInRange)));
}
$this->pagesInRange = $pagesInRange;
return $this;
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Pagination/PaginatorInterface.php | src/Pagination/PaginatorInterface.php | <?php
namespace App\Pagination;
/**
* Interface PaginatorInterface.
*
* @author Ashley Dawson <ashley@ashleydawson.co.uk>
*/
interface PaginatorInterface
{
/**
* Run paginate algorithm using the current page number.
*
* @param int $currentPageNumber Page number, usually passed from the current request
*
* @throws \InvalidArgumentException
* @throws InvalidPageNumberException
*
* @return Pagination Collection of items returned by the slice callback with pagination meta information
*/
public function paginate($currentPageNumber = 1);
/**
* Get sliceCallback.
*
* @return \Closure
*/
public function getSliceCallback();
/**
* Set sliceCallback.
*
* @return $this
*/
public function setSliceCallback(\Closure $sliceCallback);
/**
* Get itemTotalCallback.
*
* @return \Closure
*/
public function getItemTotalCallback();
/**
* Set itemTotalCallback.
*
* @return $this
*/
public function setItemTotalCallback(\Closure $itemTotalCallback);
/**
* @return \Closure
*/
public function getBeforeQueryCallback();
/**
* @return $this
*/
public function setBeforeQueryCallback(\Closure $beforeQueryCallback);
/**
* @return \Closure
*/
public function getAfterQueryCallback();
/**
* @return $this
*/
public function setAfterQueryCallback(\Closure $afterQueryCallback);
/**
* Get itemsPerPage.
*
* @return int
*/
public function getItemsPerPage();
/**
* Set itemsPerPage.
*
* @param int $itemsPerPage
*
* @throws \InvalidArgumentException
*
* @return $this
*/
public function setItemsPerPage($itemsPerPage);
/**
* Get pagesInRange.
*
* @return int
*/
public function getPagesInRange();
/**
* Set pagesInRange.
*
* @param int $pagesInRange
*
* @throws \InvalidArgumentException
*
* @return $this
*/
public function setPagesInRange($pagesInRange);
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Pagination/Exception/InvalidPageNumberException.php | src/Pagination/Exception/InvalidPageNumberException.php | <?php
namespace App\Pagination\Exception;
/**
* Class InvalidPageNumberException.
*
* @author Ashley Dawson <ashley@ashleydawson.co.uk>
*/
class InvalidPageNumberException extends \InvalidArgumentException
{
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Pagination/Exception/CallbackNotFoundException.php | src/Pagination/Exception/CallbackNotFoundException.php | <?php
namespace App\Pagination\Exception;
/**
* Class CallbackNotFoundException.
*
* @author Ashley Dawson <ashley@ashleydawson.co.uk>
*/
class CallbackNotFoundException extends \RuntimeException
{
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/DataFixtures/AppFixtures.php | src/DataFixtures/AppFixtures.php | <?php
namespace App\DataFixtures;
use App\Entity\Repo;
use App\Entity\Star;
use App\Entity\User;
use App\Entity\Version;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
class AppFixtures extends Fixture
{
public function load(ObjectManager $manager): void
{
$this->loadUsers($manager);
$this->loadRepos($manager);
$this->loadStars($manager);
$this->loadVersions($manager);
}
private function loadUsers(ObjectManager $manager): void
{
$user1 = new User();
$user1->setId(123);
$user1->setUsername('admin');
$user1->setName('Bob');
$user1->setAccessToken('1234567890');
$user1->setAvatar('http://0.0.0.0/avatar.jpg');
$manager->persist($user1);
$manager->flush();
$this->addReference('user1', $user1);
}
private function loadRepos(ObjectManager $manager): void
{
$repo1 = new Repo();
$repo1->hydrateFromGithub([
'id' => 666,
'name' => 'test',
'full_name' => 'test/test',
'description' => 'This is a test repo',
'homepage' => 'http://homepage.io',
'language' => 'Go',
'owner' => [
'avatar_url' => 'http://0.0.0.0/test.jpg',
],
]);
$manager->persist($repo1);
$repo2 = new Repo();
$repo2->hydrateFromGithub([
'id' => 555,
'name' => 'symfony',
'full_name' => 'symfony/symfony',
'description' => 'The Symfony PHP framework',
'homepage' => 'http://symfony.com',
'language' => 'PHP',
'owner' => [
'avatar_url' => 'https://avatars2.githubusercontent.com/u/143937?v=3',
],
]);
$manager->persist($repo2);
$repo3 = new Repo();
$repo3->hydrateFromGithub([
'id' => 444,
'name' => 'graby',
'full_name' => 'j0k3r/graby',
'description' => 'graby',
'homepage' => 'http://graby.io',
'language' => 'PHP',
'owner' => [
'avatar_url' => 'http://0.0.0.0/graby.jpg',
],
]);
$manager->persist($repo3);
$manager->flush();
$this->addReference('repo1', $repo1);
$this->addReference('repo2', $repo2);
$this->addReference('repo3', $repo3);
}
private function loadStars(ObjectManager $manager): void
{
/** @var User */
$user1 = $this->getReference('user1', User::class);
/** @var Repo */
$repo1 = $this->getReference('repo1', Repo::class);
/** @var Repo */
$repo2 = $this->getReference('repo2', Repo::class);
$star1 = new Star($user1, $repo1);
$star2 = new Star($user1, $repo2);
$manager->persist($star1);
$manager->persist($star2);
$manager->flush();
$this->addReference('star1', $star1);
$this->addReference('star2', $star2);
}
private function loadVersions(ObjectManager $manager): void
{
/** @var Repo */
$repo1 = $this->getReference('repo1', Repo::class);
/** @var Repo */
$repo2 = $this->getReference('repo2', Repo::class);
/** @var Repo */
$repo3 = $this->getReference('repo3', Repo::class);
$version1 = new Version($repo1);
$version1->hydrateFromGithub([
'tag_name' => '1.0.0',
'name' => 'First release',
'prerelease' => false,
'message' => 'YAY',
'published_at' => '2019-10-15T07:49:21Z',
]);
$manager->persist($version1);
$version2 = new Version($repo2);
$version2->hydrateFromGithub([
'tag_name' => '1.0.21',
'name' => 'First release',
'prerelease' => false,
'message' => 'YAY 555',
'published_at' => '2019-06-15T07:49:21Z',
]);
$manager->persist($version2);
$manager->flush();
$version3 = new Version($repo3);
$version3->hydrateFromGithub([
'tag_name' => '0.0.21',
'name' => 'Outdated release',
'prerelease' => false,
'message' => 'YAY OLD',
'published_at' => date('Y') . '-06-15T07:49:21Z',
]);
$manager->persist($version3);
$manager->flush();
$this->addReference('version1', $version1);
$this->addReference('version2', $version2);
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Rss/Generator.php | src/Rss/Generator.php | <?php
namespace App\Rss;
use App\Entity\User;
use App\Webfeeds\Webfeeds;
use MarcW\RssWriter\Extension\Atom\AtomLink;
use MarcW\RssWriter\Extension\Core\Channel;
use MarcW\RssWriter\Extension\Core\Guid;
use MarcW\RssWriter\Extension\Core\Item;
/**
* Generate the RSS for a user.
*/
class Generator
{
public const CHANNEL_TITLE = 'New releases from starred repo of %USERNAME%';
public const CHANNEL_DESCRIPTION = 'Here are all the new releases from all repos starred by %USERNAME%';
/**
* It will return the RSS for the given user with all the latests releases given.
*
* @param User $user User which require the RSS
* @param array $releases An array of releases information
* @param string $feedUrl The feed URL
*
* @return Channel Information to be dumped by `RssStreamedResponse` for example
*/
public function generate(User $user, array $releases, $feedUrl)
{
$channel = new Channel();
$channel->addExtension(
(new AtomLink())
->setRel('self')
->setHref($feedUrl)
->setType('application/rss+xml')
);
$channel->addExtension(
(new AtomLink())
->setRel('hub')
->setHref('http://pubsubhubbub.appspot.com/')
);
$channel->addExtension(
(new Webfeeds())
->setLogo($user->getAvatar())
->setIcon($user->getAvatar())
->setAccentColor('10556B')
);
$channel->setTitle(str_replace('%USERNAME%', $user->getUsername(), self::CHANNEL_TITLE))
->setLink($feedUrl)
->setDescription(str_replace('%USERNAME%', $user->getUsername(), self::CHANNEL_DESCRIPTION))
->setLanguage('en')
->setCopyright('(c) ' . (new \DateTime())->format('Y') . ' banditore')
->setLastBuildDate(isset($releases[0]) ? $releases[0]['createdAt'] : new \DateTime())
->setGenerator('banditore');
foreach ($releases as $release) {
// build repo top information
$repoHome = $release['homepage'] ? '(<a href="' . $release['homepage'] . '">' . $release['homepage'] . '</a>)' : '';
$repoLanguage = $release['language'] ? '<p>#' . $release['language'] . '</p>' : '';
$repoInformation = '<table>
<tr>
<td>
<a href="https://github.com/' . $release['fullName'] . '">
<img src="' . $release['ownerAvatar'] . '&s=140" alt="' . $release['fullName'] . '" title="' . $release['fullName'] . '" />
</a>
</td>
<td>
<b><a href="https://github.com/' . $release['fullName'] . '">' . $release['fullName'] . '</a></b>
' . $repoHome . '<br/>
' . $release['description'] . '<br/>
' . $repoLanguage . '
</td>
</tr>
</table>
<hr/>';
$item = new Item();
$item->setTitle($release['fullName'] . ' ' . $release['tagName'])
->setLink('https://github.com/' . $release['fullName'] . '/releases/' . urlencode((string) $release['tagName']))
->setDescription($repoInformation . $release['body'])
->setPubDate($release['createdAt'])
->setGuid((new Guid())->setIsPermaLink(true)->setGuid('https://github.com/' . $release['fullName'] . '/releases/' . urlencode((string) $release['tagName'])))
;
$channel->addItem($item);
}
return $channel;
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Repository/RepoRepository.php | src/Repository/RepoRepository.php | <?php
namespace App\Repository;
use App\Entity\Repo;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @method Repo|null findOneByFullName(string $fullName)
*
* @extends ServiceEntityRepository<Repo>
*/
class RepoRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Repo::class);
}
/**
* Retrieve all repositories to be fetched for new release.
*
* @return array
*/
public function findAllForRelease()
{
$data = $this->createQueryBuilder('r')
->select('r.id')
->where('r.removedAt IS NULL')
->getQuery()
->getArrayResult();
$return = [];
foreach ($data as $oneData) {
$return[] = $oneData['id'];
}
return $return;
}
/**
* Count total repos.
*
* @return int
*/
public function countTotal()
{
return (int) $this->createQueryBuilder('r')
->select('COUNT(r.id) as total')
->getQuery()
->getSingleScalarResult();
}
/**
* Retrieve repos with the most releases.
* Used for stats.
*
* @return array
*/
public function mostVersionsPerRepo()
{
return $this->createQueryBuilder('r')
->select('r.fullName', 'r.description', 'r.ownerAvatar')
->addSelect('(SELECT COUNT(v.id)
FROM App\Entity\Version v
WHERE v.repo = r.id) AS total'
)
->groupBy('r.fullName', 'r.description', 'r.ownerAvatar', 'total')
->orderBy('total', 'desc')
->setMaxResults(5)
->getQuery()
->getArrayResult();
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Repository/VersionRepository.php | src/Repository/VersionRepository.php | <?php
namespace App\Repository;
use App\Entity\Version;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\AbstractQuery;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<Version>
*/
class VersionRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Version::class);
}
/**
* Find one version for a given tag name and repo id.
* This is exactly the same as `findOneBy` but this one use a result cache.
* Version doesn't change after being inserted and since we check to many times for a version
* it's faster to store result in a cache.
*
* @param string $tagName Tag name to search, like v1.0.0
* @param int $repoId Repository ID
*
* @return int|null
*/
public function findExistingOne($tagName, $repoId)
{
$query = $this->createQueryBuilder('v')
->select('v.id')
->where('v.repo = :repoId')->setParameter('repoId', $repoId)
->andWhere('v.tagName = :tagName')->setParameter('tagName', $tagName)
->setMaxResults(1)
->getQuery()
;
return $query->getOneOrNullResult(AbstractQuery::HYDRATE_SINGLE_SCALAR);
}
/**
* Find all versions available for the given user.
*
* @param int $userId
* @param int $offset
* @param int $length
*
* @return array
*/
public function findForUser($userId, $offset = 0, $length = 20)
{
return $this->createQueryBuilder('v')
->select('v.tagName', 'v.name', 'v.createdAt', 'v.body', 'v.prerelease', 'r.fullName', 'r.ownerAvatar', 'r.ownerAvatar', 'r.homepage', 'r.language', 'r.description')
->leftJoin('v.repo', 'r')
->leftJoin('r.stars', 's')
->where('s.user = :userId')->setParameter('userId', $userId)
->orderBy('v.createdAt', 'desc')
->setFirstResult($offset)
->setMaxResults($length)
->getQuery()
->getArrayResult();
}
/**
* Count all versions available for the given user.
* Used in the dashboard pagination and auth process.
*
* @param int $userId
*
* @return int
*/
public function countForUser($userId)
{
return (int) $this->createQueryBuilder('v')
->select('COUNT(v.id)')
->leftJoin('v.repo', 'r')
->leftJoin('r.stars', 's')
->where('s.user = :userId')->setParameter('userId', $userId)
->getQuery()
->getSingleScalarResult();
}
/**
* Retrieve latest version of each repo.
*
* @param int $length Number of items
*
* @return array
*/
public function findLastVersionForEachRepo($length = 10)
{
$query = '
SELECT v1.tagName, v1.name, v1.createdAt, r.fullName, r.description, r.ownerAvatar, v1.prerelease
FROM App\Entity\Version v1
LEFT JOIN App\Entity\Version v2 WITH (v1.repo = v2.repo AND v1.createdAt < v2.createdAt)
LEFT JOIN App\Entity\Repo r WITH r.id = v1.repo
WHERE v2.repo IS NULL
ORDER BY v1.createdAt DESC
';
return $this->getEntityManager()->createQuery($query)
->setFirstResult(0)
->setMaxResults($length)
->getArrayResult();
}
/**
* Count total versions.
*
* @return int
*/
public function countTotal()
{
return (int) $this->createQueryBuilder('v')
->select('COUNT(v.id) as total')
->getQuery()
->getSingleScalarResult();
}
/**
* Retrieve the latest version saved.
*
* @return array|null
*/
public function findLatest()
{
return $this->createQueryBuilder('v')
->select('v.createdAt')
->orderBy('v.createdAt', 'desc')
->setMaxResults(1)
->getQuery()
->getOneOrNullResult();
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Repository/StarRepository.php | src/Repository/StarRepository.php | <?php
namespace App\Repository;
use App\Entity\Star;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<Star>
*/
class StarRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Star::class);
}
/**
* Retrieve all repos starred by a user.
*
* @param int $userId User id
*
* @return array
*/
public function findAllByUser($userId)
{
$repos = $this->createQueryBuilder('s')
->select('r.id')
->leftJoin('s.repo', 'r')
->where('s.user = ' . $userId)
->getQuery()
->getArrayResult();
$res = [];
foreach ($repos as $repo) {
$res[] = $repo['id'];
}
return $res;
}
/**
* Remove stars for a user.
*/
public function removeFromUser(array $repoIds, int $userId): void
{
$this->createQueryBuilder('s')
->delete()
->where('s.repo IN (:ids)')->setParameter('ids', $repoIds)
->andWhere('s.user = :userId')->setParameter('userId', $userId)
->getQuery()
->execute();
}
/**
* Count total stars.
*
* @return int
*/
public function countTotal()
{
return (int) $this->createQueryBuilder('s')
->select('COUNT(s.id) as total')
->getQuery()
->getSingleScalarResult();
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Repository/UserRepository.php | src/Repository/UserRepository.php | <?php
namespace App\Repository;
use App\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @method User|null findOneByUsername(string $username)
*
* @extends ServiceEntityRepository<User>
*/
class UserRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, User::class);
}
/**
* Retrieve user.
*
* @return array
*/
public function findByRepoIds(array $repoIds)
{
return $this->createQueryBuilder('u')
->select('DISTINCT u.uuid')
->leftJoin('u.stars', 's')
->where('s.repo IN (:ids)')->setParameter('ids', $repoIds)
->getQuery()
->getArrayResult();
}
/**
* Retrieve all users to be synced.
* We only retrieve ids to be as fast as possible.
*
* @return array
*/
public function findAllToSync()
{
$data = $this->createQueryBuilder('u')
->select('u.id')
->where('u.removedAt IS NULL')
->getQuery()
->getArrayResult();
$return = [];
foreach ($data as $oneData) {
$return[] = $oneData['id'];
}
return $return;
}
/**
* Retrieve all tokens available.
* This is used for the GithubClientDiscovery.
*
* @return array
*/
public function findAllTokens()
{
return $this->createQueryBuilder('u')
->select('u.id', 'u.username', 'u.accessToken')
->where('u.removedAt IS NULL')
->getQuery()
->enableResultCache()
->setResultCacheLifetime(10 * 60)
->getArrayResult();
}
/**
* Count total users.
*
* @return int
*/
public function countTotal()
{
return (int) $this->createQueryBuilder('u')
->select('COUNT(u.id) as total')
->getQuery()
->getSingleScalarResult();
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Security/GithubAuthenticator.php | src/Security/GithubAuthenticator.php | <?php
namespace App\Security;
use App\Entity\User;
use App\Entity\Version;
use App\Message\StarredReposSync;
use App\Repository\VersionRepository;
use Doctrine\ORM\EntityManagerInterface;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use KnpU\OAuth2ClientBundle\Security\Authenticator\OAuth2Authenticator;
use League\OAuth2\Client\Provider\GithubResourceOwner;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
class GithubAuthenticator extends OAuth2Authenticator
{
public function __construct(private readonly ClientRegistry $clientRegistry, private readonly EntityManagerInterface $entityManager, private readonly RouterInterface $router, private readonly MessageBusInterface $bus)
{
}
public function supports(Request $request): ?bool
{
// continue ONLY if the current ROUTE matches the check ROUTE
return 'github_callback' === $request->attributes->get('_route');
}
public function authenticate(Request $request): Passport
{
$client = $this->clientRegistry->getClient('github');
$accessToken = $this->fetchAccessToken($client);
return new SelfValidatingPassport(
new UserBadge($accessToken->getToken(), function () use ($accessToken, $client) {
/** @var GithubResourceOwner */
$githubUser = $client->fetchUserFromToken($accessToken);
/** @var User|null */
$user = $this->entityManager->getRepository(User::class)->find($githubUser->getId());
// always update user information at login
if (null === $user) {
$user = new User();
}
$user->setAccessToken($accessToken->getToken());
$user->hydrateFromGithub($githubUser);
$this->entityManager->persist($user);
$this->entityManager->flush();
return $user;
})
);
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
/** @var User */
$user = $token->getUser();
/** @var VersionRepository */
$versionRepo = $this->entityManager->getRepository(Version::class);
$versions = $versionRepo->countForUser($user->getId());
// if no versions were found, it means the user logged in for the first time
// and we need to display an explanation message
$message = 'Successfully logged in!';
if (0 === $versions) {
$message = 'Successfully logged in. Your starred repos will soon be synced!';
}
/** @var FlashBag */
$flash = $request->getSession()->getBag('flashes');
$flash->add('info', $message);
$this->bus->dispatch(new StarredReposSync($user->getId()));
return new RedirectResponse($this->router->generate('dashboard'));
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
$message = strtr($exception->getMessageKey(), $exception->getMessageData());
return new Response($message, Response::HTTP_FORBIDDEN);
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Command/SyncStarredReposCommand.php | src/Command/SyncStarredReposCommand.php | <?php
namespace App\Command;
use App\Message\StarredReposSync;
use App\MessageHandler\StarredReposSyncHandler;
use App\Repository\UserRepository;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Attribute\Option;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Messenger\Transport\Receiver\MessageCountAwareInterface;
use Symfony\Component\Messenger\Transport\TransportInterface;
/**
* This command sync starred repos from user(s).
*
* It can do it:
* - right away, might take longer to process
* - by publishing a message in a queue
*/
#[AsCommand(name: 'banditore:sync:starred-repos', description: 'Sync starred repos for all users')]
class SyncStarredReposCommand
{
public function __construct(private readonly UserRepository $userRepository, private readonly StarredReposSyncHandler $syncRepo, private readonly TransportInterface $transport, private readonly MessageBusInterface $bus)
{
}
public function __invoke(
OutputInterface $output,
#[Option(description: 'Retrieve only one user using its id')] string|bool $id = false,
#[Option(description: 'Retrieve only one user using its username')] string|bool $username = false,
#[Option(description: 'Push each user into a queue instead of fetching it right away')] bool $useQueue = false,
): int {
if ($useQueue && $this->transport instanceof MessageCountAwareInterface) {
// check that queue is empty before pushing new messages
$count = $this->transport->getMessageCount();
if (0 < $count) {
$output->writeln('Current queue as too much messages (<error>' . $count . '</error>), <comment>skipping</comment>.');
return Command::FAILURE;
}
}
$users = $this->retrieveUsers($id, $username);
if (\count(array_filter($users)) <= 0) {
$output->writeln('<error>No users found</error>');
return Command::FAILURE;
}
$userSynced = 0;
$totalUsers = \count($users);
foreach ($users as $userId) {
++$userSynced;
$output->writeln('[' . $userSynced . '/' . $totalUsers . '] Sync user <info>' . $userId . '</info> … ');
$message = new StarredReposSync($userId);
if ($useQueue) {
$this->bus->dispatch($message);
} else {
$this->syncRepo->__invoke($message);
}
}
$output->writeln('<info>User synced: ' . $userSynced . '</info>');
return Command::SUCCESS;
}
/**
* Retrieve users to work on.
*/
private function retrieveUsers(?string $id, ?string $username): array
{
if ($id) {
return [$id];
}
if ($username) {
$user = $this->userRepository->findOneByUsername((string) $username);
if ($user) {
return [$user->getId()];
}
return [];
}
return $this->userRepository->findAllToSync();
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/src/Command/SyncVersionsCommand.php | src/Command/SyncVersionsCommand.php | <?php
namespace App\Command;
use App\Message\VersionsSync;
use App\MessageHandler\VersionsSyncHandler;
use App\Repository\RepoRepository;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Attribute\Option;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Messenger\Transport\Receiver\MessageCountAwareInterface;
use Symfony\Component\Messenger\Transport\TransportInterface;
/**
* This command send contents to opt-in Messenger users.
* It can send one content or many.
*
* Options priority is build this way:
* - one content
* - many contents
*/
#[AsCommand(name: 'banditore:sync:versions', description: 'Sync new version for each repository')]
class SyncVersionsCommand
{
public function __construct(private readonly RepoRepository $repoRepository, private readonly VersionsSyncHandler $syncVersions, private readonly TransportInterface $transport, private readonly MessageBusInterface $bus)
{
}
public function __invoke(
OutputInterface $output,
#[Option(description: 'Retrieve version only for that repository (using its id)')] string|bool $repoId = false,
#[Option(description: 'Retrieve version only for that repository (using it full name: username/repo)')] string|bool $repoName = false,
#[Option(description: 'Push each repo into a queue instead of fetching it right away')] bool $useQueue = false,
): int {
if ($useQueue && $this->transport instanceof MessageCountAwareInterface) {
// check that queue is empty before pushing new messages
$count = $this->transport->getMessageCount();
if (0 < $count) {
$output->writeln('Current queue as too much messages (<error>' . $count . '</error>), <comment>skipping</comment>.');
return Command::FAILURE;
}
}
$repos = $this->retrieveRepos($repoId, $repoName);
if (\count(array_filter($repos)) <= 0) {
$output->writeln('<error>No repos found</error>');
return Command::FAILURE;
}
$repoChecked = 0;
$totalRepos = \count($repos);
foreach ($repos as $repoId) {
++$repoChecked;
$output->writeln('[' . $repoChecked . '/' . $totalRepos . '] Check <info>' . $repoId . '</info> … ');
$message = new VersionsSync($repoId);
if ($useQueue) {
$this->bus->dispatch($message);
} else {
$this->syncVersions->__invoke($message);
}
}
$output->writeln('<info>Repo checked: ' . $repoChecked . '</info>');
return Command::SUCCESS;
}
/**
* Retrieve repos to work on.
*/
private function retrieveRepos(?string $repoId, ?string $repoName): array
{
if ($repoId) {
return [$repoId];
}
if ($repoName) {
$repo = $this->repoRepository->findOneByFullName((string) $repoName);
if ($repo) {
return [$repo->getId()];
}
return [];
}
return $this->repoRepository->findAllForRelease();
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/tests/object-manager.php | tests/object-manager.php | <?php
use App\Kernel;
require dirname(__DIR__) . '/tests/bootstrap.php';
$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);
$kernel->boot();
return $kernel->getContainer()->get('doctrine')->getManager();
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/tests/console-application.php | tests/console-application.php | <?php
use App\Kernel;
use Symfony\Bundle\FrameworkBundle\Console\Application;
/**
* @see https://github.com/phpstan/phpstan-symfony#console-command-analysis
*/
require dirname(__DIR__) . '/tests/bootstrap.php';
$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);
return new Application($kernel);
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/tests/bootstrap.php | tests/bootstrap.php | <?php
use Symfony\Component\Dotenv\Dotenv;
require dirname(__DIR__) . '/vendor/autoload.php';
if (method_exists(Dotenv::class, 'bootEnv')) {
(new Dotenv())->bootEnv(dirname(__DIR__) . '/.env');
}
if ($_SERVER['APP_DEBUG']) {
umask(0000);
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/tests/Webfeeds/WebfeedsWriterTest.php | tests/Webfeeds/WebfeedsWriterTest.php | <?php
namespace App\Tests\Webfeeds;
use App\Webfeeds\Webfeeds;
use App\Webfeeds\WebfeedsWriter;
use MarcW\RssWriter\RssWriter;
use PHPUnit\Framework\TestCase;
class WebfeedsWriterTest extends TestCase
{
public function test(): void
{
$writer = new WebfeedsWriter();
$rssWriter = new RssWriter();
$webfeeds = new Webfeeds();
$webfeeds->setLogo('https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png')
->setIcon('https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png')
->setAccentColor('404040');
$writer->write($rssWriter, $webfeeds);
$expected = <<<'EOF'
<webfeeds:logo>https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png</webfeeds:logo><webfeeds:icon>https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png</webfeeds:icon><webfeeds:accentColor>404040</webfeeds:accentColor>
EOF
;
$this->assertSame(
$expected,
$rssWriter->getXmlWriter()->flush()
);
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/tests/Webfeeds/WebfeedsTest.php | tests/Webfeeds/WebfeedsTest.php | <?php
namespace App\Tests\Webfeeds;
use App\Webfeeds\Webfeeds;
use PHPUnit\Framework\TestCase;
class WebfeedsTest extends TestCase
{
public function test(): void
{
$webfeeds = new Webfeeds();
$webfeeds->setLogo('https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png')
->setIcon('https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png')
->setAccentColor('404040');
$this->assertSame('https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png', $webfeeds->getLogo());
$this->assertSame('https://upload.wikimedia.org/wikipedia/commons/a/ab/Logo_TV_2015.png', $webfeeds->getIcon());
$this->assertSame('404040', $webfeeds->getAccentColor());
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/tests/MessageHandler/StarredReposSyncHandlerTest.php | tests/MessageHandler/StarredReposSyncHandlerTest.php | <?php
namespace App\Tests\MessageHandler;
use App\Entity\Repo;
use App\Entity\User;
use App\Message\StarredReposSync;
use App\MessageHandler\StarredReposSyncHandler;
use App\Repository\RepoRepository;
use App\Repository\StarRepository;
use App\Repository\UserRepository;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Doctrine\ORM\EntityManager;
use Github\Client as GithubClient;
use Github\HttpClient\Builder;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use Http\Adapter\Guzzle7\Client as Guzzle7Client;
use Monolog\Handler\TestHandler;
use Monolog\Logger;
use Psr\Log\NullLogger;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class StarredReposSyncHandlerTest extends WebTestCase
{
public function testProcessNoUser(): void
{
$doctrine = $this->getMockBuilder(Registry::class)
->disableOriginalConstructor()
->getMock();
$userRepository = $this->getMockBuilder(UserRepository::class)
->disableOriginalConstructor()
->getMock();
$userRepository->expects($this->once())
->method('find')
->with(123)
->willReturn(null);
$starRepository = $this->getMockBuilder(StarRepository::class)
->disableOriginalConstructor()
->getMock();
$repoRepository = $this->getMockBuilder(RepoRepository::class)
->disableOriginalConstructor()
->getMock();
$githubClient = $this->getMockBuilder(GithubClient::class)
->disableOriginalConstructor()
->getMock();
$githubClient->expects($this->never())
->method('authenticate');
$redisClient = $this->getMockBuilder(\Predis\Client::class)
->disableOriginalConstructor()
->getMock();
// will use `setex` & `del` but will be called dynamically by `_call`
$redisClient->expects($this->never())
->method('__call');
$handler = new StarredReposSyncHandler(
$doctrine,
$userRepository,
$starRepository,
$repoRepository,
$githubClient,
new NullLogger(),
$redisClient
);
$handler->__invoke(new StarredReposSync(123));
}
public function testProcessSuccessfulMessage(): void
{
$em = $this->getMockBuilder(EntityManager::class)
->disableOriginalConstructor()
->getMock();
$em->expects($this->once())
->method('isOpen')
->willReturn(true);
$doctrine = $this->getMockBuilder(Registry::class)
->disableOriginalConstructor()
->getMock();
$doctrine->expects($this->once())
->method('getManager')
->willReturn($em);
$user = new User();
$user->setId(123);
$user->setUsername('bob');
$user->setName('Bobby');
$userRepository = $this->getMockBuilder(UserRepository::class)
->disableOriginalConstructor()
->getMock();
$userRepository->expects($this->once())
->method('find')
->with(123)
->willReturn($user);
$starRepository = $this->getMockBuilder(StarRepository::class)
->disableOriginalConstructor()
->getMock();
$starRepository->expects($this->exactly(2))
->method('findAllByUser')
->with(123)
->willReturn([666, 777]);
$starRepository->expects($this->once())
->method('removeFromUser')
->with([1 => 777], 123);
$repo = new Repo();
$repo->setId(666);
$repo->setFullName('j0k3r/banditore');
$repo->setUpdatedAt((new \DateTime())->setTimestamp(time() - 3600 * 72));
$repoRepository = $this->getMockBuilder(RepoRepository::class)
->disableOriginalConstructor()
->getMock();
$repoRepository->expects($this->once())
->method('find')
->with(666)
->willReturn($repo);
$responses = new MockHandler([
// /rate_limit
$this->getOKResponse(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => 10]]]),
// first /user/starred
$this->getOKResponse([[
'description' => 'banditore',
'homepage' => 'http://banditore.io',
'language' => 'PHP',
'name' => 'banditore',
'full_name' => 'j0k3r/banditore',
'id' => 666,
'owner' => [
'avatar_url' => 'http://avatar.api/banditore.jpg',
],
]]),
// /rate_limit
$this->getOKResponse(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => 10]]]),
// third /user/starred will return empty response which means, we reached the last page
$this->getOKResponse([]),
// /rate_limit
$this->getOKResponse(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => 10]]]),
]);
$githubClient = $this->getMockClient($responses);
$logger = new Logger('foo');
$logHandler = new TestHandler();
$logger->pushHandler($logHandler);
$redisClient = $this->getMockBuilder(\Predis\Client::class)
->disableOriginalConstructor()
->getMock();
// will use `setex` & `del` but will be called dynamically by `_call`
$redisClient->expects($this->exactly(2))
->method('__call');
$handler = new StarredReposSyncHandler(
$doctrine,
$userRepository,
$starRepository,
$repoRepository,
$githubClient,
$logger,
$redisClient
);
$handler->__invoke(new StarredReposSync(123));
$records = $logHandler->getRecords();
$this->assertSame('Consume banditore.sync_starred_repos message', $records[0]['message']);
$this->assertSame('[10] Check <info>bob</info> … ', $records[1]['message']);
$this->assertSame(' sync 1 starred repos', $records[2]['message']);
$this->assertSame('Removed stars: 1', $records[3]['message']);
$this->assertSame('[10] Synced repos: 1', $records[4]['message']);
}
public function testUserRemovedFromGitHub(): void
{
$em = $this->getMockBuilder(EntityManager::class)
->disableOriginalConstructor()
->getMock();
$em->expects($this->once())
->method('isOpen')
->willReturn(true);
$doctrine = $this->getMockBuilder(Registry::class)
->disableOriginalConstructor()
->getMock();
$doctrine->expects($this->once())
->method('getManager')
->willReturn($em);
$user = new User();
$user->setId(123);
$user->setUsername('bob');
$user->setName('Bobby');
$userRepository = $this->getMockBuilder(UserRepository::class)
->disableOriginalConstructor()
->getMock();
$userRepository->expects($this->once())
->method('find')
->with(123)
->willReturn($user);
$starRepository = $this->getMockBuilder(StarRepository::class)
->disableOriginalConstructor()
->getMock();
$starRepository->expects($this->never())
->method('findAllByUser');
$repoRepository = $this->getMockBuilder(RepoRepository::class)
->disableOriginalConstructor()
->getMock();
$repoRepository->expects($this->never())
->method('find');
$responses = new MockHandler([
// /rate_limit
$this->getOKResponse(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => 10]]]),
// first /user/starred
new Response(404, ['Content-Type' => 'application/json']),
]);
$githubClient = $this->getMockClient($responses);
$logger = new Logger('foo');
$logHandler = new TestHandler();
$logger->pushHandler($logHandler);
$redisClient = $this->getMockBuilder(\Predis\Client::class)
->disableOriginalConstructor()
->getMock();
// will use `setex` & `del` but will be called dynamically by `_call`
$redisClient->expects($this->exactly(2))
->method('__call');
$handler = new StarredReposSyncHandler(
$doctrine,
$userRepository,
$starRepository,
$repoRepository,
$githubClient,
$logger,
$redisClient
);
$handler->__invoke(new StarredReposSync(123));
$records = $logHandler->getRecords();
$this->assertSame('Consume banditore.sync_starred_repos message', $records[0]['message']);
$this->assertSame('[10] Check <info>bob</info> … ', $records[1]['message']);
$this->assertStringContainsString('(starred) <error>', $records[2]['message']);
$this->assertNotNull($user->getRemovedAt());
}
public function testProcessUnexpectedError(): void
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('booboo');
$em = $this->getMockBuilder(EntityManager::class)
->disableOriginalConstructor()
->getMock();
$em->expects($this->once())
->method('isOpen')
->willReturn(true);
$doctrine = $this->getMockBuilder(Registry::class)
->disableOriginalConstructor()
->getMock();
$doctrine->expects($this->once())
->method('getManager')
->willReturn($em);
$user = new User();
$user->setId(123);
$user->setUsername('bob');
$user->setName('Bobby');
$userRepository = $this->getMockBuilder(UserRepository::class)
->disableOriginalConstructor()
->getMock();
$userRepository->expects($this->once())
->method('find')
->with(123)
->willReturn($user);
$starRepository = $this->getMockBuilder(StarRepository::class)
->disableOriginalConstructor()
->getMock();
$starRepository->expects($this->once())
->method('findAllByUser')
->with(123)
->willReturn([666]);
$repoRepository = $this->getMockBuilder(RepoRepository::class)
->disableOriginalConstructor()
->getMock();
$repoRepository->expects($this->once())
->method('find')
->with(666)
->will($this->throwException(new \Exception('booboo')));
$responses = new MockHandler([
// /rate_limit
$this->getOKResponse(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => 10]]]),
// first /user/starred
$this->getOKResponse([[
'description' => 'banditore',
'homepage' => 'http://banditore.io',
'language' => 'PHP',
'name' => 'banditore',
'full_name' => 'j0k3r/banditore',
'id' => 666,
'owner' => [
'avatar_url' => 'http://avatar.api/banditore.jpg',
],
]]),
// /rate_limit
$this->getOKResponse(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => 10]]]),
// second /user/starred will return empty response which means, we reached the last page
$this->getOKResponse([]),
// /rate_limit
$this->getOKResponse(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => 10]]]),
]);
$githubClient = $this->getMockClient($responses);
$redisClient = $this->getMockBuilder(\Predis\Client::class)
->disableOriginalConstructor()
->getMock();
// will use `setex` & `del` but will be called dynamically by `_call`
$redisClient->expects($this->once())
->method('__call');
$handler = new StarredReposSyncHandler(
$doctrine,
$userRepository,
$starRepository,
$repoRepository,
$githubClient,
new NullLogger(),
$redisClient
);
$handler->__invoke(new StarredReposSync(123));
}
/**
* Everything will goes fine (like testProcessSuccessfulMessage) and we won't remove old stars (no change detected in starred repos).
*/
public function testProcessSuccessfulMessageNoStarToRemove(): void
{
$em = $this->getMockBuilder(EntityManager::class)
->disableOriginalConstructor()
->getMock();
$em->expects($this->once())
->method('isOpen')
->willReturn(false); // simulate a closing manager
$doctrine = $this->getMockBuilder(Registry::class)
->disableOriginalConstructor()
->getMock();
$doctrine->expects($this->once())
->method('getManager')
->willReturn($em);
$doctrine->expects($this->once())
->method('resetManager')
->willReturn($em);
$user = new User();
$user->setId(123);
$user->setUsername('bob');
$user->setName('Bobby');
$userRepository = $this->getMockBuilder(UserRepository::class)
->disableOriginalConstructor()
->getMock();
$userRepository->expects($this->once())
->method('find')
->with(123)
->willReturn($user);
$starRepository = $this->getMockBuilder(StarRepository::class)
->disableOriginalConstructor()
->getMock();
$starRepository->expects($this->exactly(2))
->method('findAllByUser')
->with(123)
->willReturn([123]);
$repo = new Repo();
$repo->setId(123);
$repo->setFullName('j0k3r/banditore');
$repo->setUpdatedAt((new \DateTime())->setTimestamp(time() - 3600 * 72));
$repoRepository = $this->getMockBuilder(RepoRepository::class)
->disableOriginalConstructor()
->getMock();
$repoRepository->expects($this->once())
->method('find')
->with(123)
->willReturn($repo);
$responses = new MockHandler([
// /rate_limit
$this->getOKResponse(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => 10]]]),
// first /user/starred
$this->getOKResponse([[
'description' => 'banditore',
'homepage' => 'http://banditore.io',
'language' => 'PHP',
'name' => 'banditore',
'full_name' => 'j0k3r/banditore',
'id' => 123,
'owner' => [
'avatar_url' => 'http://avatar.api/banditore.jpg',
],
]]),
// /rate_limit
$this->getOKResponse(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => 10]]]),
// second /user/starred will return empty response which means, we reached the last page
$this->getOKResponse([]),
// /rate_limit
$this->getOKResponse(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => 10]]]),
]);
$githubClient = $this->getMockClient($responses);
$logger = new Logger('foo');
$logHandler = new TestHandler();
$logger->pushHandler($logHandler);
$redisClient = $this->getMockBuilder(\Predis\Client::class)
->disableOriginalConstructor()
->getMock();
// will use `setex` & `del` but will be called dynamically by `_call`
$redisClient->expects($this->exactly(2))
->method('__call');
$handler = new StarredReposSyncHandler(
$doctrine,
$userRepository,
$starRepository,
$repoRepository,
$githubClient,
$logger,
$redisClient
);
$handler->__invoke(new StarredReposSync(123));
$records = $logHandler->getRecords();
$this->assertSame('Consume banditore.sync_starred_repos message', $records[0]['message']);
$this->assertSame('[10] Check <info>bob</info> … ', $records[1]['message']);
$this->assertSame(' sync 1 starred repos', $records[2]['message']);
$this->assertSame('[10] Synced repos: 1', $records[3]['message']);
}
public function testProcessWithBadClient(): void
{
$doctrine = $this->getMockBuilder(Registry::class)
->disableOriginalConstructor()
->getMock();
$userRepository = $this->getMockBuilder(UserRepository::class)
->disableOriginalConstructor()
->getMock();
$userRepository->expects($this->never())
->method('find');
$starRepository = $this->getMockBuilder(StarRepository::class)
->disableOriginalConstructor()
->getMock();
$starRepository->expects($this->never())
->method('findAllByUser');
$repoRepository = $this->getMockBuilder(RepoRepository::class)
->disableOriginalConstructor()
->getMock();
$repoRepository->expects($this->never())
->method('find');
$logger = new Logger('foo');
$logHandler = new TestHandler();
$logger->pushHandler($logHandler);
$redisClient = $this->getMockBuilder(\Predis\Client::class)
->disableOriginalConstructor()
->getMock();
// will use `setex` & `del` but will be called dynamically by `_call`
$redisClient->expects($this->never())
->method('__call');
$handler = new StarredReposSyncHandler(
$doctrine,
$userRepository,
$starRepository,
$repoRepository,
null, // simulate a bad client
$logger,
$redisClient
);
$handler->__invoke(new StarredReposSync(123));
$records = $logHandler->getRecords();
$this->assertSame('No client provided', $records[0]['message']);
}
public function testProcessWithRateLimitReached(): void
{
$em = $this->getMockBuilder(EntityManager::class)
->disableOriginalConstructor()
->getMock();
$em->expects($this->never())
->method('isOpen');
$doctrine = $this->getMockBuilder(Registry::class)
->disableOriginalConstructor()
->getMock();
$doctrine->expects($this->never())
->method('getManager');
$user = new User();
$user->setId(123);
$user->setUsername('bob');
$user->setName('Bobby');
$userRepository = $this->getMockBuilder(UserRepository::class)
->disableOriginalConstructor()
->getMock();
$userRepository->expects($this->once())
->method('find')
->with(123)
->willReturn($user);
$starRepository = $this->getMockBuilder(StarRepository::class)
->disableOriginalConstructor()
->getMock();
$starRepository->expects($this->never())
->method('findAllByUser');
$starRepository->expects($this->never())
->method('removeFromUser');
$repoRepository = $this->getMockBuilder(RepoRepository::class)
->disableOriginalConstructor()
->getMock();
$repoRepository->expects($this->never())
->method('find');
$responses = new MockHandler([
// /rate_limit
$this->getOKResponse(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => 0]]]),
]);
$githubClient = $this->getMockClient($responses);
$logger = new Logger('foo');
$logHandler = new TestHandler();
$logger->pushHandler($logHandler);
$redisClient = $this->getMockBuilder(\Predis\Client::class)
->disableOriginalConstructor()
->getMock();
// will use `setex` & `del` but will be called dynamically by `_call`
$redisClient->expects($this->once())
->method('__call');
$handler = new StarredReposSyncHandler(
$doctrine,
$userRepository,
$starRepository,
$repoRepository,
$githubClient,
$logger,
$redisClient
);
$handler->__invoke(new StarredReposSync(123));
$records = $logHandler->getRecords();
$this->assertSame('Consume banditore.sync_starred_repos message', $records[0]['message']);
$this->assertSame('[0] Check <info>bob</info> … ', $records[1]['message']);
$this->assertSame('RateLimit reached, stopping.', $records[2]['message']);
}
public function testFunctionalConsumer(): void
{
$responses = new MockHandler([
// /rate_limit
$this->getOKResponse(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => 10]]]),
// first /user/starred
$this->getOKResponse([[
'description' => 'banditore',
'homepage' => 'http://banditore.io',
'language' => 'PHP',
'name' => 'banditore',
'full_name' => 'j0k3r/banditore',
'id' => 777,
'owner' => [
'avatar_url' => 'http://avatar.api/banditore.jpg',
],
]]),
// /rate_limit
$this->getOKResponse(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => 10]]]),
// second /user/starred
$this->getOKResponse([[
'description' => 'This is a test repo',
'homepage' => 'http://test.io',
'language' => 'Ruby',
'name' => 'test',
'full_name' => 'test/test',
'id' => 666,
'owner' => [
'avatar_url' => 'http://0.0.0.0/test.jpg',
],
]]),
// /rate_limit
$this->getOKResponse(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => 8]]]),
// third /user/starred will return empty response which means, we reached the last page
$this->getOKResponse([]),
// /rate_limit
$this->getOKResponse(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => 6]]]),
]);
$githubClient = $this->getMockClient($responses);
$client = static::createClient();
// override factory to avoid real call to Github
self::getContainer()->set('banditore.client.github.test', $githubClient);
$handler = self::getContainer()->get(StarredReposSyncHandler::class);
// before import
$stars = self::getContainer()->get(StarRepository::class)->findAllByUser(123);
$this->assertCount(2, $stars, 'User 123 has 2 starred repos');
$this->assertSame(555, $stars[0], 'User 123 has "symfony/symfony" starred repo');
$this->assertSame(666, $stars[1], 'User 123 has "test/test" starred repo');
$handler->__invoke(new StarredReposSync(123));
/** @var Repo */
$repo = self::getContainer()->get(RepoRepository::class)->find(777);
$this->assertNotNull($repo, 'Imported repo with id 777 exists');
$this->assertSame('j0k3r/banditore', $repo->getFullName(), 'Imported repo with id 777 exists');
// validate that `test/test` association got removed
$stars = self::getContainer()->get(StarRepository::class)->findAllByUser(123);
$this->assertCount(2, $stars, 'User 123 has 2 starred repos');
$this->assertSame(666, $stars[0], 'User 123 has "test/test" starred repo');
$this->assertSame(777, $stars[1], 'User 123 has "j0k3r/banditore" starred repo');
}
private function getOKResponse(array $body): Response
{
return new Response(
200,
['Content-Type' => 'application/json'],
(string) json_encode($body)
);
}
private function getMockClient(MockHandler $responses): GithubClient
{
$clientHandler = HandlerStack::create($responses);
$guzzleClient = new Client([
'handler' => $clientHandler,
]);
$httpClient = new Guzzle7Client($guzzleClient);
$httpBuilder = new Builder($httpClient);
$githubClient = new GithubClient($httpBuilder);
return $githubClient;
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/tests/MessageHandler/VersionsSyncHandlerTest.php | tests/MessageHandler/VersionsSyncHandlerTest.php | <?php
namespace App\Tests\MessageHandler;
use App\Entity\Repo;
use App\Entity\Version;
use App\Message\VersionsSync;
use App\MessageHandler\VersionsSyncHandler;
use App\PubSubHubbub\Publisher;
use App\Repository\RepoRepository;
use App\Repository\VersionRepository;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\UnitOfWork;
use Github\Client as GithubClient;
use Github\HttpClient\Builder;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use Http\Adapter\Guzzle7\Client as Guzzle7Client;
use Monolog\Handler\TestHandler;
use Monolog\Logger;
use Psr\Log\NullLogger;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class VersionsSyncHandlerTest extends WebTestCase
{
public function testProcessNoRepo(): void
{
$doctrine = $this->getMockBuilder(Registry::class)
->disableOriginalConstructor()
->getMock();
$repoRepository = $this->getMockBuilder(RepoRepository::class)
->disableOriginalConstructor()
->getMock();
$repoRepository->expects($this->once())
->method('find')
->with(123)
->willReturn(null);
$versionRepository = $this->getMockBuilder(VersionRepository::class)
->disableOriginalConstructor()
->getMock();
$pubsubhubbub = $this->getMockBuilder(Publisher::class)
->disableOriginalConstructor()
->getMock();
$githubClient = $this->getMockBuilder(GithubClient::class)
->disableOriginalConstructor()
->getMock();
$githubClient->expects($this->never())
->method('authenticate');
$handler = new VersionsSyncHandler(
$doctrine,
$repoRepository,
$versionRepository,
$pubsubhubbub,
$githubClient,
new NullLogger()
);
$handler->__invoke(new VersionsSync(123));
}
public function getWorkingResponses(): MockHandler
{
return new MockHandler([
// rate_limit
$this->getOKResponse(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => 10]]]),
// repo/tags
$this->getOKResponse([[
'name' => '2.0.1',
'zipball_url' => 'https://api.github.com/repos/snc/SncRedisBundle/zipball/2.0.1',
'tarball_url' => 'https://api.github.com/repos/snc/SncRedisBundle/tarball/2.0.1',
'commit' => [
'sha' => '02c808d157c79ac32777e19f3ec31af24a32d2df',
'url' => 'https://api.github.com/repos/snc/SncRedisBundle/commits/02c808d157c79ac32777e19f3ec31af24a32d2df',
],
]]),
// git/refs/tags
$this->getOKResponse([
[
'ref' => 'refs/tags/1.0.0',
'url' => 'https://api.github.com/repos/snc/SncRedisBundle/git/refs/tags/1.0.0',
'object' => [
'sha' => '04b99722e0c25bfc45926cd3a1081c04a8e950ed',
'type' => 'commit',
'url' => 'https://api.github.com/repos/snc/SncRedisBundle/git/commits/04b99722e0c25bfc45926cd3a1081c04a8e950ed',
],
],
[
'ref' => 'refs/tags/1.0.1',
'url' => 'https://api.github.com/repos/snc/SncRedisBundle/git/refs/tags/1.0.1',
'object' => [
'sha' => '4845571072d49c2794b165482420b66c206a942a',
'type' => 'commit',
'url' => 'https://api.github.com/repos/snc/SncRedisBundle/git/commits/4845571072d49c2794b165482420b66c206a942a',
],
],
[
'ref' => 'refs/tags/1.0.2',
'url' => 'https://api.github.com/repos/snc/SncRedisBundle/git/refs/tags/1.0.2',
'object' => [
'sha' => '694b8cc3983f52209029605300910507bec700b4',
'type' => 'tag',
'url' => 'https://api.github.com/repos/snc/SncRedisBundle/git/tags/694b8cc3983f52209029605300910507bec700b4',
],
],
[
'ref' => 'refs/tags/2.0.1',
'url' => 'https://api.github.com/repos/snc/SncRedisBundle/git/refs/tags/2.0.1',
'object' => [
'sha' => '02c808d157c79ac32777e19f3ec31af24a32d2df',
'type' => 'commit',
'url' => 'https://api.github.com/repos/snc/SncRedisBundle/git/commits/02c808d157c79ac32777e19f3ec31af24a32d2df',
],
],
]),
// TAG 1.0.1
// repos/release with tag 1.0.1 (which is not a release)
new Response(404, ['Content-Type' => 'application/json'], (string) json_encode([
'message' => 'Not Found',
'documentation_url' => 'https://developer.github.com/v3',
])),
// retrieve tag information from the commit (since the release does not exist)
$this->getOKResponse([
'sha' => '4845571072d49c2794b165482420b66c206a942a',
'url' => 'https://api.github.com/repos/snc/SncRedisBundle/git/commits/4845571072d49c2794b165482420b66c206a942a',
'html_url' => 'https://github.com/snc/SncRedisBundle/commit/4845571072d49c2794b165482420b66c206a942a',
'author' => [
'name' => 'Daniele Alessandri',
'email' => 'suppakilla@gmail.com',
'date' => '2011-10-15T07:49:04Z',
],
'committer' => [
'name' => 'Daniele Alessandri',
'email' => 'suppakilla@gmail.com',
'date' => '2011-10-15T07:49:21Z',
],
'tree' => [
'sha' => '0f570c5083aa017b7cb5a4b83869ed5054c17764',
'url' => 'https://api.github.com/repos/snc/SncRedisBundle/git/trees/0f570c5083aa017b7cb5a4b83869ed5054c17764',
],
'message' => 'Use the correct package type for composer.',
'parents' => [[
'sha' => '40f7ee543e217aa3a1eadbc952df56b548071d20',
'url' => 'https://api.github.com/repos/snc/SncRedisBundle/git/commits/40f7ee543e217aa3a1eadbc952df56b548071d20',
'html_url' => 'https://github.com/snc/SncRedisBundle/commit/40f7ee543e217aa3a1eadbc952df56b548071d20',
]],
]),
// markdown
new Response(200, ['Content-Type' => 'text/html'], '<p>Use the correct package type for composer.</p>'),
// TAG 1.0.2
// repos/release with tag 1.0.2 (which is not a release)
new Response(404, ['Content-Type' => 'application/json'], (string) json_encode([
'message' => 'Not Found',
'documentation_url' => 'https://developer.github.com/v3',
])),
// retrieve tag information from the tag (since the release does not exist)
$this->getOKResponse([
'sha' => '694b8cc3983f52209029605300910507bec700b4',
'url' => 'https://api.github.com/repos/snc/SncRedisBundle/git/tags/694b8cc3983f52209029605300910507bec700b4',
'tagger' => [
'name' => 'Erwin Mombay',
'email' => 'erwinm@google.com',
'date' => '2012-10-18T17:23:37Z',
],
'object' => [
'sha' => '694b8cc3983f52209029605300910507bec700b5',
'type' => 'commit',
'url' => 'https://api.github.com/repos/snc/SncRedisBundle/git/commits/694b8cc3983f52209029605300910507bec700b5',
],
'tag' => '1.0.2',
'message' => "weekly release\n-----BEGIN PGP SIGNATURE-----\nVersion: GnuPG v2\n\niF4EABEIAAYFAliw58IACgkQ64qmmlZsB5VNFwD+L1M86cO76oohqSy4TCbubPAL\n6341glOKJpfkwyjQnUkBAPCTZSBbe8CFHLxLUvypIiQSMn+AIkPfvzvSEahA40Vz\n=SaF+\n-----END PGP SIGNATURE-----\n",
]),
// markdown
new Response(200, ['Content-Type' => 'text/html'], '<p>weekly release</p>'),
// TAG 2.0.1
// now tag 2.0.1 which is a release
$this->getOKResponse([
'tag_name' => '2.0.1',
'name' => 'Trade-off memory for compute, Windows support, 24 distributions with cdf, variance etc., dtypes, zero-dimensional Tensors, Tensor-Variable merge, , faster distributed, perf and bug fixes, CuDNN 7.1',
'prerelease' => false,
'published_at' => '2017-02-19T13:27:32Z',
'body' => 'yay',
]),
// markdown
new Response(200, ['Content-Type' => 'text/html'], '<p>yay</p>'),
// rate_limit
$this->getOKResponse(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => 10]]]),
]);
}
public function testProcessSuccessfulMessage(): void
{
$uow = $this->getMockBuilder(UnitOfWork::class)
->disableOriginalConstructor()
->getMock();
$uow->expects($this->exactly(3))
->method('getScheduledEntityInsertions')
->willReturn([]);
$em = $this->getMockBuilder(EntityManager::class)
->disableOriginalConstructor()
->getMock();
$em->expects($this->once())
->method('isOpen')
->willReturn(false); // simulate a closing manager
$em->expects($this->exactly(3))
->method('getUnitOfWork')
->willReturn($uow);
$doctrine = $this->getMockBuilder(Registry::class)
->disableOriginalConstructor()
->getMock();
$doctrine->expects($this->once())
->method('getManager')
->willReturn($em);
$doctrine->expects($this->once())
->method('resetManager')
->willReturn($em);
$repo = new Repo();
$repo->setId(123);
$repo->setFullName('bob/wow');
$repo->setName('wow');
$repoRepository = $this->getMockBuilder(RepoRepository::class)
->disableOriginalConstructor()
->getMock();
$repoRepository->expects($this->once())
->method('find')
->with(123)
->willReturn($repo);
$versionRepository = $this->getMockBuilder(VersionRepository::class)
->disableOriginalConstructor()
->getMock();
$versionRepository->expects($this->exactly(4))
->method('findExistingOne')
->willReturnCallback(function ($tagName, $repoId) use ($repo) {
// first version will exist, next one won't
if ('1.0.0' === $tagName) {
return new Version($repo);
}
});
$pubsubhubbub = $this->getMockBuilder(Publisher::class)
->disableOriginalConstructor()
->getMock();
$pubsubhubbub->expects($this->once())
->method('pingHub')
->with([123]);
$clientHandler = HandlerStack::create($this->getWorkingResponses());
$guzzleClient = new Client([
'handler' => $clientHandler,
]);
$httpClient = new Guzzle7Client($guzzleClient);
$httpBuilder = new Builder($httpClient);
$githubClient = new GithubClient($httpBuilder);
$logger = new Logger('foo');
$logHandler = new TestHandler();
$logger->pushHandler($logHandler);
$handler = new VersionsSyncHandler(
$doctrine,
$repoRepository,
$versionRepository,
$pubsubhubbub,
$githubClient,
$logger
);
$handler->__invoke(new VersionsSync(123));
$records = $logHandler->getRecords();
$this->assertSame('Consume banditore.sync_versions message', $records[0]['message']);
$this->assertSame('[10] Check <info>bob/wow</info> … ', $records[1]['message']);
$this->assertSame('[10] <comment>3</comment> new versions for <info>bob/wow</info>', $records[2]['message']);
}
/**
* The call to repo/tags will return a bad response.
*/
public function testProcessRepoTagFailed(): void
{
$em = $this->getMockBuilder(EntityManager::class)
->disableOriginalConstructor()
->getMock();
$em->expects($this->once())
->method('isOpen')
->willReturn(true);
$doctrine = $this->getMockBuilder(Registry::class)
->disableOriginalConstructor()
->getMock();
$doctrine->expects($this->once())
->method('getManager')
->willReturn($em);
$repo = new Repo();
$repo->setId(123);
$repo->setFullName('bob/wow');
$repo->setName('wow');
$repoRepository = $this->getMockBuilder(RepoRepository::class)
->disableOriginalConstructor()
->getMock();
$repoRepository->expects($this->once())
->method('find')
->with(123)
->willReturn($repo);
$versionRepository = $this->getMockBuilder(VersionRepository::class)
->disableOriginalConstructor()
->getMock();
$pubsubhubbub = $this->getMockBuilder(Publisher::class)
->disableOriginalConstructor()
->getMock();
$pubsubhubbub->expects($this->never())
->method('pingHub');
$responses = new MockHandler([
// rate_limit
$this->getOKResponse(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => 10]]]),
// repo/tags generate a bad request
new Response(400, ['Content-Type' => 'application/json']),
// rate_limit
$this->getOKResponse(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => 10]]]),
]);
$clientHandler = HandlerStack::create($responses);
$guzzleClient = new Client([
'handler' => $clientHandler,
]);
$httpClient = new Guzzle7Client($guzzleClient);
$httpBuilder = new Builder($httpClient);
$githubClient = new GithubClient($httpBuilder);
$logger = new Logger('foo');
$logHandler = new TestHandler();
$logger->pushHandler($logHandler);
$handler = new VersionsSyncHandler(
$doctrine,
$repoRepository,
$versionRepository,
$pubsubhubbub,
$githubClient,
$logger
);
$handler->__invoke(new VersionsSync(123));
$records = $logHandler->getRecords();
$this->assertSame('Consume banditore.sync_versions message', $records[0]['message']);
$this->assertSame('[10] Check <info>bob/wow</info> … ', $records[1]['message']);
$this->assertStringContainsString('(repo/tags) <error>', $records[2]['message']);
}
/**
* The call to repo/tags will return a "404" then the repo will be flag as removed.
*/
public function testProcessRepoNotFound(): void
{
$em = $this->getMockBuilder(EntityManager::class)
->disableOriginalConstructor()
->getMock();
$em->expects($this->once())
->method('isOpen')
->willReturn(true);
$doctrine = $this->getMockBuilder(Registry::class)
->disableOriginalConstructor()
->getMock();
$doctrine->expects($this->once())
->method('getManager')
->willReturn($em);
$repo = new Repo();
$repo->setId(123);
$repo->setFullName('bob/wow');
$repo->setName('wow');
$repoRepository = $this->getMockBuilder(RepoRepository::class)
->disableOriginalConstructor()
->getMock();
$repoRepository->expects($this->once())
->method('find')
->with(123)
->willReturn($repo);
$versionRepository = $this->getMockBuilder(VersionRepository::class)
->disableOriginalConstructor()
->getMock();
$pubsubhubbub = $this->getMockBuilder(Publisher::class)
->disableOriginalConstructor()
->getMock();
$pubsubhubbub->expects($this->never())
->method('pingHub');
$responses = new MockHandler([
// rate_limit
$this->getOKResponse(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => 10]]]),
// repo/tags generate a bad request
new Response(404, ['Content-Type' => 'application/json']),
// rate_limit
$this->getOKResponse(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => 10]]]),
]);
$clientHandler = HandlerStack::create($responses);
$guzzleClient = new Client([
'handler' => $clientHandler,
]);
$httpClient = new Guzzle7Client($guzzleClient);
$httpBuilder = new Builder($httpClient);
$githubClient = new GithubClient($httpBuilder);
$logger = new Logger('foo');
$logHandler = new TestHandler();
$logger->pushHandler($logHandler);
$handler = new VersionsSyncHandler(
$doctrine,
$repoRepository,
$versionRepository,
$pubsubhubbub,
$githubClient,
$logger
);
$handler->__invoke(new VersionsSync(123));
$records = $logHandler->getRecords();
$this->assertSame('Consume banditore.sync_versions message', $records[0]['message']);
$this->assertSame('[10] Check <info>bob/wow</info> … ', $records[1]['message']);
$this->assertStringContainsString('(repo/tags) <error>', $records[2]['message']);
$this->assertNotNull($repo->getRemovedAt());
}
/**
* Not enough calls remaining.
*/
public function testProcessCallsRemaingLow(): void
{
$em = $this->getMockBuilder(EntityManager::class)
->disableOriginalConstructor()
->getMock();
$em->expects($this->never())
->method('isOpen');
$doctrine = $this->getMockBuilder(Registry::class)
->disableOriginalConstructor()
->getMock();
$doctrine->expects($this->never())
->method('getManager');
$repo = new Repo();
$repo->setId(123);
$repo->setFullName('bob/wow');
$repo->setName('wow');
$repoRepository = $this->getMockBuilder(RepoRepository::class)
->disableOriginalConstructor()
->getMock();
$repoRepository->expects($this->once())
->method('find')
->with(123)
->willReturn($repo);
$versionRepository = $this->getMockBuilder(VersionRepository::class)
->disableOriginalConstructor()
->getMock();
$pubsubhubbub = $this->getMockBuilder(Publisher::class)
->disableOriginalConstructor()
->getMock();
$pubsubhubbub->expects($this->never())
->method('pingHub');
$responses = new MockHandler([
// rate_limit
$this->getOKResponse(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => 0]]]),
]);
$clientHandler = HandlerStack::create($responses);
$guzzleClient = new Client([
'handler' => $clientHandler,
]);
$httpClient = new Guzzle7Client($guzzleClient);
$httpBuilder = new Builder($httpClient);
$githubClient = new GithubClient($httpBuilder);
$logger = new Logger('foo');
$logHandler = new TestHandler();
$logger->pushHandler($logHandler);
$handler = new VersionsSyncHandler(
$doctrine,
$repoRepository,
$versionRepository,
$pubsubhubbub,
$githubClient,
$logger
);
$handler->__invoke(new VersionsSync(123));
$records = $logHandler->getRecords();
$this->assertSame('Consume banditore.sync_versions message', $records[0]['message']);
$this->assertSame('[0] Check <info>bob/wow</info> … ', $records[1]['message']);
$this->assertStringContainsString('RateLimit reached, stopping.', $records[2]['message']);
}
/**
* The call to markdown will return a bad response.
*/
public function testProcessMarkdownFailed(): void
{
$uow = $this->getMockBuilder(UnitOfWork::class)
->disableOriginalConstructor()
->getMock();
$uow->expects($this->once())
->method('getScheduledEntityInsertions')
->willReturn([]);
$em = $this->getMockBuilder(EntityManager::class)
->disableOriginalConstructor()
->getMock();
$em->expects($this->once())
->method('isOpen')
->willReturn(true);
$em->expects($this->once())
->method('getUnitOfWork')
->willReturn($uow);
$doctrine = $this->getMockBuilder(Registry::class)
->disableOriginalConstructor()
->getMock();
$doctrine->expects($this->once())
->method('getManager')
->willReturn($em);
$repo = new Repo();
$repo->setId(123);
$repo->setFullName('bob/wow');
$repo->setName('wow');
$repoRepository = $this->getMockBuilder(RepoRepository::class)
->disableOriginalConstructor()
->getMock();
$repoRepository->expects($this->once())
->method('find')
->with(123)
->willReturn($repo);
$versionRepository = $this->getMockBuilder(VersionRepository::class)
->disableOriginalConstructor()
->getMock();
$versionRepository->expects($this->once())
->method('findExistingOne')
->willReturn(null);
$pubsubhubbub = $this->getMockBuilder(Publisher::class)
->disableOriginalConstructor()
->getMock();
$pubsubhubbub->expects($this->never())
->method('pingHub');
$responses = new MockHandler([
// rate_limit
$this->getOKResponse(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => 10]]]),
// repo/tags
$this->getOKResponse([[
'name' => '2.0.1',
'zipball_url' => 'https://api.github.com/repos/snc/SncRedisBundle/zipball/2.0.1',
'tarball_url' => 'https://api.github.com/repos/snc/SncRedisBundle/tarball/2.0.1',
'commit' => [
'sha' => '02c808d157c79ac32777e19f3ec31af24a32d2df',
'url' => 'https://api.github.com/repos/snc/SncRedisBundle/commits/02c808d157c79ac32777e19f3ec31af24a32d2df',
],
]]),
// git/refs/tags generate a bad request
$this->getOKResponse([
[
'ref' => 'refs/tags/1.0.0',
'url' => 'https://api.github.com/repos/snc/SncRedisBundle/git/refs/tags/1.0.0',
'object' => [
'sha' => '04b99722e0c25bfc45926cd3a1081c04a8e950ed',
'type' => 'commit',
'url' => 'https://api.github.com/repos/snc/SncRedisBundle/git/commits/04b99722e0c25bfc45926cd3a1081c04a8e950ed',
],
],
]),
// now tag 1.0.0 which is a release
$this->getOKResponse([
'tag_name' => '1.0.0',
'name' => '1.0.0',
'prerelease' => false,
'published_at' => '2017-02-19T13:27:32Z',
'body' => 'yay',
]),
// markdown failed
new Response(400, ['Content-Type' => 'text/html'], 'booboo'),
// rate_limit
$this->getOKResponse(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => 10]]]),
]);
$clientHandler = HandlerStack::create($responses);
$guzzleClient = new Client([
'handler' => $clientHandler,
]);
$httpClient = new Guzzle7Client($guzzleClient);
$httpBuilder = new Builder($httpClient);
$githubClient = new GithubClient($httpBuilder);
$logger = new Logger('foo');
$logHandler = new TestHandler();
$logger->pushHandler($logHandler);
$handler = new VersionsSyncHandler(
$doctrine,
$repoRepository,
$versionRepository,
$pubsubhubbub,
$githubClient,
$logger
);
$handler->__invoke(new VersionsSync(123));
$records = $logHandler->getRecords();
$this->assertSame('Consume banditore.sync_versions message', $records[0]['message']);
$this->assertSame('[10] Check <info>bob/wow</info> … ', $records[1]['message']);
$this->assertStringContainsString('<error>Failed to parse markdown', $records[2]['message']);
}
/**
* No tag found for that repo.
*/
public function testProcessNoTagFound(): void
{
$em = $this->getMockBuilder(EntityManager::class)
->disableOriginalConstructor()
->getMock();
$em->expects($this->once())
->method('isOpen')
->willReturn(true);
$doctrine = $this->getMockBuilder(Registry::class)
->disableOriginalConstructor()
->getMock();
$doctrine->expects($this->once())
->method('getManager')
->willReturn($em);
$repo = new Repo();
$repo->setId(123);
$repo->setFullName('bob/wow');
$repo->setName('wow');
$repoRepository = $this->getMockBuilder(RepoRepository::class)
->disableOriginalConstructor()
->getMock();
$repoRepository->expects($this->once())
->method('find')
->with(123)
->willReturn($repo);
$versionRepository = $this->getMockBuilder(VersionRepository::class)
->disableOriginalConstructor()
->getMock();
$pubsubhubbub = $this->getMockBuilder(Publisher::class)
->disableOriginalConstructor()
->getMock();
$pubsubhubbub->expects($this->never())
->method('pingHub');
$responses = new MockHandler([
// rate_limit
$this->getOKResponse(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => 10]]]),
// repo/tags
$this->getOKResponse([]),
// rate_limit
$this->getOKResponse(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => 10]]]),
]);
$clientHandler = HandlerStack::create($responses);
$guzzleClient = new Client([
'handler' => $clientHandler,
]);
$httpClient = new Guzzle7Client($guzzleClient);
$httpBuilder = new Builder($httpClient);
$githubClient = new GithubClient($httpBuilder);
$logger = new Logger('foo');
$logHandler = new TestHandler();
$logger->pushHandler($logHandler);
$handler = new VersionsSyncHandler(
$doctrine,
$repoRepository,
$versionRepository,
$pubsubhubbub,
$githubClient,
$logger
);
$handler->__invoke(new VersionsSync(123));
$records = $logHandler->getRecords();
$this->assertSame('Consume banditore.sync_versions message', $records[0]['message']);
$this->assertSame('[10] Check <info>bob/wow</info> … ', $records[1]['message']);
$this->assertSame('[10] <comment>0</comment> new versions for <info>bob/wow</info>', $records[2]['message']);
}
/**
* Generate an unexpected error (like from MySQL).
*/
public function testProcessUnexpectedError(): void
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('booboo');
$em = $this->getMockBuilder(EntityManager::class)
->disableOriginalConstructor()
->getMock();
$em->expects($this->once())
->method('isOpen')
->willReturn(true);
$doctrine = $this->getMockBuilder(Registry::class)
->disableOriginalConstructor()
->getMock();
$doctrine->expects($this->once())
->method('getManager')
->willReturn($em);
$repo = new Repo();
$repo->setId(123);
$repo->setFullName('bob/wow');
$repo->setName('wow');
$repoRepository = $this->getMockBuilder(RepoRepository::class)
->disableOriginalConstructor()
->getMock();
$repoRepository->expects($this->once())
->method('find')
->with(123)
->willReturn($repo);
$versionRepository = $this->getMockBuilder(VersionRepository::class)
->disableOriginalConstructor()
->getMock();
$versionRepository->expects($this->once())
->method('findExistingOne')
->will($this->throwException(new \Exception('booboo')));
$pubsubhubbub = $this->getMockBuilder(Publisher::class)
->disableOriginalConstructor()
->getMock();
$pubsubhubbub->expects($this->never())
->method('pingHub');
$responses = new MockHandler([
// rate_limit
$this->getOKResponse(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => 10]]]),
// repo/tags
$this->getOKResponse([[
'name' => '2.0.1',
'zipball_url' => 'https://api.github.com/repos/snc/SncRedisBundle/zipball/2.0.1',
'tarball_url' => 'https://api.github.com/repos/snc/SncRedisBundle/tarball/2.0.1',
'commit' => [
'sha' => '02c808d157c79ac32777e19f3ec31af24a32d2df',
'url' => 'https://api.github.com/repos/snc/SncRedisBundle/commits/02c808d157c79ac32777e19f3ec31af24a32d2df',
],
]]),
// git/refs/tags
$this->getOKResponse([
[
'ref' => 'refs/tags/1.0.0',
'url' => 'https://api.github.com/repos/snc/SncRedisBundle/git/refs/tags/1.0.0',
'object' => [
'sha' => '04b99722e0c25bfc45926cd3a1081c04a8e950ed',
'type' => 'commit',
'url' => 'https://api.github.com/repos/snc/SncRedisBundle/git/commits/04b99722e0c25bfc45926cd3a1081c04a8e950ed',
],
],
]),
// rate_limit
$this->getOKResponse(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => 10]]]),
]);
$clientHandler = HandlerStack::create($responses);
$guzzleClient = new Client([
'handler' => $clientHandler,
]);
$httpClient = new Guzzle7Client($guzzleClient);
$httpBuilder = new Builder($httpClient);
$githubClient = new GithubClient($httpBuilder);
$handler = new VersionsSyncHandler(
$doctrine,
$repoRepository,
$versionRepository,
$pubsubhubbub,
$githubClient,
new NullLogger()
);
$handler->__invoke(new VersionsSync(123));
}
/**
* The call to git/refs/tags will return a bad response.
*/
public function testProcessGitRefTagFailed(): void
{
$em = $this->getMockBuilder(EntityManager::class)
->disableOriginalConstructor()
->getMock();
$em->expects($this->once())
->method('isOpen')
->willReturn(true);
$doctrine = $this->getMockBuilder(Registry::class)
->disableOriginalConstructor()
->getMock();
$doctrine->expects($this->once())
->method('getManager')
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | true |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/tests/Controller/DefaultControllerTest.php | tests/Controller/DefaultControllerTest.php | <?php
namespace App\Tests\Controller;
use App\Entity\User;
use App\Repository\UserRepository;
use MarcW\RssWriter\Bridge\Symfony\HttpFoundation\RssStreamedResponse;
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\RedirectResponse;
class DefaultControllerTest extends WebTestCase
{
/** @var KernelBrowser */
private $client;
protected function setUp(): void
{
$this->client = static::createClient();
}
public function testIndexNotLoggedIn(): void
{
$crawler = $this->client->request('GET', '/');
$this->assertResponseIsSuccessful();
$this->assertSelectorTextContains('a.pure-menu-heading', 'Bandito.re');
}
public function testIndexLoggedIn(): void
{
/** @var User */
$user = self::getContainer()->get(UserRepository::class)->find(123);
$this->client->loginUser($user);
$this->client->request('GET', '/');
$this->assertResponseRedirects('/dashboard', 302);
}
public function testConnect(): void
{
$this->client->request('GET', '/connect');
/** @var RedirectResponse */
$response = $this->client->getResponse();
$this->assertSame(302, $response->getStatusCode());
$this->assertStringContainsString('https://github.com/login/oauth/authorize?', $response->getTargetUrl());
}
public function testConnectWithLoggedInUser(): void
{
/** @var User */
$user = self::getContainer()->get(UserRepository::class)->find(123);
$this->client->loginUser($user);
$this->client->request('GET', '/connect');
$this->assertResponseRedirects('/dashboard', 302);
}
public function testDashboardNotLoggedIn(): void
{
$this->client->request('GET', '/dashboard');
$this->assertResponseRedirects('/', 302);
}
public function testDashboard(): void
{
/** @var User */
$user = self::getContainer()->get(UserRepository::class)->find(123);
$this->client->loginUser($user);
$crawler = $this->client->request('GET', '/dashboard');
$this->assertResponseIsSuccessful();
$menu = $crawler->filter('.menu-wrapper')->text();
$this->assertStringContainsString('View it on GitHub', $menu, 'Link to GitHub is here');
$this->assertStringContainsString('Logout (admin)', $menu, 'Info about logged in user is here');
$aside = $crawler->filter('aside.feed')->text();
$this->assertStringContainsString('your feed link', $aside, 'Feed link is here');
$table = $crawler->filter('table')->text();
$this->assertStringContainsString('test/test', $table, 'Repo test/test exist in a table');
$this->assertStringContainsString('ago', $table, 'Date is translated and ok');
}
public function testDashboardPageTooHigh(): void
{
/** @var User */
$user = self::getContainer()->get(UserRepository::class)->find(123);
$this->client->loginUser($user);
$crawler = $this->client->request('GET', '/dashboard?page=20000');
$this->assertResponseRedirects('/dashboard', 302);
}
public function testDashboardBadPage(): void
{
/** @var User */
$user = self::getContainer()->get(UserRepository::class)->find(123);
$this->client->loginUser($user);
$this->client->request('GET', '/dashboard?page=dsdsds');
$this->assertResponseStatusCodeSame(404);
}
public function testRss(): void
{
/** @var User */
$user = self::getContainer()->get(UserRepository::class)->find(123);
$crawler = $this->client->request('GET', '/' . $user->getUuid() . '.atom');
$this->assertResponseIsSuccessful();
$this->assertInstanceOf(RssStreamedResponse::class, $this->client->getResponse());
$this->assertSelectorTextContains('channel>title', 'New releases from starred repo of admin');
$this->assertSelectorTextContains('channel>description', 'Here are all the new releases from all repos starred by admin');
$this->assertSame('http://0.0.0.0/avatar.jpg', $crawler->filterXPath('//webfeeds:icon')->text());
$this->assertSame('10556B', $crawler->filterXPath('//webfeeds:accentColor')->text());
$link = $crawler->filterXPath('//atom:link');
$this->assertSame('http://localhost/' . $user->getUuid() . '.atom', $link->getNode(0)->getAttribute('href'));
$this->assertSame('http://pubsubhubbub.appspot.com/', $link->getNode(1)->getAttribute('href'));
$this->assertSame('http://localhost/' . $user->getUuid() . '.atom', $crawler->filter('channel>link')->text());
$this->assertSame('test/test 1.0.0', $crawler->filter('item>title')->text());
}
public function testStats(): void
{
$crawler = $this->client->request('GET', '/stats');
$this->assertResponseIsSuccessful();
}
public function testStatus(): void
{
$crawler = $this->client->request('GET', '/status');
$data = json_decode((string) $this->client->getResponse()->getContent(), true);
$this->assertTrue($data['is_fresh']);
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/tests/Twig/RepoVersionExtensionTest.php | tests/Twig/RepoVersionExtensionTest.php | <?php
namespace App\Tests\Twig;
use App\Twig\RepoVersionExtension;
use PHPUnit\Framework\TestCase;
class RepoVersionExtensionTest extends TestCase
{
public function test(): void
{
$ext = new RepoVersionExtension();
$this->assertSame('repo_version_extension', $ext->getName());
$this->assertNull($ext->linkToVersion([]));
$this->assertNull($ext->linkToVersion(['fullName' => 'test/test']));
$this->assertNull($ext->linkToVersion(['tagName' => 'v1.0.0']));
$this->assertSame('https://github.com/test/test/releases/v1.0.0', $ext->linkToVersion(['fullName' => 'test/test', 'tagName' => 'v1.0.0']));
}
public function testEncodedTagName(): void
{
$ext = new RepoVersionExtension();
$this->assertSame('repo_version_extension', $ext->getName());
$this->assertNull($ext->linkToVersion([]));
$this->assertNull($ext->linkToVersion(['fullName' => 'test/test']));
$this->assertNull($ext->linkToVersion(['tagName' => '@1.0.0-alpha.1']));
$this->assertSame('https://github.com/test/test/releases/%401.0.0-alpha.1', $ext->linkToVersion(['fullName' => 'test/test', 'tagName' => '@1.0.0-alpha.1']));
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/tests/PubSubHubbub/PublisherTest.php | tests/PubSubHubbub/PublisherTest.php | <?php
namespace App\Tests\PubSubHubbub;
use App\PubSubHubbub\Publisher;
use App\Repository\UserRepository;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
class PublisherTest extends TestCase
{
/** @var Router */
private $router;
protected function setUp(): void
{
$routes = new RouteCollection();
$routes->add('rss_user', new Route('/{uuid}.atom'));
$sc = $this->getServiceContainer($routes);
$this->router = new Router($sc, 'rss_user');
}
public function testNoHubDefined(): void
{
$userRepository = $this->getMockBuilder(UserRepository::class)
->disableOriginalConstructor()
->getMock();
$client = new Client();
$publisher = new Publisher('', $this->router, $client, $userRepository, 'banditore.com', 'http');
$res = $publisher->pingHub([1]);
// the hub url is invalid, so it will be generate an error and return false
$this->assertFalse($res);
}
public function testBadResponse(): void
{
$userRepository = $this->getMockBuilder(UserRepository::class)
->disableOriginalConstructor()
->getMock();
$userRepository->expects($this->once())
->method('findByRepoIds')
->with([123])
->willReturn([['uuid' => '7fc8de31-5371-4f0a-b606-a7e164c41d46']]);
$mock = new MockHandler([
new Response(500),
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$publisher = new Publisher('http://pubsubhubbub.io', $this->router, $client, $userRepository, 'banditore.com', 'http');
$res = $publisher->pingHub([123]);
// the response is bad, so it will return false
$this->assertFalse($res);
}
public function testGoodResponse(): void
{
$userRepository = $this->getMockBuilder(UserRepository::class)
->disableOriginalConstructor()
->getMock();
$userRepository->expects($this->once())
->method('findByRepoIds')
->with([123])
->willReturn([['uuid' => '7fc8de31-5371-4f0a-b606-a7e164c41d46']]);
$mock = new MockHandler([
new Response(204),
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$publisher = new Publisher('http://pubsubhubbub.io', $this->router, $client, $userRepository, 'banditore.com', 'http');
$res = $publisher->pingHub([123]);
$this->assertTrue($res);
}
public function testUrlGeneration(): void
{
$userRepository = $this->getMockBuilder(UserRepository::class)
->disableOriginalConstructor()
->getMock();
$userRepository->expects($this->once())
->method('findByRepoIds')
->with([123])
->willReturn([['uuid' => '7fc8de31-5371-4f0a-b606-a7e164c41d46']]);
$method = new \ReflectionMethod(
Publisher::class, 'retrieveFeedUrls'
);
$urls = $method->invoke(
new Publisher('http://pubsubhubbub.io', $this->router, new Client(), $userRepository, 'banditore.com', 'http'),
[123]
);
$this->assertSame(['http://banditore.com/7fc8de31-5371-4f0a-b606-a7e164c41d46.atom'], $urls);
}
/**
* @see \Symfony\Bundle\FrameworkBundle\Tests\Routing\RouterTest
*/
private function getServiceContainer(RouteCollection $routes): Container
{
$loader = $this->getMockBuilder(LoaderInterface::class)->getMock();
$loader
->expects($this->any())
->method('load')
->willReturn($routes)
;
$sc = $this->getMockBuilder(Container::class)->onlyMethods(['get'])->getMock();
$sc
->expects($this->any())
->method('get')
->willReturn($loader)
;
return $sc;
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/tests/Github/ClientDiscoveryTest.php | tests/Github/ClientDiscoveryTest.php | <?php
namespace App\Tests\Github;
use App\Github\ClientDiscovery;
use App\Repository\UserRepository;
use Github\Client as GithubClient;
use Github\HttpClient\Builder;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use Http\Adapter\Guzzle7\Client as Guzzle7Client;
use Monolog\Handler\TestHandler;
use Monolog\Logger;
use Predis\Client as RedisClient;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class ClientDiscoveryTest extends WebTestCase
{
public function testUseApplicationDefaultClient(): void
{
$userRepository = $this->getMockBuilder(UserRepository::class)
->disableOriginalConstructor()
->getMock();
$responses = new MockHandler([
// first rate_limit, it'll be ok because remaining > 50
new Response(200, ['Content-Type' => 'application/json'], (string) json_encode(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => ClientDiscovery::THRESHOLD_RATE_REMAIN_APP + 1]]])),
]);
$clientHandler = HandlerStack::create($responses);
$guzzleClient = new Client([
'handler' => $clientHandler,
]);
$httpClient = new Guzzle7Client($guzzleClient);
$httpBuilder = new Builder($httpClient);
$githubClient = new GithubClient($httpBuilder);
$redis = new RedisClient();
$logger = new Logger('foo');
$logHandler = new TestHandler();
$logger->pushHandler($logHandler);
$disco = new ClientDiscovery(
$userRepository,
$redis,
'client_id',
'client_secret',
$logger
);
$disco->setGithubClient($githubClient);
$resClient = $disco->find();
$records = $logHandler->getRecords();
$this->assertInstanceOf(GithubClient::class, $resClient);
$this->assertSame('RateLimit ok (' . (ClientDiscovery::THRESHOLD_RATE_REMAIN_APP + 1) . ') with default application', $records[0]['message']);
}
public function testUseUserToken(): void
{
$userRepository = $this->getMockBuilder(UserRepository::class)
->disableOriginalConstructor()
->getMock();
$userRepository->expects($this->once())
->method('findAllTokens')
->willReturn([
[
'id' => '123',
'username' => 'bob',
'accessToken' => '123123',
],
[
'id' => '456',
'username' => 'lion',
'accessToken' => '456456',
],
]);
$responses = new MockHandler([
// first rate_limit, it won't be ok because remaining < 50
new Response(200, ['Content-Type' => 'application/json'], (string) json_encode(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => ClientDiscovery::THRESHOLD_RATE_REMAIN_APP - 40]]])),
// second rate_limit, it won't be ok because remaining < 50
new Response(200, ['Content-Type' => 'application/json'], (string) json_encode(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => ClientDiscovery::THRESHOLD_RATE_REMAIN_USER - 20]]])),
// third rate_limit, it'll' be ok because remaining > 50
new Response(200, ['Content-Type' => 'application/json'], (string) json_encode(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => ClientDiscovery::THRESHOLD_RATE_REMAIN_USER + 150]]])),
]);
$clientHandler = HandlerStack::create($responses);
$guzzleClient = new Client([
'handler' => $clientHandler,
]);
$httpClient = new Guzzle7Client($guzzleClient);
$httpBuilder = new Builder($httpClient);
$githubClient = new GithubClient($httpBuilder);
$redis = new RedisClient();
$logger = new Logger('foo');
$logHandler = new TestHandler();
$logger->pushHandler($logHandler);
$disco = new ClientDiscovery(
$userRepository,
$redis,
'client_id',
'client_secret',
$logger
);
$disco->setGithubClient($githubClient);
$resClient = $disco->find();
$records = $logHandler->getRecords();
$this->assertInstanceOf(GithubClient::class, $resClient);
$this->assertSame('RateLimit ok (' . (ClientDiscovery::THRESHOLD_RATE_REMAIN_USER + 150) . ') with user: lion', $records[0]['message']);
}
public function testNoTokenAvailable(): void
{
$userRepository = $this->getMockBuilder(UserRepository::class)
->disableOriginalConstructor()
->getMock();
$userRepository->expects($this->once())
->method('findAllTokens')
->willReturn([
[
'id' => '123',
'username' => 'bob',
'accessToken' => '123123',
],
]);
$responses = new MockHandler([
// first rate_limit, it won't be ok because remaining < 50
new Response(200, ['Content-Type' => 'application/json'], (string) json_encode(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => ClientDiscovery::THRESHOLD_RATE_REMAIN_APP - 10]]])),
// second rate_limit, it won't be ok because remaining < 50
new Response(200, ['Content-Type' => 'application/json'], (string) json_encode(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => ClientDiscovery::THRESHOLD_RATE_REMAIN_APP - 20]]])),
]);
$clientHandler = HandlerStack::create($responses);
$guzzleClient = new Client([
'handler' => $clientHandler,
]);
$httpClient = new Guzzle7Client($guzzleClient);
$httpBuilder = new Builder($httpClient);
$githubClient = new GithubClient($httpBuilder);
$redis = new RedisClient();
$logger = new Logger('foo');
$logHandler = new TestHandler();
$logger->pushHandler($logHandler);
$disco = new ClientDiscovery(
$userRepository,
$redis,
'client_id',
'client_secret',
$logger
);
$disco->setGithubClient($githubClient);
$resClient = $disco->find();
$records = $logHandler->getRecords();
$this->assertNull($resClient);
$this->assertSame('No way to authenticate a client with enough rate limit remaining :(', $records[0]['message']);
}
public function testOneCallFail(): void
{
$userRepository = $this->getMockBuilder(UserRepository::class)
->disableOriginalConstructor()
->getMock();
$userRepository->expects($this->once())
->method('findAllTokens')
->willReturn([
[
'id' => '123',
'username' => 'bob',
'accessToken' => '123123',
],
]);
$responses = new MockHandler([
// first rate_limit request fail (Github booboo)
new Response(400, ['Content-Type' => 'application/json'], (string) json_encode(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => ClientDiscovery::THRESHOLD_RATE_REMAIN_USER + 100]]])),
// second rate_limit, it'll be ok because remaining > 50
new Response(200, ['Content-Type' => 'application/json'], (string) json_encode(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => ClientDiscovery::THRESHOLD_RATE_REMAIN_USER + 100]]])),
]);
$clientHandler = HandlerStack::create($responses);
$guzzleClient = new Client([
'handler' => $clientHandler,
]);
$httpClient = new Guzzle7Client($guzzleClient);
$httpBuilder = new Builder($httpClient);
$githubClient = new GithubClient($httpBuilder);
$redis = new RedisClient();
$logger = new Logger('foo');
$logHandler = new TestHandler();
$logger->pushHandler($logHandler);
$disco = new ClientDiscovery(
$userRepository,
$redis,
'client_id',
'client_secret',
$logger
);
$disco->setGithubClient($githubClient);
$resClient = $disco->find();
$records = $logHandler->getRecords();
$this->assertInstanceOf(GithubClient::class, $resClient);
$this->assertSame('RateLimit call goes bad.', $records[0]['message']);
$this->assertSame('RateLimit ok (' . (ClientDiscovery::THRESHOLD_RATE_REMAIN_USER + 100) . ') with user: bob', $records[1]['message']);
}
/**
* Using only mocks for request.
*/
public function testFunctionnal(): void
{
$client = static::createClient();
try {
self::getContainer()->get('snc_redis.guzzle_cache')->connect();
} catch (\Exception) {
$this->markTestSkipped('Redis is not installed/activated');
}
$responses = new MockHandler([
// first rate_limit request fail (Github booboo)
new Response(200, ['Content-Type' => 'application/json'], (string) json_encode(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => ClientDiscovery::THRESHOLD_RATE_REMAIN_APP - 10]]])),
// second rate_limit, it'll be ok because remaining > 50
new Response(200, ['Content-Type' => 'application/json'], (string) json_encode(['resources' => ['core' => ['reset' => time() + 1000, 'limit' => 200, 'remaining' => ClientDiscovery::THRESHOLD_RATE_REMAIN_USER + 100]]])),
]);
$clientHandler = HandlerStack::create($responses);
$guzzleClient = new Client([
'handler' => $clientHandler,
]);
$httpClient = new Guzzle7Client($guzzleClient);
$httpBuilder = new Builder($httpClient);
$githubClient = new GithubClient($httpBuilder);
$disco = self::getContainer()->get(ClientDiscovery::class);
$disco->setGithubClient($githubClient);
$resClient = $disco->find();
$this->assertInstanceOf(GithubClient::class, $resClient);
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/tests/Cache/CustomRedisCachePoolTest.php | tests/Cache/CustomRedisCachePoolTest.php | <?php
namespace App\Tests\Cache;
use App\Cache\CustomRedisCachePool;
use Cache\Adapter\Common\CacheItem;
use GuzzleHttp\Psr7\Response;
use Predis\ClientInterface;
use Predis\Response\Status;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class CustomRedisCachePoolTest extends WebTestCase
{
public function testResponseWithEmptyBody(): void
{
$redisStatus = new Status('OK');
$cache = $this->getMockBuilder(ClientInterface::class)
->disableOriginalConstructor()
->getMock();
$cache->expects($this->once())
->method('__call')
->willReturn($redisStatus);
$body = (string) json_encode([]);
$response = new Response(
200,
[],
$body
);
$item = new CacheItem('superkey', true, [
'response' => $response,
'body' => $body,
]);
$cachePool = new CustomRedisCachePool($cache);
$cachePool->save($item);
}
public function testResponseWith404(): void
{
$redisStatus = new Status('OK');
$cache = $this->getMockBuilder(ClientInterface::class)
->disableOriginalConstructor()
->getMock();
$cache->expects($this->once())
->method('__call')
->willReturn($redisStatus);
$response = new Response(404);
$item = new CacheItem('superkey', true, [
'response' => $response,
'body' => '',
]);
$cachePool = new CustomRedisCachePool($cache);
$cachePool->save($item);
}
public function testResponseWithRelease(): void
{
$cache = $this->getMockBuilder(ClientInterface::class)
->disableOriginalConstructor()
->getMock();
$cache->expects($this->never())
->method('__call');
$body = (string) json_encode([
'tag_name' => 'V1.1.0',
'name' => 'V1.1.0',
'prerelease' => false,
'published_at' => '2014-12-01T18:28:39Z',
'body' => 'This is the first release after our major push.',
]);
$response = new Response(
200,
[],
$body
);
$item = new CacheItem('superkey', true, [
'response' => $response,
'body' => $body,
]);
$cachePool = new CustomRedisCachePool($cache);
$cachePool->save($item);
}
public function testResponseWithRefTags(): void
{
$redisStatus = new Status('OK');
$cache = $this->getMockBuilder(ClientInterface::class)
->disableOriginalConstructor()
->getMock();
$cache->expects($this->once())
->method('__call')
->willReturn($redisStatus);
$body = (string) json_encode([[
'ref' => 'refs/tags/1.0.0',
'url' => 'https://api.github.com/repos/snc/SncRedisBundle/git/refs/tags/1.0.0',
'object' => [
'sha' => '04b99722e0c25bfc45926cd3a1081c04a8e950ed',
'type' => 'commit',
'url' => 'https://api.github.com/repos/snc/SncRedisBundle/git/commits/04b99722e0c25bfc45926cd3a1081c04a8e950ed',
],
],
[
'ref' => 'refs/tags/1.0.1',
'url' => 'https://api.github.com/repos/snc/SncRedisBundle/git/refs/tags/1.0.1',
'object' => [
'sha' => '4845571072d49c2794b165482420b66c206a942a',
'type' => 'commit',
'url' => 'https://api.github.com/repos/snc/SncRedisBundle/git/commits/4845571072d49c2794b165482420b66c206a942a',
],
],
]);
$response = new Response(
200,
[],
$body
);
$item = new CacheItem('superkey', true, [
'response' => $response,
'body' => $body,
]);
$cachePool = new CustomRedisCachePool($cache);
$cachePool->save($item);
}
public function testResponseWithTag(): void
{
$redisStatus = new Status('OK');
$cache = $this->getMockBuilder(ClientInterface::class)
->disableOriginalConstructor()
->getMock();
$cache->expects($this->once())
->method('__call')
->willReturn($redisStatus);
$body = (string) json_encode([[
'name' => '2.0.1',
'zipball_url' => 'https://api.github.com/repos/snc/SncRedisBundle/zipball/2.0.1',
'tarball_url' => 'https://api.github.com/repos/snc/SncRedisBundle/tarball/2.0.1',
'commit' => [
'sha' => '02c808d157c79ac32777e19f3ec31af24a32d2df',
'url' => 'https://api.github.com/repos/snc/SncRedisBundle/commits/02c808d157c79ac32777e19f3ec31af24a32d2df',
],
]]);
$response = new Response(
200,
[],
$body
);
$item = new CacheItem('superkey', true, [
'response' => $response,
'body' => $body,
]);
$cachePool = new CustomRedisCachePool($cache);
$cachePool->save($item);
}
public function testResponseWithStarredRepos(): void
{
$redisStatus = new Status('OK');
$cache = $this->getMockBuilder(ClientInterface::class)
->disableOriginalConstructor()
->getMock();
$cache->expects($this->once())
->method('__call')
->willReturn($redisStatus);
$body = (string) json_encode([[
'description' => 'banditore',
'homepage' => 'http://banditore.io',
'language' => 'PHP',
'name' => 'banditore',
'full_name' => 'j0k3r/banditore',
'id' => 666,
'owner' => [
'avatar_url' => 'http://avatar.api/banditore.jpg',
],
]]);
$response = new Response(
200,
[],
$body
);
$item = new CacheItem('superkey', true, [
'response' => $response,
'body' => $body,
]);
$cachePool = new CustomRedisCachePool($cache);
$cachePool->save($item);
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/tests/Rss/GeneratorTest.php | tests/Rss/GeneratorTest.php | <?php
namespace App\Tests\Rss;
use App\Entity\User;
use App\Rss\Generator;
use PHPUnit\Framework\TestCase;
class GeneratorTest extends TestCase
{
public function test(): void
{
$user = new User();
$user->setId(123);
$user->setUsername('bob');
$user->setName('Bobby');
$generator = new Generator();
$channel = $generator->generate(
$user,
[
[
'homepage' => 'http://homepa.ge',
'language' => 'Thus',
'ownerAvatar' => 'http://avat.ar/mine.png',
'fullName' => 'test/test',
'description' => 'This is an awesome description',
'tagName' => '1.0.0',
'body' => '<p>yay</p>',
'createdAt' => (new \DateTime())->setTimestamp(1171502725),
],
],
'http://myfeed.api/.rss'
);
$this->assertSame('New releases from starred repo of bob', $channel->getTitle());
$this->assertSame('http://myfeed.api/.rss', $channel->getLink());
$this->assertSame('Here are all the new releases from all repos starred by bob', $channel->getDescription());
$this->assertSame('en', $channel->getLanguage());
$this->assertStringContainsString('(c)', $channel->getCopyright());
$this->assertStringContainsString('banditore', $channel->getCopyright());
$this->assertStringContainsString('15 Feb 2007', $channel->getLastBuildDate()->format('r'));
$this->assertSame('banditore', $channel->getGenerator());
$items = $channel->getItems();
$this->assertCount(1, $items);
$this->assertSame('test/test 1.0.0', $items[0]->getTitle());
$this->assertSame('https://github.com/test/test/releases/1.0.0', $items[0]->getLink());
$this->assertStringContainsString('<img src="http://avat.ar/mine.png&s=140" alt="test/test" title="test/test" />', $items[0]->getDescription());
$this->assertStringContainsString('#Thus', $items[0]->getDescription());
$this->assertStringContainsString('<p>yay</p>', $items[0]->getDescription());
$this->assertStringContainsString('<b><a href="https://github.com/test/test">test/test</a></b>', $items[0]->getDescription());
$this->assertStringContainsString('(<a href="http://homepa.ge">http://homepa.ge</a>)', $items[0]->getDescription());
$this->assertStringContainsString('This is an awesome description', $items[0]->getDescription());
$this->assertSame('https://github.com/test/test/releases/1.0.0', $items[0]->getGuid()->getGuid());
$this->assertTrue($items[0]->getGuid()->getIsPermaLink());
$this->assertStringContainsString('15 Feb 2007', $items[0]->getPubDate()->format('r'));
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/tests/Security/GithubAuthenticatorTest.php | tests/Security/GithubAuthenticatorTest.php | <?php
namespace App\Tests\Security;
use App\Entity\User;
use App\Message\StarredReposSync;
use App\Repository\UserRepository;
use Github\Client as GithubClient;
use Github\HttpClient\Builder;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use Http\Adapter\Guzzle7\Client as Guzzle7Client;
use KnpU\OAuth2ClientBundle\Client\OAuth2Client;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\RedirectResponse;
class GithubAuthenticatorTest extends WebTestCase
{
public function testCallbackWithExistingUser(): void
{
$this->markTestSkipped('Dunno how to mock the session / access it from the container');
$client = static::createClient();
$responses = new MockHandler([
// /login/oauth/access_token (to retrieve the access_token from `authenticate()`)
new Response(200, ['Content-Type' => 'application/json'], (string) json_encode([
'access_token' => 'blablabla',
])),
// /api/v3/user (to retrieve user information from Github)
new Response(200, ['Content-Type' => 'application/json'], (string) json_encode([
'id' => 123,
'email' => 'toto@test.io',
'name' => 'Bob',
'login' => 'admin',
'avatar_url' => 'http://avat.ar/my.png',
])),
]);
$clientHandler = HandlerStack::create($responses);
$guzzleClient = new Client([
'handler' => $clientHandler,
]);
$httpClient = new Guzzle7Client($guzzleClient);
$httpBuilder = new Builder($httpClient);
$githubClient = new GithubClient($httpBuilder);
self::getContainer()->set('banditore.client.github.application', $githubClient);
self::getContainer()->get('oauth2.registry')->getClient('github')->getOAuth2Provider()->setHttpClient($guzzleClient);
self::getContainer()->get('session')->set(OAuth2Client::OAUTH2_SESSION_STATE_KEY, 'MyAwesomeState');
// before login
/** @var User */
$user = self::getContainer()->get(UserRepository::class)->find(123);
$this->assertSame('1234567890', $user->getAccessToken());
$this->assertSame('http://0.0.0.0/avatar.jpg', $user->getAvatar());
$client->request('GET', '/callback?state=MyAwesomeState&code=MyAwesomeCode');
// after login
/** @var User */
$user = self::getContainer()->get(UserRepository::class)->find(123);
$this->assertSame('blablabla', $user->getAccessToken());
$this->assertSame('http://avat.ar/my.png', $user->getAvatar());
$this->assertSame(302, $client->getResponse()->getStatusCode());
/** @var RedirectResponse */
$response = $client->getResponse();
$this->assertSame('/dashboard', $response->getTargetUrl());
$message = self::getContainer()->get('session')->getFlashBag()->get('info');
$this->assertSame('Successfully logged in!', $message[0]);
$transport = self::getContainer()->get('messenger.transport.sync_starred_repos');
$this->assertCount(1, $transport->get());
$messages = (array) $transport->get();
/** @var StarredReposSync */
$message = $messages[0]->getMessage();
$this->assertSame(123, $message->getUserId());
}
public function testCallbackWithNewUser(): void
{
$this->markTestSkipped('Dunno how to mock the session / access it from the container');
$client = static::createClient();
$responses = new MockHandler([
// /login/oauth/access_token (to retrieve the access_token from `authenticate()`)
new Response(200, ['Content-Type' => 'application/json'], (string) json_encode([
'access_token' => 'superboum',
])),
// /api/v3/user (to retrieve user information from Github)
new Response(200, ['Content-Type' => 'application/json'], (string) json_encode([
'id' => 456,
'email' => 'down@g.et',
'name' => 'Any',
'login' => 'getdown',
'avatar_url' => 'http://avat.ar/down.png',
])),
]);
$clientHandler = HandlerStack::create($responses);
$guzzleClient = new Client([
'handler' => $clientHandler,
]);
$httpClient = new Guzzle7Client($guzzleClient);
$httpBuilder = new Builder($httpClient);
$githubClient = new GithubClient($httpBuilder);
self::getContainer()->set('banditore.client.github.application', $githubClient);
self::getContainer()->get('oauth2.registry')->getClient('github')->getOAuth2Provider()->setHttpClient($guzzleClient);
self::getContainer()->get('session')->set(OAuth2Client::OAUTH2_SESSION_STATE_KEY, 'MyAwesomeState');
// before login
$user = self::getContainer()->get(UserRepository::class)->find(456);
$this->assertNull($user, 'User 456 does not YET exist');
$client->request('GET', '/callback?state=MyAwesomeState&code=MyAwesomeCode');
// after login
/** @var User */
$user = self::getContainer()->get(UserRepository::class)->find(456);
$this->assertSame('superboum', $user->getAccessToken());
$this->assertSame('http://avat.ar/down.png', $user->getAvatar());
$this->assertSame('getdown', $user->getUsername());
$this->assertSame('Any', $user->getName());
$this->assertSame(302, $client->getResponse()->getStatusCode());
/** @var RedirectResponse */
$response = $client->getResponse();
$this->assertSame('/dashboard', $response->getTargetUrl());
$message = self::getContainer()->get('session')->getFlashBag()->get('info');
$this->assertSame('Successfully logged in. Your starred repos will soon be synced!', $message[0]);
$transport = self::getContainer()->get('messenger.transport.sync_starred_repos');
$this->assertCount(1, $transport->get());
$messages = (array) $transport->get();
/** @var StarredReposSync */
$message = $messages[0]->getMessage();
$this->assertSame(456, $message->getUserId());
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/tests/Command/SyncStarredReposCommandTest.php | tests/Command/SyncStarredReposCommandTest.php | <?php
namespace App\Tests\Command;
use App\Command\SyncStarredReposCommand;
use App\Message\StarredReposSync;
use App\MessageHandler\StarredReposSyncHandler;
use App\Repository\UserRepository;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\Messenger\Bridge\Amqp\Transport\AmqpTransport;
use Symfony\Component\Messenger\Bridge\Amqp\Transport\Connection;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\MessageBusInterface;
class SyncStarredReposCommandTest extends KernelTestCase
{
public function testCommandSyncAllUsersWithoutQueue(): void
{
$message = new StarredReposSync(123);
$bus = $this->getMockBuilder(MessageBusInterface::class)
->disableOriginalConstructor()
->getMock();
$bus->expects($this->never())
->method('dispatch');
$syncRepo = $this->getMockBuilder(StarredReposSyncHandler::class)
->disableOriginalConstructor()
->getMock();
$syncRepo->expects($this->once())
->method('__invoke')
->with($message);
$command = new SyncStarredReposCommand(
self::getContainer()->get(UserRepository::class),
$syncRepo,
self::getContainer()->get('messenger.transport.sync_starred_repos'),
$bus
);
$output = new BufferedOutput();
$res = $command->__invoke($output, false, false, false);
$this->assertSame($res, 0);
$this->assertStringContainsString('Sync user 123 …', $output->fetch());
}
public function testCommandSyncAllUsersWithQueue(): void
{
$message = new StarredReposSync(123);
$bus = $this->getMockBuilder(MessageBusInterface::class)
->disableOriginalConstructor()
->getMock();
$bus->expects($this->once())
->method('dispatch')
->with($message)
->willReturn(new Envelope($message));
$syncRepo = $this->getMockBuilder(StarredReposSyncHandler::class)
->disableOriginalConstructor()
->getMock();
$syncRepo->expects($this->never())
->method('__invoke');
$command = new SyncStarredReposCommand(
self::getContainer()->get(UserRepository::class),
$syncRepo,
$this->getTransportMessageCount(0),
$bus
);
$output = new BufferedOutput();
$res = $command->__invoke($output, false, false, true);
$this->assertSame($res, 0);
$this->assertStringContainsString('Sync user 123 …', $output->fetch());
}
public function testCommandSyncAllUsersWithQueueFull(): void
{
$bus = $this->getMockBuilder(MessageBusInterface::class)
->disableOriginalConstructor()
->getMock();
$bus->expects($this->never())
->method('dispatch');
$syncRepo = $this->getMockBuilder(StarredReposSyncHandler::class)
->disableOriginalConstructor()
->getMock();
$syncRepo->expects($this->never())
->method('__invoke');
$command = new SyncStarredReposCommand(
self::getContainer()->get(UserRepository::class),
$syncRepo,
$this->getTransportMessageCount(10),
$bus
);
$output = new BufferedOutput();
$res = $command->__invoke($output, false, false, true);
$this->assertSame($res, 1);
$this->assertStringContainsString('Current queue as too much messages (10), skipping.', $output->fetch());
}
public function testCommandSyncOneUserById(): void
{
$message = new StarredReposSync(123);
$bus = $this->getMockBuilder(MessageBusInterface::class)
->disableOriginalConstructor()
->getMock();
$bus->expects($this->once())
->method('dispatch')
->with($message)
->willReturn(new Envelope($message));
$syncRepo = $this->getMockBuilder(StarredReposSyncHandler::class)
->disableOriginalConstructor()
->getMock();
$syncRepo->expects($this->never())
->method('__invoke');
$command = new SyncStarredReposCommand(
self::getContainer()->get(UserRepository::class),
$syncRepo,
$this->getTransportMessageCount(0),
$bus
);
$output = new BufferedOutput();
$res = $command->__invoke($output, '123', false, true);
$this->assertSame($res, 0);
$buffer = $output->fetch();
$this->assertStringContainsString('Sync user 123 …', $buffer);
$this->assertStringContainsString('User synced: 1', $buffer);
}
public function testCommandSyncOneUserByUsername(): void
{
$bus = $this->getMockBuilder(MessageBusInterface::class)
->disableOriginalConstructor()
->getMock();
$bus->expects($this->never())
->method('dispatch');
$syncRepo = $this->getMockBuilder(StarredReposSyncHandler::class)
->disableOriginalConstructor()
->getMock();
$syncRepo->expects($this->once())
->method('__invoke')
->with(new StarredReposSync(123));
$command = new SyncStarredReposCommand(
self::getContainer()->get(UserRepository::class),
$syncRepo,
self::getContainer()->get('messenger.transport.sync_starred_repos'),
$bus
);
$output = new BufferedOutput();
$res = $command->__invoke($output, false, 'admin', false);
$this->assertSame($res, 0);
$buffer = $output->fetch();
$this->assertStringContainsString('Sync user 123 …', $buffer);
$this->assertStringContainsString('User synced: 1', $buffer);
}
public function testCommandSyncOneUserNotFound(): void
{
$bus = $this->getMockBuilder(MessageBusInterface::class)
->disableOriginalConstructor()
->getMock();
$bus->expects($this->never())
->method('dispatch');
$syncRepo = $this->getMockBuilder(StarredReposSyncHandler::class)
->disableOriginalConstructor()
->getMock();
$syncRepo->expects($this->never())
->method('__invoke');
$command = new SyncStarredReposCommand(
self::getContainer()->get(UserRepository::class),
$syncRepo,
self::getContainer()->get('messenger.transport.sync_starred_repos'),
$bus
);
$output = new BufferedOutput();
$res = $command->__invoke($output, false, 'toto', false);
$this->assertSame($res, 1);
$this->assertStringContainsString('No users found', $output->fetch());
}
private function getTransportMessageCount(int $totalMessage = 0): AmqpTransport
{
$connection = $this->getMockBuilder(Connection::class)
->disableOriginalConstructor()
->getMock();
$connection->expects($this->once())
->method('countMessagesInQueues')
->willReturn($totalMessage);
return new AmqpTransport($connection);
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/tests/Command/SyncVersionsCommandTest.php | tests/Command/SyncVersionsCommandTest.php | <?php
namespace App\Tests\Command;
use App\Command\SyncVersionsCommand;
use App\Message\VersionsSync;
use App\MessageHandler\VersionsSyncHandler;
use App\Repository\RepoRepository;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\Messenger\Bridge\Amqp\Transport\AmqpTransport;
use Symfony\Component\Messenger\Bridge\Amqp\Transport\Connection;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\MessageBusInterface;
class SyncVersionsCommandTest extends KernelTestCase
{
public function testCommandSyncAllUsersWithoutQueue(): void
{
$bus = $this->getMockBuilder(MessageBusInterface::class)
->disableOriginalConstructor()
->getMock();
$bus->expects($this->never())
->method('dispatch');
$syncVersion = $this->getMockBuilder(VersionsSyncHandler::class)
->disableOriginalConstructor()
->getMock();
$syncVersion->expects($this->any())
->method('__invoke');
$command = new SyncVersionsCommand(
self::getContainer()->get(RepoRepository::class),
$syncVersion,
self::getContainer()->get('messenger.transport.sync_versions'),
$bus
);
$output = new BufferedOutput();
$res = $command->__invoke($output, false, false, false);
$this->assertSame($res, 0);
$this->assertStringContainsString('Check 555 …', $output->fetch());
}
public function testCommandSyncAllUsersWithQueue(): void
{
$bus = $this->getMockBuilder(MessageBusInterface::class)
->disableOriginalConstructor()
->getMock();
$bus->expects($this->any())
->method('dispatch')
->willReturn(new Envelope(new VersionsSync(555)));
$syncVersion = $this->getMockBuilder(VersionsSyncHandler::class)
->disableOriginalConstructor()
->getMock();
$syncVersion->expects($this->any())
->method('__invoke');
$command = new SyncVersionsCommand(
self::getContainer()->get(RepoRepository::class),
$syncVersion,
$this->getTransportMessageCount(0),
$bus
);
$output = new BufferedOutput();
$res = $command->__invoke($output, false, false, true);
$this->assertSame($res, 0);
$this->assertStringContainsString('Check 555 …', $output->fetch());
}
public function testCommandSyncAllUsersWithQueueFull(): void
{
$bus = $this->getMockBuilder(MessageBusInterface::class)
->disableOriginalConstructor()
->getMock();
$bus->expects($this->never())
->method('dispatch');
$syncVersion = $this->getMockBuilder(VersionsSyncHandler::class)
->disableOriginalConstructor()
->getMock();
$syncVersion->expects($this->never())
->method('__invoke');
$command = new SyncVersionsCommand(
self::getContainer()->get(RepoRepository::class),
$syncVersion,
$this->getTransportMessageCount(10),
$bus
);
$output = new BufferedOutput();
$res = $command->__invoke($output, false, false, true);
$this->assertSame($res, 1);
$this->assertStringContainsString('Current queue as too much messages (10), skipping.', $output->fetch());
}
public function testCommandSyncOneUserById(): void
{
$message = new VersionsSync(555);
$bus = $this->getMockBuilder(MessageBusInterface::class)
->disableOriginalConstructor()
->getMock();
$bus->expects($this->once())
->method('dispatch')
->with($message)
->willReturn(new Envelope($message));
$syncVersion = $this->getMockBuilder(VersionsSyncHandler::class)
->disableOriginalConstructor()
->getMock();
$syncVersion->expects($this->never())
->method('__invoke');
$command = new SyncVersionsCommand(
self::getContainer()->get(RepoRepository::class),
$syncVersion,
$this->getTransportMessageCount(0),
$bus
);
$output = new BufferedOutput();
$res = $command->__invoke($output, '555', false, true);
$this->assertSame($res, 0);
$buffer = $output->fetch();
$this->assertStringContainsString('Check 555 …', $buffer);
$this->assertStringContainsString('Repo checked: 1', $buffer);
}
public function testCommandSyncOneUserByUsername(): void
{
$message = new VersionsSync(666);
$bus = $this->getMockBuilder(MessageBusInterface::class)
->disableOriginalConstructor()
->getMock();
$bus->expects($this->never())
->method('dispatch');
$syncVersion = $this->getMockBuilder(VersionsSyncHandler::class)
->disableOriginalConstructor()
->getMock();
$syncVersion->expects($this->once())
->method('__invoke')
->with($message);
$command = new SyncVersionsCommand(
self::getContainer()->get(RepoRepository::class),
$syncVersion,
self::getContainer()->get('messenger.transport.sync_versions'),
$bus
);
$output = new BufferedOutput();
$res = $command->__invoke($output, false, 'test/test', false);
$this->assertSame($res, 0);
$buffer = $output->fetch();
$this->assertStringContainsString('Check 666 …', $buffer);
$this->assertStringContainsString('Repo checked: 1', $buffer);
}
public function testCommandSyncOneUserNotFound(): void
{
$bus = $this->getMockBuilder(MessageBusInterface::class)
->disableOriginalConstructor()
->getMock();
$bus->expects($this->never())
->method('dispatch');
$syncVersion = $this->getMockBuilder(VersionsSyncHandler::class)
->disableOriginalConstructor()
->getMock();
$syncVersion->expects($this->never())
->method('__invoke');
$command = new SyncVersionsCommand(
self::getContainer()->get(RepoRepository::class),
$syncVersion,
self::getContainer()->get('messenger.transport.sync_versions'),
$bus
);
$output = new BufferedOutput();
$res = $command->__invoke($output, false, 'toto', false);
$this->assertSame($res, 1);
$this->assertStringContainsString('No repos found', $output->fetch());
}
private function getTransportMessageCount(int $totalMessage = 0): AmqpTransport
{
$connection = $this->getMockBuilder(Connection::class)
->disableOriginalConstructor()
->getMock();
$connection->expects($this->once())
->method('countMessagesInQueues')
->willReturn($totalMessage);
return new AmqpTransport($connection);
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/public/index.php | public/index.php | <?php
use App\Kernel;
require_once dirname(__DIR__) . '/vendor/autoload_runtime.php';
return fn (array $context) => new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/migrations/Version20170222055642.php | migrations/Version20170222055642.php | <?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Add homepage & language to the repo entity.
*/
final class Version20170222055642 extends AbstractMigration
{
public function getDescription(): string
{
return 'Add homepage & language to the repo entity.';
}
public function up(Schema $schema): void
{
$this->abortIf('mysql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'mysql\'.');
$repoTable = $schema->getTable('repo');
$this->skipIf($repoTable->hasColumn('homepage') || $repoTable->hasColumn('language'), 'It seems that you already played this migration.');
$this->addSql('ALTER TABLE repo ADD homepage VARCHAR(255) DEFAULT NULL, ADD language VARCHAR(255) DEFAULT NULL');
}
public function down(Schema $schema): void
{
$this->abortIf('mysql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE repo DROP homepage, DROP language');
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/migrations/Version20200511062812.php | migrations/Version20200511062812.php | <?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Mark a user as removed to avoid checking for new starred repos in the future.
*/
final class Version20200511062812 extends AbstractMigration
{
public function getDescription(): string
{
return 'Mark a user as removed to avoid checking for new starred repos in the future.';
}
public function up(Schema $schema): void
{
$this->abortIf('mysql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE user ADD removed_at DATETIME DEFAULT NULL');
}
public function down(Schema $schema): void
{
$this->abortIf('mysql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE user DROP removed_at');
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/migrations/Version20180827105910.php | migrations/Version20180827105910.php | <?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Mark a repo as removed to avoid checking for new version in the future.
*/
final class Version20180827105910 extends AbstractMigration
{
public function getDescription(): string
{
return 'Mark a repo as removed to avoid checking for new version in the future.';
}
public function up(Schema $schema): void
{
$this->abortIf('mysql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE repo ADD removed_at DATETIME DEFAULT NULL');
}
public function down(Schema $schema): void
{
$this->abortIf('mysql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE repo DROP removed_at');
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/migrations/Version20200613153754.php | migrations/Version20200613153754.php | <?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Enforce some relations to not be null.
*/
final class Version20200613153754 extends AbstractMigration
{
public function getDescription(): string
{
return 'Enforce some relations to not be null';
}
public function up(Schema $schema): void
{
$this->abortIf('mysql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE star CHANGE user_id user_id INT NOT NULL, CHANGE repo_id repo_id INT NOT NULL');
$this->addSql('ALTER TABLE version CHANGE repo_id repo_id INT NOT NULL');
}
public function down(Schema $schema): void
{
$this->abortIf('mysql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE star CHANGE user_id user_id INT DEFAULT NULL, CHANGE repo_id repo_id INT DEFAULT NULL');
$this->addSql('ALTER TABLE version CHANGE repo_id repo_id INT DEFAULT NULL');
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/migrations/Version20170329095349.php | migrations/Version20170329095349.php | <?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* GitHub name can be null.
*/
final class Version20170329095349 extends AbstractMigration
{
public function getDescription(): string
{
return 'GitHub name can be null.';
}
public function up(Schema $schema): void
{
$this->abortIf('mysql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE user CHANGE name name VARCHAR(191) DEFAULT NULL');
}
public function down(Schema $schema): void
{
$this->abortIf('mysql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE user CHANGE name name VARCHAR(191) NOT NULL COLLATE utf8mb4_unicode_ci');
}
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/config/preload.php | config/preload.php | <?php
if (file_exists(dirname(__DIR__) . '/var/cache/prod/App_KernelProdContainer.preload.php')) {
require dirname(__DIR__) . '/var/cache/prod/App_KernelProdContainer.preload.php';
}
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/config/reference.php | config/reference.php | <?php
// This file is auto-generated and is for apps only. Bundles SHOULD NOT rely on its content.
namespace Symfony\Component\DependencyInjection\Loader\Configurator;
/**
* This class provides array-shapes for configuring the services and bundles of an application.
*
* Services declared with the config() method below are autowired and autoconfigured by default.
*
* This is for apps only. Bundles SHOULD NOT use it.
*
* Example:
*
* ```php
* // config/services.php
* namespace Symfony\Component\DependencyInjection\Loader\Configurator;
*
* return App::config([
* 'services' => [
* 'App\\' => [
* 'resource' => '../src/',
* ],
* ],
* ]);
* ```
*
* @psalm-type ImportsConfig = list<string|array{
* resource: string,
* type?: string|null,
* ignore_errors?: bool,
* }>
* @psalm-type ParametersConfig = array<string, scalar|\UnitEnum|array<scalar|\UnitEnum|array<mixed>|null>|null>
* @psalm-type ArgumentsType = list<mixed>|array<string, mixed>
* @psalm-type CallType = array<string, ArgumentsType>|array{0:string, 1?:ArgumentsType, 2?:bool}|array{method:string, arguments?:ArgumentsType, returns_clone?:bool}
* @psalm-type TagsType = list<string|array<string, array<string, mixed>>> // arrays inside the list must have only one element, with the tag name as the key
* @psalm-type CallbackType = string|array{0:string|ReferenceConfigurator,1:string}|\Closure|ReferenceConfigurator|ExpressionConfigurator
* @psalm-type DeprecationType = array{package: string, version: string, message?: string}
* @psalm-type DefaultsType = array{
* public?: bool,
* tags?: TagsType,
* resource_tags?: TagsType,
* autowire?: bool,
* autoconfigure?: bool,
* bind?: array<string, mixed>,
* }
* @psalm-type InstanceofType = array{
* shared?: bool,
* lazy?: bool|string,
* public?: bool,
* properties?: array<string, mixed>,
* configurator?: CallbackType,
* calls?: list<CallType>,
* tags?: TagsType,
* resource_tags?: TagsType,
* autowire?: bool,
* bind?: array<string, mixed>,
* constructor?: string,
* }
* @psalm-type DefinitionType = array{
* class?: string,
* file?: string,
* parent?: string,
* shared?: bool,
* synthetic?: bool,
* lazy?: bool|string,
* public?: bool,
* abstract?: bool,
* deprecated?: DeprecationType,
* factory?: CallbackType,
* configurator?: CallbackType,
* arguments?: ArgumentsType,
* properties?: array<string, mixed>,
* calls?: list<CallType>,
* tags?: TagsType,
* resource_tags?: TagsType,
* decorates?: string,
* decoration_inner_name?: string,
* decoration_priority?: int,
* decoration_on_invalid?: 'exception'|'ignore'|null,
* autowire?: bool,
* autoconfigure?: bool,
* bind?: array<string, mixed>,
* constructor?: string,
* from_callable?: CallbackType,
* }
* @psalm-type AliasType = string|array{
* alias: string,
* public?: bool,
* deprecated?: DeprecationType,
* }
* @psalm-type PrototypeType = array{
* resource: string,
* namespace?: string,
* exclude?: string|list<string>,
* parent?: string,
* shared?: bool,
* lazy?: bool|string,
* public?: bool,
* abstract?: bool,
* deprecated?: DeprecationType,
* factory?: CallbackType,
* arguments?: ArgumentsType,
* properties?: array<string, mixed>,
* configurator?: CallbackType,
* calls?: list<CallType>,
* tags?: TagsType,
* resource_tags?: TagsType,
* autowire?: bool,
* autoconfigure?: bool,
* bind?: array<string, mixed>,
* constructor?: string,
* }
* @psalm-type StackType = array{
* stack: list<DefinitionType|AliasType|PrototypeType|array<class-string, ArgumentsType|null>>,
* public?: bool,
* deprecated?: DeprecationType,
* }
* @psalm-type ServicesConfig = array{
* _defaults?: DefaultsType,
* _instanceof?: InstanceofType,
* ...<string, DefinitionType|AliasType|PrototypeType|StackType|ArgumentsType|null>
* }
* @psalm-type ExtensionType = array<string, mixed>
* @psalm-type FrameworkConfig = array{
* secret?: scalar|null,
* http_method_override?: bool, // Set true to enable support for the '_method' request parameter to determine the intended HTTP method on POST requests. // Default: false
* allowed_http_method_override?: list<string>|null,
* trust_x_sendfile_type_header?: scalar|null, // Set true to enable support for xsendfile in binary file responses. // Default: "%env(bool:default::SYMFONY_TRUST_X_SENDFILE_TYPE_HEADER)%"
* ide?: scalar|null, // Default: "%env(default::SYMFONY_IDE)%"
* test?: bool,
* default_locale?: scalar|null, // Default: "en"
* set_locale_from_accept_language?: bool, // Whether to use the Accept-Language HTTP header to set the Request locale (only when the "_locale" request attribute is not passed). // Default: false
* set_content_language_from_locale?: bool, // Whether to set the Content-Language HTTP header on the Response using the Request locale. // Default: false
* enabled_locales?: list<scalar|null>,
* trusted_hosts?: list<scalar|null>,
* trusted_proxies?: mixed, // Default: ["%env(default::SYMFONY_TRUSTED_PROXIES)%"]
* trusted_headers?: list<scalar|null>,
* error_controller?: scalar|null, // Default: "error_controller"
* handle_all_throwables?: bool, // HttpKernel will handle all kinds of \Throwable. // Default: true
* csrf_protection?: bool|array{
* enabled?: scalar|null, // Default: null
* stateless_token_ids?: list<scalar|null>,
* check_header?: scalar|null, // Whether to check the CSRF token in a header in addition to a cookie when using stateless protection. // Default: false
* cookie_name?: scalar|null, // The name of the cookie to use when using stateless protection. // Default: "csrf-token"
* },
* form?: bool|array{ // Form configuration
* enabled?: bool, // Default: true
* csrf_protection?: array{
* enabled?: scalar|null, // Default: null
* token_id?: scalar|null, // Default: null
* field_name?: scalar|null, // Default: "_token"
* field_attr?: array<string, scalar|null>,
* },
* },
* http_cache?: bool|array{ // HTTP cache configuration
* enabled?: bool, // Default: false
* debug?: bool, // Default: "%kernel.debug%"
* trace_level?: "none"|"short"|"full",
* trace_header?: scalar|null,
* default_ttl?: int,
* private_headers?: list<scalar|null>,
* skip_response_headers?: list<scalar|null>,
* allow_reload?: bool,
* allow_revalidate?: bool,
* stale_while_revalidate?: int,
* stale_if_error?: int,
* terminate_on_cache_hit?: bool,
* },
* esi?: bool|array{ // ESI configuration
* enabled?: bool, // Default: false
* },
* ssi?: bool|array{ // SSI configuration
* enabled?: bool, // Default: false
* },
* fragments?: bool|array{ // Fragments configuration
* enabled?: bool, // Default: false
* hinclude_default_template?: scalar|null, // Default: null
* path?: scalar|null, // Default: "/_fragment"
* },
* profiler?: bool|array{ // Profiler configuration
* enabled?: bool, // Default: false
* collect?: bool, // Default: true
* collect_parameter?: scalar|null, // The name of the parameter to use to enable or disable collection on a per request basis. // Default: null
* only_exceptions?: bool, // Default: false
* only_main_requests?: bool, // Default: false
* dsn?: scalar|null, // Default: "file:%kernel.cache_dir%/profiler"
* collect_serializer_data?: bool, // Enables the serializer data collector and profiler panel. // Default: false
* },
* workflows?: bool|array{
* enabled?: bool, // Default: false
* workflows?: array<string, array{ // Default: []
* audit_trail?: bool|array{
* enabled?: bool, // Default: false
* },
* type?: "workflow"|"state_machine", // Default: "state_machine"
* marking_store?: array{
* type?: "method",
* property?: scalar|null,
* service?: scalar|null,
* },
* supports?: list<scalar|null>,
* definition_validators?: list<scalar|null>,
* support_strategy?: scalar|null,
* initial_marking?: list<scalar|null>,
* events_to_dispatch?: list<string>|null,
* places?: list<array{ // Default: []
* name: scalar|null,
* metadata?: list<mixed>,
* }>,
* transitions: list<array{ // Default: []
* name: string,
* guard?: string, // An expression to block the transition.
* from?: list<array{ // Default: []
* place: string,
* weight?: int, // Default: 1
* }>,
* to?: list<array{ // Default: []
* place: string,
* weight?: int, // Default: 1
* }>,
* weight?: int, // Default: 1
* metadata?: list<mixed>,
* }>,
* metadata?: list<mixed>,
* }>,
* },
* router?: bool|array{ // Router configuration
* enabled?: bool, // Default: false
* resource: scalar|null,
* type?: scalar|null,
* cache_dir?: scalar|null, // Deprecated: Setting the "framework.router.cache_dir.cache_dir" configuration option is deprecated. It will be removed in version 8.0. // Default: "%kernel.build_dir%"
* default_uri?: scalar|null, // The default URI used to generate URLs in a non-HTTP context. // Default: null
* http_port?: scalar|null, // Default: 80
* https_port?: scalar|null, // Default: 443
* strict_requirements?: scalar|null, // set to true to throw an exception when a parameter does not match the requirements set to false to disable exceptions when a parameter does not match the requirements (and return null instead) set to null to disable parameter checks against requirements 'true' is the preferred configuration in development mode, while 'false' or 'null' might be preferred in production // Default: true
* utf8?: bool, // Default: true
* },
* session?: bool|array{ // Session configuration
* enabled?: bool, // Default: false
* storage_factory_id?: scalar|null, // Default: "session.storage.factory.native"
* handler_id?: scalar|null, // Defaults to using the native session handler, or to the native *file* session handler if "save_path" is not null.
* name?: scalar|null,
* cookie_lifetime?: scalar|null,
* cookie_path?: scalar|null,
* cookie_domain?: scalar|null,
* cookie_secure?: true|false|"auto", // Default: "auto"
* cookie_httponly?: bool, // Default: true
* cookie_samesite?: null|"lax"|"strict"|"none", // Default: "lax"
* use_cookies?: bool,
* gc_divisor?: scalar|null,
* gc_probability?: scalar|null,
* gc_maxlifetime?: scalar|null,
* save_path?: scalar|null, // Defaults to "%kernel.cache_dir%/sessions" if the "handler_id" option is not null.
* metadata_update_threshold?: int, // Seconds to wait between 2 session metadata updates. // Default: 0
* sid_length?: int, // Deprecated: Setting the "framework.session.sid_length.sid_length" configuration option is deprecated. It will be removed in version 8.0. No alternative is provided as PHP 8.4 has deprecated the related option.
* sid_bits_per_character?: int, // Deprecated: Setting the "framework.session.sid_bits_per_character.sid_bits_per_character" configuration option is deprecated. It will be removed in version 8.0. No alternative is provided as PHP 8.4 has deprecated the related option.
* },
* request?: bool|array{ // Request configuration
* enabled?: bool, // Default: false
* formats?: array<string, string|list<scalar|null>>,
* },
* assets?: bool|array{ // Assets configuration
* enabled?: bool, // Default: true
* strict_mode?: bool, // Throw an exception if an entry is missing from the manifest.json. // Default: false
* version_strategy?: scalar|null, // Default: null
* version?: scalar|null, // Default: null
* version_format?: scalar|null, // Default: "%%s?%%s"
* json_manifest_path?: scalar|null, // Default: null
* base_path?: scalar|null, // Default: ""
* base_urls?: list<scalar|null>,
* packages?: array<string, array{ // Default: []
* strict_mode?: bool, // Throw an exception if an entry is missing from the manifest.json. // Default: false
* version_strategy?: scalar|null, // Default: null
* version?: scalar|null,
* version_format?: scalar|null, // Default: null
* json_manifest_path?: scalar|null, // Default: null
* base_path?: scalar|null, // Default: ""
* base_urls?: list<scalar|null>,
* }>,
* },
* asset_mapper?: bool|array{ // Asset Mapper configuration
* enabled?: bool, // Default: false
* paths?: array<string, scalar|null>,
* excluded_patterns?: list<scalar|null>,
* exclude_dotfiles?: bool, // If true, any files starting with "." will be excluded from the asset mapper. // Default: true
* server?: bool, // If true, a "dev server" will return the assets from the public directory (true in "debug" mode only by default). // Default: true
* public_prefix?: scalar|null, // The public path where the assets will be written to (and served from when "server" is true). // Default: "/assets/"
* missing_import_mode?: "strict"|"warn"|"ignore", // Behavior if an asset cannot be found when imported from JavaScript or CSS files - e.g. "import './non-existent.js'". "strict" means an exception is thrown, "warn" means a warning is logged, "ignore" means the import is left as-is. // Default: "warn"
* extensions?: array<string, scalar|null>,
* importmap_path?: scalar|null, // The path of the importmap.php file. // Default: "%kernel.project_dir%/importmap.php"
* importmap_polyfill?: scalar|null, // The importmap name that will be used to load the polyfill. Set to false to disable. // Default: "es-module-shims"
* importmap_script_attributes?: array<string, scalar|null>,
* vendor_dir?: scalar|null, // The directory to store JavaScript vendors. // Default: "%kernel.project_dir%/assets/vendor"
* precompress?: bool|array{ // Precompress assets with Brotli, Zstandard and gzip.
* enabled?: bool, // Default: false
* formats?: list<scalar|null>,
* extensions?: list<scalar|null>,
* },
* },
* translator?: bool|array{ // Translator configuration
* enabled?: bool, // Default: true
* fallbacks?: list<scalar|null>,
* logging?: bool, // Default: false
* formatter?: scalar|null, // Default: "translator.formatter.default"
* cache_dir?: scalar|null, // Default: "%kernel.cache_dir%/translations"
* default_path?: scalar|null, // The default path used to load translations. // Default: "%kernel.project_dir%/translations"
* paths?: list<scalar|null>,
* pseudo_localization?: bool|array{
* enabled?: bool, // Default: false
* accents?: bool, // Default: true
* expansion_factor?: float, // Default: 1.0
* brackets?: bool, // Default: true
* parse_html?: bool, // Default: false
* localizable_html_attributes?: list<scalar|null>,
* },
* providers?: array<string, array{ // Default: []
* dsn?: scalar|null,
* domains?: list<scalar|null>,
* locales?: list<scalar|null>,
* }>,
* globals?: array<string, string|array{ // Default: []
* value?: mixed,
* message?: string,
* parameters?: array<string, scalar|null>,
* domain?: string,
* }>,
* },
* validation?: bool|array{ // Validation configuration
* enabled?: bool, // Default: true
* cache?: scalar|null, // Deprecated: Setting the "framework.validation.cache.cache" configuration option is deprecated. It will be removed in version 8.0.
* enable_attributes?: bool, // Default: true
* static_method?: list<scalar|null>,
* translation_domain?: scalar|null, // Default: "validators"
* email_validation_mode?: "html5"|"html5-allow-no-tld"|"strict"|"loose", // Default: "html5"
* mapping?: array{
* paths?: list<scalar|null>,
* },
* not_compromised_password?: bool|array{
* enabled?: bool, // When disabled, compromised passwords will be accepted as valid. // Default: true
* endpoint?: scalar|null, // API endpoint for the NotCompromisedPassword Validator. // Default: null
* },
* disable_translation?: bool, // Default: false
* auto_mapping?: array<string, array{ // Default: []
* services?: list<scalar|null>,
* }>,
* },
* annotations?: bool|array{
* enabled?: bool, // Default: false
* },
* serializer?: bool|array{ // Serializer configuration
* enabled?: bool, // Default: false
* enable_attributes?: bool, // Default: true
* name_converter?: scalar|null,
* circular_reference_handler?: scalar|null,
* max_depth_handler?: scalar|null,
* mapping?: array{
* paths?: list<scalar|null>,
* },
* default_context?: list<mixed>,
* named_serializers?: array<string, array{ // Default: []
* name_converter?: scalar|null,
* default_context?: list<mixed>,
* include_built_in_normalizers?: bool, // Whether to include the built-in normalizers // Default: true
* include_built_in_encoders?: bool, // Whether to include the built-in encoders // Default: true
* }>,
* },
* property_access?: bool|array{ // Property access configuration
* enabled?: bool, // Default: true
* magic_call?: bool, // Default: false
* magic_get?: bool, // Default: true
* magic_set?: bool, // Default: true
* throw_exception_on_invalid_index?: bool, // Default: false
* throw_exception_on_invalid_property_path?: bool, // Default: true
* },
* type_info?: bool|array{ // Type info configuration
* enabled?: bool, // Default: true
* aliases?: array<string, scalar|null>,
* },
* property_info?: bool|array{ // Property info configuration
* enabled?: bool, // Default: true
* with_constructor_extractor?: bool, // Registers the constructor extractor.
* },
* cache?: array{ // Cache configuration
* prefix_seed?: scalar|null, // Used to namespace cache keys when using several apps with the same shared backend. // Default: "_%kernel.project_dir%.%kernel.container_class%"
* app?: scalar|null, // App related cache pools configuration. // Default: "cache.adapter.filesystem"
* system?: scalar|null, // System related cache pools configuration. // Default: "cache.adapter.system"
* directory?: scalar|null, // Default: "%kernel.share_dir%/pools/app"
* default_psr6_provider?: scalar|null,
* default_redis_provider?: scalar|null, // Default: "redis://localhost"
* default_valkey_provider?: scalar|null, // Default: "valkey://localhost"
* default_memcached_provider?: scalar|null, // Default: "memcached://localhost"
* default_doctrine_dbal_provider?: scalar|null, // Default: "database_connection"
* default_pdo_provider?: scalar|null, // Default: null
* pools?: array<string, array{ // Default: []
* adapters?: list<scalar|null>,
* tags?: scalar|null, // Default: null
* public?: bool, // Default: false
* default_lifetime?: scalar|null, // Default lifetime of the pool.
* provider?: scalar|null, // Overwrite the setting from the default provider for this adapter.
* early_expiration_message_bus?: scalar|null,
* clearer?: scalar|null,
* }>,
* },
* php_errors?: array{ // PHP errors handling configuration
* log?: mixed, // Use the application logger instead of the PHP logger for logging PHP errors. // Default: true
* throw?: bool, // Throw PHP errors as \ErrorException instances. // Default: true
* },
* exceptions?: array<string, array{ // Default: []
* log_level?: scalar|null, // The level of log message. Null to let Symfony decide. // Default: null
* status_code?: scalar|null, // The status code of the response. Null or 0 to let Symfony decide. // Default: null
* log_channel?: scalar|null, // The channel of log message. Null to let Symfony decide. // Default: null
* }>,
* web_link?: bool|array{ // Web links configuration
* enabled?: bool, // Default: false
* },
* lock?: bool|string|array{ // Lock configuration
* enabled?: bool, // Default: false
* resources?: array<string, string|list<scalar|null>>,
* },
* semaphore?: bool|string|array{ // Semaphore configuration
* enabled?: bool, // Default: false
* resources?: array<string, scalar|null>,
* },
* messenger?: bool|array{ // Messenger configuration
* enabled?: bool, // Default: true
* routing?: array<string, array{ // Default: []
* senders?: list<scalar|null>,
* }>,
* serializer?: array{
* default_serializer?: scalar|null, // Service id to use as the default serializer for the transports. // Default: "messenger.transport.native_php_serializer"
* symfony_serializer?: array{
* format?: scalar|null, // Serialization format for the messenger.transport.symfony_serializer service (which is not the serializer used by default). // Default: "json"
* context?: array<string, mixed>,
* },
* },
* transports?: array<string, string|array{ // Default: []
* dsn?: scalar|null,
* serializer?: scalar|null, // Service id of a custom serializer to use. // Default: null
* options?: list<mixed>,
* failure_transport?: scalar|null, // Transport name to send failed messages to (after all retries have failed). // Default: null
* retry_strategy?: string|array{
* service?: scalar|null, // Service id to override the retry strategy entirely. // Default: null
* max_retries?: int, // Default: 3
* delay?: int, // Time in ms to delay (or the initial value when multiplier is used). // Default: 1000
* multiplier?: float, // If greater than 1, delay will grow exponentially for each retry: this delay = (delay * (multiple ^ retries)). // Default: 2
* max_delay?: int, // Max time in ms that a retry should ever be delayed (0 = infinite). // Default: 0
* jitter?: float, // Randomness to apply to the delay (between 0 and 1). // Default: 0.1
* },
* rate_limiter?: scalar|null, // Rate limiter name to use when processing messages. // Default: null
* }>,
* failure_transport?: scalar|null, // Transport name to send failed messages to (after all retries have failed). // Default: null
* stop_worker_on_signals?: list<scalar|null>,
* default_bus?: scalar|null, // Default: null
* buses?: array<string, array{ // Default: {"messenger.bus.default":{"default_middleware":{"enabled":true,"allow_no_handlers":false,"allow_no_senders":true},"middleware":[]}}
* default_middleware?: bool|string|array{
* enabled?: bool, // Default: true
* allow_no_handlers?: bool, // Default: false
* allow_no_senders?: bool, // Default: true
* },
* middleware?: list<string|array{ // Default: []
* id: scalar|null,
* arguments?: list<mixed>,
* }>,
* }>,
* },
* scheduler?: bool|array{ // Scheduler configuration
* enabled?: bool, // Default: false
* },
* disallow_search_engine_index?: bool, // Enabled by default when debug is enabled. // Default: true
* http_client?: bool|array{ // HTTP Client configuration
* enabled?: bool, // Default: false
* max_host_connections?: int, // The maximum number of connections to a single host.
* default_options?: array{
* headers?: array<string, mixed>,
* vars?: array<string, mixed>,
* max_redirects?: int, // The maximum number of redirects to follow.
* http_version?: scalar|null, // The default HTTP version, typically 1.1 or 2.0, leave to null for the best version.
* resolve?: array<string, scalar|null>,
* proxy?: scalar|null, // The URL of the proxy to pass requests through or null for automatic detection.
* no_proxy?: scalar|null, // A comma separated list of hosts that do not require a proxy to be reached.
* timeout?: float, // The idle timeout, defaults to the "default_socket_timeout" ini parameter.
* max_duration?: float, // The maximum execution time for the request+response as a whole.
* bindto?: scalar|null, // A network interface name, IP address, a host name or a UNIX socket to bind to.
* verify_peer?: bool, // Indicates if the peer should be verified in a TLS context.
* verify_host?: bool, // Indicates if the host should exist as a certificate common name.
* cafile?: scalar|null, // A certificate authority file.
* capath?: scalar|null, // A directory that contains multiple certificate authority files.
* local_cert?: scalar|null, // A PEM formatted certificate file.
* local_pk?: scalar|null, // A private key file.
* passphrase?: scalar|null, // The passphrase used to encrypt the "local_pk" file.
* ciphers?: scalar|null, // A list of TLS ciphers separated by colons, commas or spaces (e.g. "RC3-SHA:TLS13-AES-128-GCM-SHA256"...)
* peer_fingerprint?: array{ // Associative array: hashing algorithm => hash(es).
* sha1?: mixed,
* pin-sha256?: mixed,
* md5?: mixed,
* },
* crypto_method?: scalar|null, // The minimum version of TLS to accept; must be one of STREAM_CRYPTO_METHOD_TLSv*_CLIENT constants.
* extra?: array<string, mixed>,
* rate_limiter?: scalar|null, // Rate limiter name to use for throttling requests. // Default: null
* caching?: bool|array{ // Caching configuration.
* enabled?: bool, // Default: false
* cache_pool?: string, // The taggable cache pool to use for storing the responses. // Default: "cache.http_client"
* shared?: bool, // Indicates whether the cache is shared (public) or private. // Default: true
* max_ttl?: int, // The maximum TTL (in seconds) allowed for cached responses. Null means no cap. // Default: null
* },
* retry_failed?: bool|array{
* enabled?: bool, // Default: false
* retry_strategy?: scalar|null, // service id to override the retry strategy. // Default: null
* http_codes?: array<string, array{ // Default: []
* code?: int,
* methods?: list<string>,
* }>,
* max_retries?: int, // Default: 3
* delay?: int, // Time in ms to delay (or the initial value when multiplier is used). // Default: 1000
* multiplier?: float, // If greater than 1, delay will grow exponentially for each retry: delay * (multiple ^ retries). // Default: 2
* max_delay?: int, // Max time in ms that a retry should ever be delayed (0 = infinite). // Default: 0
* jitter?: float, // Randomness in percent (between 0 and 1) to apply to the delay. // Default: 0.1
* },
* },
* mock_response_factory?: scalar|null, // The id of the service that should generate mock responses. It should be either an invokable or an iterable.
* scoped_clients?: array<string, string|array{ // Default: []
* scope?: scalar|null, // The regular expression that the request URL must match before adding the other options. When none is provided, the base URI is used instead.
* base_uri?: scalar|null, // The URI to resolve relative URLs, following rules in RFC 3985, section 2.
* auth_basic?: scalar|null, // An HTTP Basic authentication "username:password".
* auth_bearer?: scalar|null, // A token enabling HTTP Bearer authorization.
* auth_ntlm?: scalar|null, // A "username:password" pair to use Microsoft NTLM authentication (requires the cURL extension).
* query?: array<string, scalar|null>,
* headers?: array<string, mixed>,
* max_redirects?: int, // The maximum number of redirects to follow.
* http_version?: scalar|null, // The default HTTP version, typically 1.1 or 2.0, leave to null for the best version.
* resolve?: array<string, scalar|null>,
* proxy?: scalar|null, // The URL of the proxy to pass requests through or null for automatic detection.
* no_proxy?: scalar|null, // A comma separated list of hosts that do not require a proxy to be reached.
* timeout?: float, // The idle timeout, defaults to the "default_socket_timeout" ini parameter.
* max_duration?: float, // The maximum execution time for the request+response as a whole.
* bindto?: scalar|null, // A network interface name, IP address, a host name or a UNIX socket to bind to.
* verify_peer?: bool, // Indicates if the peer should be verified in a TLS context.
* verify_host?: bool, // Indicates if the host should exist as a certificate common name.
* cafile?: scalar|null, // A certificate authority file.
* capath?: scalar|null, // A directory that contains multiple certificate authority files.
* local_cert?: scalar|null, // A PEM formatted certificate file.
* local_pk?: scalar|null, // A private key file.
* passphrase?: scalar|null, // The passphrase used to encrypt the "local_pk" file.
* ciphers?: scalar|null, // A list of TLS ciphers separated by colons, commas or spaces (e.g. "RC3-SHA:TLS13-AES-128-GCM-SHA256"...).
* peer_fingerprint?: array{ // Associative array: hashing algorithm => hash(es).
* sha1?: mixed,
* pin-sha256?: mixed,
* md5?: mixed,
* },
* crypto_method?: scalar|null, // The minimum version of TLS to accept; must be one of STREAM_CRYPTO_METHOD_TLSv*_CLIENT constants.
* extra?: array<string, mixed>,
* rate_limiter?: scalar|null, // Rate limiter name to use for throttling requests. // Default: null
* caching?: bool|array{ // Caching configuration.
* enabled?: bool, // Default: false
* cache_pool?: string, // The taggable cache pool to use for storing the responses. // Default: "cache.http_client"
* shared?: bool, // Indicates whether the cache is shared (public) or private. // Default: true
* max_ttl?: int, // The maximum TTL (in seconds) allowed for cached responses. Null means no cap. // Default: null
* },
* retry_failed?: bool|array{
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | true |
j0k3r/banditore | https://github.com/j0k3r/banditore/blob/8b3f266d748406c74b6971f95ad9a62003365e8a/config/bundles.php | config/bundles.php | <?php
use Doctrine\Bundle\DoctrineBundle\DoctrineBundle;
use Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle;
use Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle;
use Knp\Bundle\TimeBundle\KnpTimeBundle;
use KnpU\OAuth2ClientBundle\KnpUOAuth2ClientBundle;
use Sentry\SentryBundle\SentryBundle;
use Snc\RedisBundle\SncRedisBundle;
use Symfony\Bundle\DebugBundle\DebugBundle;
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Bundle\MonologBundle\MonologBundle;
use Symfony\Bundle\SecurityBundle\SecurityBundle;
use Symfony\Bundle\TwigBundle\TwigBundle;
use Symfony\Bundle\WebProfilerBundle\WebProfilerBundle;
use Twig\Extra\TwigExtraBundle\TwigExtraBundle;
return [
FrameworkBundle::class => ['all' => true],
DoctrineBundle::class => ['all' => true],
DoctrineMigrationsBundle::class => ['all' => true],
KnpTimeBundle::class => ['all' => true],
KnpUOAuth2ClientBundle::class => ['all' => true],
SentryBundle::class => ['prod' => true],
SncRedisBundle::class => ['all' => true],
MonologBundle::class => ['all' => true],
DoctrineFixturesBundle::class => ['dev' => true, 'test' => true],
TwigBundle::class => ['all' => true],
TwigExtraBundle::class => ['all' => true],
SecurityBundle::class => ['all' => true],
DebugBundle::class => ['dev' => true, 'test' => true],
WebProfilerBundle::class => ['dev' => true, 'test' => true],
];
| php | MIT | 8b3f266d748406c74b6971f95ad9a62003365e8a | 2026-01-05T04:49:43.160258Z | false |
reactphp/filesystem | https://github.com/reactphp/filesystem/blob/385933fdf47ad2db195c859523a8d854792dbad2/src/NodeNotFound.php | src/NodeNotFound.php | <?php
namespace React\Filesystem;
use React\EventLoop\ExtUvLoop;
use React\Filesystem\Node\FileInterface;
use React\Filesystem\Stat;
use React\Promise\Promise;
use React\Promise\PromiseInterface;
use RuntimeException;
use React\EventLoop\LoopInterface;
use React\Filesystem\Node;
use UV;
final class NodeNotFound extends \Exception
{
}
| php | MIT | 385933fdf47ad2db195c859523a8d854792dbad2 | 2026-01-05T04:49:50.958304Z | false |
reactphp/filesystem | https://github.com/reactphp/filesystem/blob/385933fdf47ad2db195c859523a8d854792dbad2/src/FlagResolver.php | src/FlagResolver.php | <?php
namespace React\Filesystem;
abstract class FlagResolver
{
/**
* @param string $flagString
* @param null|int $flags
* @param null|array $mapping
* @return int
*/
public function resolve($flagString, $flags = null, $mapping = null)
{
if ($flags === null) {
$flags = $this->defaultFlags();
}
if ($mapping === null) {
$mapping = $this->flagMapping();
}
$flagString = str_split($flagString);
foreach ($flagString as $flag) {
if (isset($mapping[$flag])) {
$flags |= $mapping[$flag];
}
}
return $flags;
}
}
| php | MIT | 385933fdf47ad2db195c859523a8d854792dbad2 | 2026-01-05T04:49:50.958304Z | false |
reactphp/filesystem | https://github.com/reactphp/filesystem/blob/385933fdf47ad2db195c859523a8d854792dbad2/src/AdapterInterface.php | src/AdapterInterface.php | <?php
namespace React\Filesystem;
use React\Filesystem\Node;
use React\Promise\PromiseInterface;
interface AdapterInterface
{
/**
* @return PromiseInterface<Node\NodeInterface>
*/
public function detect(string $path): PromiseInterface;
public function directory(string $path): Node\DirectoryInterface;
public function file(string $path): Node\FileInterface;
}
| php | MIT | 385933fdf47ad2db195c859523a8d854792dbad2 | 2026-01-05T04:49:50.958304Z | false |
reactphp/filesystem | https://github.com/reactphp/filesystem/blob/385933fdf47ad2db195c859523a8d854792dbad2/src/PollInterface.php | src/PollInterface.php | <?php
namespace React\Filesystem;
use UV;
interface PollInterface
{
public function activate(): void;
public function deactivate(): void;
}
| php | MIT | 385933fdf47ad2db195c859523a8d854792dbad2 | 2026-01-05T04:49:50.958304Z | false |
reactphp/filesystem | https://github.com/reactphp/filesystem/blob/385933fdf47ad2db195c859523a8d854792dbad2/src/FlagResolverInterface.php | src/FlagResolverInterface.php | <?php
namespace React\Filesystem;
interface FlagResolverInterface
{
/**
* @return int
*/
public function defaultFlags();
/**
* @return array
*/
public function flagMapping();
}
| php | MIT | 385933fdf47ad2db195c859523a8d854792dbad2 | 2026-01-05T04:49:50.958304Z | false |
reactphp/filesystem | https://github.com/reactphp/filesystem/blob/385933fdf47ad2db195c859523a8d854792dbad2/src/TypeDetectorInterface.php | src/TypeDetectorInterface.php | <?php
namespace React\Filesystem;
interface TypeDetectorInterface
{
/**
* @param AdapterInterface $filesystem
*/
public function __construct(AdapterInterface $filesystem);
/**
* @param array $node
* @return React\Promise\PromiseInterface
*/
public function detect(array $node);
}
| php | MIT | 385933fdf47ad2db195c859523a8d854792dbad2 | 2026-01-05T04:49:50.958304Z | false |
reactphp/filesystem | https://github.com/reactphp/filesystem/blob/385933fdf47ad2db195c859523a8d854792dbad2/src/Stat.php | src/Stat.php | <?php
namespace React\Filesystem;
use React\EventLoop\ExtUvLoop;
use React\EventLoop\LoopInterface;
final class Stat
{
private string $path;
/** @var array<string, mixed> */
private array $data;
public function __construct(string $path, array $data)
{
$this->path = $path;
$this->data = $data;
}
public function path(): string
{
return $this->path;
}
public function mode(): ?int
{
return array_key_exists('mode', $this->data) ? $this->data['mode'] : null;
}
public function uid(): ?int
{
return array_key_exists('uid', $this->data) ? $this->data['uid'] : null;
}
public function gid(): ?int
{
return array_key_exists('gid', $this->data) ? $this->data['gid'] : null;
}
public function size(): ?int
{
return array_key_exists('size', $this->data) ? $this->data['size'] : null;
}
public function atime(): ?\DateTimeImmutable
{
return array_key_exists('atime', $this->data) ? new \DateTimeImmutable('@' . $this->data['atime']) : null;
}
public function mtime(): ?\DateTimeImmutable
{
return array_key_exists('mtime', $this->data) ? new \DateTimeImmutable('@' . $this->data['mtime']) : null;
}
public function ctime(): ?\DateTimeImmutable
{
return array_key_exists('ctime', $this->data) ? new \DateTimeImmutable('@' . $this->data['ctime']) : null;
}
}
| php | MIT | 385933fdf47ad2db195c859523a8d854792dbad2 | 2026-01-05T04:49:50.958304Z | false |
reactphp/filesystem | https://github.com/reactphp/filesystem/blob/385933fdf47ad2db195c859523a8d854792dbad2/src/ModeTypeDetector.php | src/ModeTypeDetector.php | <?php
namespace React\Filesystem;
use React\EventLoop\ExtUvLoop;
use React\EventLoop\LoopInterface;
use React\Filesystem\Node\DirectoryInterface;
use React\Filesystem\Node\FileInterface;
use React\Filesystem\Node\Unknown;
final class ModeTypeDetector
{
private const FILE = 0x8000;
private const DIRECTORY = 0x4000;
private const LINK = 0xa000;
public static function detect(int $mode): string
{
if (($mode & self::FILE) == self::FILE) {
return FileInterface::class;
}
if (($mode & self::DIRECTORY) == self::DIRECTORY) {
return DirectoryInterface::class;
}
return Unknown::class;
}
}
| php | MIT | 385933fdf47ad2db195c859523a8d854792dbad2 | 2026-01-05T04:49:50.958304Z | false |
reactphp/filesystem | https://github.com/reactphp/filesystem/blob/385933fdf47ad2db195c859523a8d854792dbad2/src/Factory.php | src/Factory.php | <?php
namespace React\Filesystem;
use React\EventLoop\ExtUvLoop;
use React\EventLoop\Loop;
use React\Filesystem\Uv;
use React\Filesystem\Eio;
final class Factory
{
public static function create(): AdapterInterface
{
if (\function_exists('eio_get_event_stream')) {
return new Eio\Adapter();
}
if (\function_exists('uv_loop_new') && Loop::get() instanceof ExtUvLoop) {
return new Uv\Adapter();
}
return new Fallback\Adapter();
}
}
| php | MIT | 385933fdf47ad2db195c859523a8d854792dbad2 | 2026-01-05T04:49:50.958304Z | false |
reactphp/filesystem | https://github.com/reactphp/filesystem/blob/385933fdf47ad2db195c859523a8d854792dbad2/src/Eio/Adapter.php | src/Eio/Adapter.php | <?php
namespace React\Filesystem\Eio;
use React\EventLoop\Loop;
use React\EventLoop\LoopInterface;
use React\Filesystem\AdapterInterface;
use React\Filesystem\ModeTypeDetector;
use React\Filesystem\Node;
use React\Filesystem\PollInterface;
use React\Filesystem\Stat;
use React\Promise\PromiseInterface;
final class Adapter implements AdapterInterface
{
use StatTrait;
private LoopInterface $loop;
private PollInterface $poll;
public function __construct()
{
$this->loop = Loop::get();
$this->poll = new Poll($this->loop);
}
public function detect(string $path): PromiseInterface
{
return $this->internalStat($path)->then(function (?Stat $stat) use ($path) {
if ($stat === null) {
return new NotExist($this->poll, $this, $this->loop, dirname($path) . DIRECTORY_SEPARATOR, basename($path));
}
switch (ModeTypeDetector::detect($stat->mode())) {
case Node\FileInterface::class:
return $this->file($stat->path());
break;
case Node\DirectoryInterface::class:
return $this->directory($stat->path());
break;
default:
return new Node\Unknown($stat->path(), $stat->path());
break;
}
});
}
public function directory(string $path): Node\DirectoryInterface
{
return new Directory($this->poll, $this, dirname($path) . DIRECTORY_SEPARATOR, basename($path));
}
public function file(string $path): Node\FileInterface
{
return new File($this->poll, dirname($path) . DIRECTORY_SEPARATOR, basename($path));
}
protected function activate(): void
{
$this->poll->activate();
}
protected function deactivate(): void
{
$this->poll->deactivate();
}
}
| php | MIT | 385933fdf47ad2db195c859523a8d854792dbad2 | 2026-01-05T04:49:50.958304Z | false |
reactphp/filesystem | https://github.com/reactphp/filesystem/blob/385933fdf47ad2db195c859523a8d854792dbad2/src/Eio/EventStream.php | src/Eio/EventStream.php | <?php
namespace React\Filesystem\Eio;
/**
* Singleton to make sure we always only have one file descriptor for the ext-eio event stream.
* Creating more than one will invalidate the previous ones and make anything still using those fail.
*
* @internal
*/
final class EventStream
{
private static $fd = null;
public static function get()
{
if (self::$fd !== null) {
return self::$fd;
}
self::$fd = eio_get_event_stream();
return self::$fd;
}
}
| php | MIT | 385933fdf47ad2db195c859523a8d854792dbad2 | 2026-01-05T04:49:50.958304Z | false |
reactphp/filesystem | https://github.com/reactphp/filesystem/blob/385933fdf47ad2db195c859523a8d854792dbad2/src/Eio/Poll.php | src/Eio/Poll.php | <?php
namespace React\Filesystem\Eio;
use React\EventLoop\LoopInterface;
use React\Filesystem\PollInterface;
final class Poll implements PollInterface
{
private LoopInterface $loop;
private $fd;
private \Closure $handleEvent;
private int $workInProgress = 0;
public function __construct(LoopInterface $loop)
{
$this->fd = EventStream::get();
$this->loop = $loop;
$this->handleEvent = function () {
$this->handleEvent();
};
}
public function activate(): void
{
if ($this->workInProgress++ === 0) {
$this->loop->addReadStream($this->fd, $this->handleEvent);
}
}
private function handleEvent()
{
while (eio_npending()) {
eio_poll();
}
}
public function deactivate(): void
{
if (--$this->workInProgress <= 0) {
$this->loop->removeReadStream($this->fd);
}
}
}
| php | MIT | 385933fdf47ad2db195c859523a8d854792dbad2 | 2026-01-05T04:49:50.958304Z | false |
reactphp/filesystem | https://github.com/reactphp/filesystem/blob/385933fdf47ad2db195c859523a8d854792dbad2/src/Eio/StatTrait.php | src/Eio/StatTrait.php | <?php
namespace React\Filesystem\Eio;
use React\Filesystem\Stat;
use React\Promise\Promise;
use React\Promise\PromiseInterface;
trait StatTrait
{
protected function internalStat(string $path): PromiseInterface
{
return new Promise(function (callable $resolve, callable $reject) use ($path): void {
$this->activate();
eio_lstat($path, EIO_PRI_DEFAULT, function ($_, $stat) use ($path, $resolve, $reject): void {
try {
$this->deactivate();
if (is_array($stat)) {
$resolve(new Stat($path, $stat));
} else {
$resolve(null);
}
} catch (\Throwable $error) {
$reject($error);
}
});
});
}
abstract protected function activate(): void;
abstract protected function deactivate(): void;
}
| php | MIT | 385933fdf47ad2db195c859523a8d854792dbad2 | 2026-01-05T04:49:50.958304Z | false |
reactphp/filesystem | https://github.com/reactphp/filesystem/blob/385933fdf47ad2db195c859523a8d854792dbad2/src/Eio/NotExist.php | src/Eio/NotExist.php | <?php
namespace React\Filesystem\Eio;
use React\EventLoop\LoopInterface;
use React\Filesystem\AdapterInterface;
use React\Filesystem\Node;
use React\Filesystem\PollInterface;
use React\Promise\Promise;
use React\Promise\PromiseInterface;
use function React\Promise\resolve;
final class NotExist implements Node\NotExistInterface
{
use StatTrait;
private LoopInterface $loop;
private PollInterface $poll;
private AdapterInterface $filesystem;
private string $path;
private string $name;
public function __construct(PollInterface $poll, AdapterInterface $filesystem, LoopInterface $loop, string $path, string $name)
{
$this->poll = $poll;
$this->filesystem = $filesystem;
$this->loop = $loop;
$this->path = $path;
$this->name = $name;
}
public function stat(): PromiseInterface
{
return $this->internalStat($this->path . $this->name);
}
public function createDirectory(): PromiseInterface
{
return $this->filesystem->detect($this->path)->then(function (Node\NodeInterface $node): PromiseInterface {
if ($node instanceof Node\NotExistInterface) {
return $node->createDirectory();
}
return resolve($node);
})->then(function (Node\DirectoryInterface $directory): PromiseInterface {
return new Promise(function (callable $resolve): void {
$this->activate();
\eio_mkdir($this->path . $this->name, 0777, \EIO_PRI_DEFAULT, function () use ($resolve): void {
$this->deactivate();
$resolve($this->filesystem->directory($this->path . $this->name));
});
});
});
}
public function createFile(): PromiseInterface
{
$file = new File($this->poll, $this->path, $this->name);
return $this->filesystem->detect($this->path)->then(function (Node\NodeInterface $node): PromiseInterface {
if ($node instanceof Node\NotExistInterface) {
return $node->createDirectory();
}
return resolve($node);
})->then(function () use ($file): PromiseInterface {
$this->activate();
return new Promise(function (callable $resolve, callable $reject): void {
\eio_open(
$this->path . DIRECTORY_SEPARATOR . $this->name,
\EIO_O_RDWR | \EIO_O_CREAT,
0777,
\EIO_PRI_DEFAULT,
function ($_, $fileDescriptor) use ($resolve, $reject): void {
try {
\eio_close($fileDescriptor, \EIO_PRI_DEFAULT, function () use ($resolve) {
$this->deactivate();
$resolve($this->filesystem->file($this->path . $this->name));
});
} catch (\Throwable $error) {
$this->deactivate();
$reject($error);
}
}
);
});
})->then(function () use ($file): Node\FileInterface {
return $file;
});
}
public function unlink(): PromiseInterface
{
// Essentially a No-OP since it doesn't exist anyway
return resolve(true);
}
public function path(): string
{
return $this->path;
}
public function name(): string
{
return $this->name;
}
protected function activate(): void
{
$this->poll->activate();
}
protected function deactivate(): void
{
$this->poll->deactivate();
}
}
| php | MIT | 385933fdf47ad2db195c859523a8d854792dbad2 | 2026-01-05T04:49:50.958304Z | false |
reactphp/filesystem | https://github.com/reactphp/filesystem/blob/385933fdf47ad2db195c859523a8d854792dbad2/src/Eio/Directory.php | src/Eio/Directory.php | <?php
namespace React\Filesystem\Eio;
use React\Filesystem\AdapterInterface;
use React\Filesystem\Node;
use React\Filesystem\PollInterface;
use React\Promise\Promise;
use React\Promise\PromiseInterface;
use function React\Promise\all;
final class Directory implements Node\DirectoryInterface
{
use StatTrait;
private PollInterface $poll;
private AdapterInterface $filesystem;
private string $path;
private string $name;
public function __construct(PollInterface $poll, AdapterInterface $filesystem, string $path, string $name)
{
$this->poll = $poll;
$this->filesystem = $filesystem;
$this->path = $path;
$this->name = $name;
}
public function stat(): PromiseInterface
{
return $this->internalStat($this->path . $this->name);
}
public function ls(): PromiseInterface
{
$this->activate();
return new Promise(function (callable $resolve): void {
\eio_readdir($this->path . $this->name . DIRECTORY_SEPARATOR, \EIO_READDIR_STAT_ORDER | \EIO_READDIR_DIRS_FIRST, \EIO_PRI_DEFAULT, function ($_, $contents) use ($resolve): void {
$this->deactivate();
$list = [];
foreach ($contents['dents'] as $node) {
$fullPath = $this->path . $this->name . DIRECTORY_SEPARATOR . $node['name'];
switch ($node['type'] ?? null) {
case EIO_DT_DIR:
$list[] = $this->filesystem->directory($fullPath);
break;
case EIO_DT_REG :
$list[] = $this->filesystem->file($fullPath);
break;
default:
$list[] = $this->filesystem->detect($this->path . $this->name . DIRECTORY_SEPARATOR . $node['name']);
break;
}
}
$resolve(all($list));
});
});
}
public function unlink(): PromiseInterface
{
$this->activate();
return new Promise(function (callable $resolve): void {
\eio_readdir($this->path . $this->name . DIRECTORY_SEPARATOR, \EIO_READDIR_STAT_ORDER | \EIO_READDIR_DIRS_FIRST, \EIO_PRI_DEFAULT, function ($_, $contents) use ($resolve): void {
$this->deactivate();
if (count($contents['dents']) > 0) {
$resolve(false);
return;
}
$this->activate();
\eio_rmdir($this->path . $this->name, function () use ($resolve): void {
$this->deactivate();
$resolve(true);
});
});
});
}
public function path(): string
{
return $this->path;
}
public function name(): string
{
return $this->name;
}
protected function activate(): void
{
$this->poll->activate();
}
protected function deactivate(): void
{
$this->poll->deactivate();
}
}
| php | MIT | 385933fdf47ad2db195c859523a8d854792dbad2 | 2026-01-05T04:49:50.958304Z | false |
reactphp/filesystem | https://github.com/reactphp/filesystem/blob/385933fdf47ad2db195c859523a8d854792dbad2/src/Eio/File.php | src/Eio/File.php | <?php
namespace React\Filesystem\Eio;
use React\Filesystem\Node\FileInterface;
use React\Filesystem\PollInterface;
use React\Promise\Promise;
use React\Promise\PromiseInterface;
use function React\Promise\resolve;
final class File implements FileInterface
{
use StatTrait;
private PollInterface $poll;
private string $path;
private string $name;
public function __construct(PollInterface $poll, string $path, string $name)
{
$this->poll = $poll;
$this->path = $path;
$this->name = $name;
}
public function stat(): PromiseInterface
{
return $this->internalStat($this->path . $this->name);
}
public function getContents(int $offset = 0 , ?int $maxlen = null): PromiseInterface
{
$this->activate();
return $this->openFile(
$this->path . DIRECTORY_SEPARATOR . $this->name,
\EIO_O_RDONLY,
0,
)->then(
function ($fileDescriptor) use ($offset, $maxlen): PromiseInterface {
if ($maxlen === null) {
$sizePromise = $this->statFileDescriptor($fileDescriptor)->then(static function ($stat): int {
return (int)$stat['size'];
});
} else {
$sizePromise = resolve($maxlen);
}
return $sizePromise->then(function ($length) use ($fileDescriptor, $offset): PromiseInterface {
return new Promise (function (callable $resolve) use ($fileDescriptor, $offset, $length): void {
\eio_read($fileDescriptor, $length, $offset, \EIO_PRI_DEFAULT, function ($fileDescriptor, string $buffer) use ($resolve): void {
$resolve($this->closeOpenFile($fileDescriptor)->then(function () use ($buffer): string {
return $buffer;
}));
}, $fileDescriptor);
});
});
}
);
}
public function putContents(string $contents, int $flags = 0)
{
$this->activate();
return $this->openFile(
$this->path . DIRECTORY_SEPARATOR . $this->name,
(($flags & \FILE_APPEND) == \FILE_APPEND) ? \EIO_O_RDWR | \EIO_O_APPEND : \EIO_O_RDWR | \EIO_O_CREAT,
0644
)->then(
function ($fileDescriptor) use ($contents, $flags): PromiseInterface {
return new Promise (function (callable $resolve) use ($contents, $fileDescriptor): void {
\eio_write($fileDescriptor, $contents, strlen($contents), 0, \EIO_PRI_DEFAULT, function ($fileDescriptor, int $bytesWritten) use ($resolve): void {
$resolve($this->closeOpenFile($fileDescriptor)->then(function () use ($bytesWritten): int {
return $bytesWritten;
}));
}, $fileDescriptor);
});
}
);
}
private function statFileDescriptor($fileDescriptor): PromiseInterface
{
return new Promise(function (callable $resolve, callable $reject) use ($fileDescriptor) {
\eio_fstat($fileDescriptor, \EIO_PRI_DEFAULT, function ($_, $stat) use ($resolve): void {
$resolve($stat);
}, $fileDescriptor);
});
}
private function openFile(string $path, int $flags, int $mode): PromiseInterface
{
return new Promise(function (callable $resolve, callable $reject) use ($path, $flags, $mode): void {
\eio_open(
$path,
$flags,
$mode,
\EIO_PRI_DEFAULT,
function ($_, $fileDescriptor) use ($resolve): void {
$resolve($fileDescriptor);
}
);
});
}
private function closeOpenFile($fileDescriptor): PromiseInterface
{
return new Promise(function (callable $resolve) use ($fileDescriptor) {
try {
\eio_close($fileDescriptor, \EIO_PRI_DEFAULT, function () use ($resolve): void {
$this->deactivate();
$resolve(true);
});
} catch (\Throwable $error) {
$this->deactivate();
throw $error;
}
});
}
public function unlink(): PromiseInterface
{
$this->activate();
return new Promise(function (callable $resolve): void {
\eio_unlink($this->path . DIRECTORY_SEPARATOR . $this->name, \EIO_PRI_DEFAULT, function () use ($resolve): void {
$this->deactivate();
$resolve(true);
});
});
}
public function path(): string
{
return $this->path;
}
public function name(): string
{
return $this->name;
}
protected function activate(): void
{
$this->poll->activate();
}
protected function deactivate(): void
{
$this->poll->deactivate();
}
}
| php | MIT | 385933fdf47ad2db195c859523a8d854792dbad2 | 2026-01-05T04:49:50.958304Z | false |
reactphp/filesystem | https://github.com/reactphp/filesystem/blob/385933fdf47ad2db195c859523a8d854792dbad2/src/Node/DirectoryInterface.php | src/Node/DirectoryInterface.php | <?php
namespace React\Filesystem\Node;
use React\Filesystem\AdapterInterface;
use React\Promise\PromiseInterface;
use Rx\Observable;
interface DirectoryInterface extends NodeInterface
{
/**
* @return PromiseInterface<array<NodeInterface>>
*/
public function ls(): PromiseInterface;
}
| php | MIT | 385933fdf47ad2db195c859523a8d854792dbad2 | 2026-01-05T04:49:50.958304Z | false |
reactphp/filesystem | https://github.com/reactphp/filesystem/blob/385933fdf47ad2db195c859523a8d854792dbad2/src/Node/FileInterface.php | src/Node/FileInterface.php | <?php
namespace React\Filesystem\Node;
use React\Promise\PromiseInterface;
interface FileInterface extends NodeInterface
{
/**
* Open the file and read all its contents returning those through a promise.
*
* @return PromiseInterface<string>
*/
public function getContents(int $offset = 0 , ?int $maxlen = null);
/**
* Write the given contents to the file, overwriting any existing contents or creating the file.
*
* @param string $contents
* @return PromiseInterface<int>
*/
public function putContents(string $contents, int $flags = 0);
}
| php | MIT | 385933fdf47ad2db195c859523a8d854792dbad2 | 2026-01-05T04:49:50.958304Z | false |
reactphp/filesystem | https://github.com/reactphp/filesystem/blob/385933fdf47ad2db195c859523a8d854792dbad2/src/Node/NodeInterface.php | src/Node/NodeInterface.php | <?php
namespace React\Filesystem\Node;
use React\Filesystem\Stat;
use React\Promise\PromiseInterface;
interface NodeInterface
{
const DS = DIRECTORY_SEPARATOR;
/**
* Return the full path, for example: /path/to/
*
* @return string
*/
public function path();
/**
* Return the node name, for example: file.ext
*
* @return string
*/
public function name();
/**
* Return the node name, for example: file.ext
*
* @return PromiseInterface<?Stat>
*/
public function stat(): PromiseInterface;
/**
* Remove the node from the filesystem, errors on non-empty directories
*
* @return PromiseInterface<bool>
*/
public function unlink(): PromiseInterface;
}
| php | MIT | 385933fdf47ad2db195c859523a8d854792dbad2 | 2026-01-05T04:49:50.958304Z | false |
reactphp/filesystem | https://github.com/reactphp/filesystem/blob/385933fdf47ad2db195c859523a8d854792dbad2/src/Node/NotExistInterface.php | src/Node/NotExistInterface.php | <?php
namespace React\Filesystem\Node;
use React\Promise\PromiseInterface;
use Rx\Observable;
interface NotExistInterface extends NodeInterface
{
/**
* @return PromiseInterface<DirectoryInterface>
*/
public function createDirectory(): PromiseInterface;
/**
* @return PromiseInterface<FileInterface>
*/
public function createFile(): PromiseInterface;
}
| php | MIT | 385933fdf47ad2db195c859523a8d854792dbad2 | 2026-01-05T04:49:50.958304Z | false |
reactphp/filesystem | https://github.com/reactphp/filesystem/blob/385933fdf47ad2db195c859523a8d854792dbad2/src/Fallback/Adapter.php | src/Fallback/Adapter.php | <?php
namespace React\Filesystem\Fallback;
use React\Filesystem\AdapterInterface;
use React\Filesystem\ModeTypeDetector;
use React\Filesystem\Stat;
use React\Promise\PromiseInterface;
use React\Filesystem\Node;
final class Adapter implements AdapterInterface
{
use StatTrait;
public function detect(string $path): PromiseInterface
{
return $this->internalStat($path)->then(function (?Stat $stat) use ($path) {
if ($stat === null) {
return new NotExist($this, dirname($path) . DIRECTORY_SEPARATOR, basename($path));
}
switch (ModeTypeDetector::detect($stat->mode())) {
case Node\DirectoryInterface::class:
return $this->directory($stat->path());
break;
case Node\FileInterface::class:
return $this->file($stat->path());
break;
default:
return new Node\Unknown($stat->path(), $stat->path());
break;
}
});
}
public function directory(string $path): Node\DirectoryInterface
{
return new Directory($this, dirname($path) . DIRECTORY_SEPARATOR, basename($path));
}
public function file(string $path): Node\FileInterface
{
return new File(dirname($path) . DIRECTORY_SEPARATOR, basename($path));
}
}
| php | MIT | 385933fdf47ad2db195c859523a8d854792dbad2 | 2026-01-05T04:49:50.958304Z | false |
reactphp/filesystem | https://github.com/reactphp/filesystem/blob/385933fdf47ad2db195c859523a8d854792dbad2/src/Fallback/StatTrait.php | src/Fallback/StatTrait.php | <?php
namespace React\Filesystem\Fallback;
use React\EventLoop\ExtUvLoop;
use React\Filesystem\Node\FileInterface;
use React\Filesystem\Stat;
use React\Promise\Promise;
use React\Promise\PromiseInterface;
use RuntimeException;
use React\EventLoop\LoopInterface;
use React\Filesystem\Node;
use UV;
use function React\Promise\resolve;
use function WyriHaximus\React\FallbackPromiseClosure;
trait StatTrait
{
protected function internalStat(string $path): PromiseInterface
{
if (!file_exists($path)) {
return resolve(null);
}
return resolve(new Stat($path, stat($path)));
}
}
| php | MIT | 385933fdf47ad2db195c859523a8d854792dbad2 | 2026-01-05T04:49:50.958304Z | false |
reactphp/filesystem | https://github.com/reactphp/filesystem/blob/385933fdf47ad2db195c859523a8d854792dbad2/src/Fallback/NotExist.php | src/Fallback/NotExist.php | <?php
namespace React\Filesystem\Fallback;
use React\EventLoop\ExtUvLoop;
use React\EventLoop\LoopInterface;
use React\Filesystem\AdapterInterface;
use React\Filesystem\Node;
use React\Filesystem\PollInterface;
use React\Promise\CancellablePromiseInterface;
use React\Promise\Deferred;
use React\Promise\PromiseInterface;
use function React\Promise\all;
use function React\Promise\resolve;
use function WyriHaximus\React\FallbackPromiseClosure;
final class NotExist implements Node\NotExistInterface
{
use StatTrait;
private AdapterInterface $filesystem;
private string $path;
private string $name;
public function __construct(AdapterInterface $filesystem, string $path, string $name)
{
$this->filesystem = $filesystem;
$this->path = $path;
$this->name = $name;
}
public function stat(): PromiseInterface
{
return $this->internalStat($this->path . $this->name);
}
public function createDirectory(): PromiseInterface
{
$path = $this->path . $this->name;
mkdir($path,0777, true);
return resolve(new Directory($this->filesystem, $this->path, $this->name));
}
public function createFile(): PromiseInterface
{
$file = new File($this->path, $this->name);
return $this->filesystem->detect($this->path)->then(function (Node\NodeInterface $node): PromiseInterface {
if ($node instanceof Node\NotExistInterface) {
return $node->createDirectory();
}
return resolve($node);
})->then(function () use ($file): PromiseInterface {
return $file->putContents('');
})->then(function () use ($file): Node\FileInterface {
return $file;
});
}
public function unlink(): PromiseInterface
{
// Essentially a No-OP since it doesn't exist anyway
return resolve(true);
}
public function path(): string
{
return $this->path;
}
public function name(): string
{
return $this->name;
}
}
| php | MIT | 385933fdf47ad2db195c859523a8d854792dbad2 | 2026-01-05T04:49:50.958304Z | false |
reactphp/filesystem | https://github.com/reactphp/filesystem/blob/385933fdf47ad2db195c859523a8d854792dbad2/src/Fallback/Directory.php | src/Fallback/Directory.php | <?php
namespace React\Filesystem\Fallback;
use React\EventLoop\LoopInterface;
use React\Filesystem\AdapterInterface;
use React\Filesystem\Node;
use React\Promise\PromiseInterface;
use function React\Promise\all;
use function React\Promise\resolve;
use function WyriHaximus\React\FallbackPromiseClosure;
final class Directory implements Node\DirectoryInterface
{
use StatTrait;
private AdapterInterface $filesystem;
private string $path;
private string $name;
public function __construct(AdapterInterface $filesystem, string $path, string $name)
{
$this->filesystem = $filesystem;
$this->path = $path;
$this->name = $name;
}
public function stat(): PromiseInterface
{
return $this->internalStat($this->path . $this->name);
}
public function ls(): PromiseInterface
{
$path = $this->path . $this->name;
$promises = [];
foreach (scandir($path) as $node) {
if (in_array($node, ['.', '..'])) {
continue;
}
$promises[] = $this->filesystem->detect($this->path . $this->name . DIRECTORY_SEPARATOR . $node);
}
return all($promises);
}
public function unlink(): PromiseInterface
{
$path = $this->path . $this->name;
if (count(scandir($path)) > 0) {
return resolve(false);
}
return resolve(rmdir($path));
}
public function path(): string
{
return $this->path;
}
public function name(): string
{
return $this->name;
}
}
| php | MIT | 385933fdf47ad2db195c859523a8d854792dbad2 | 2026-01-05T04:49:50.958304Z | false |
reactphp/filesystem | https://github.com/reactphp/filesystem/blob/385933fdf47ad2db195c859523a8d854792dbad2/src/Fallback/File.php | src/Fallback/File.php | <?php
namespace React\Filesystem\Fallback;
use React\EventLoop\LoopInterface;
use React\Filesystem\Node\FileInterface;
use React\Promise\PromiseInterface;
use function React\Promise\resolve;
use function WyriHaximus\React\FallbackPromiseClosure;
final class File implements FileInterface
{
use StatTrait;
private string $path;
private string $name;
public function __construct(string $path, string $name)
{
$this->path = $path;
$this->name = $name;
}
public function stat(): PromiseInterface
{
return $this->internalStat($this->path . $this->name);
}
public function getContents(int $offset = 0 , ?int $maxlen = null): PromiseInterface
{
$path = $this->path . $this->name;
return resolve(file_get_contents($path, false, null, $offset, $maxlen ?? (int)stat($path)['size']));
}
public function putContents(string $contents, int $flags = 0): PromiseInterface
{
// Making sure we only pass in one flag for security reasons
if (($flags & \FILE_APPEND) == \FILE_APPEND) {
$flags = \FILE_APPEND;
} else {
$flags = 0;
}
$path = $this->path . $this->name;
return resolve(file_put_contents($path, $contents, $flags));
}
public function unlink(): PromiseInterface
{
$path = $this->path . $this->name;
return resolve(unlink($path));
}
public function path(): string
{
return $this->path;
}
public function name(): string
{
return $this->name;
}
}
| php | MIT | 385933fdf47ad2db195c859523a8d854792dbad2 | 2026-01-05T04:49:50.958304Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.