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 |
|---|---|---|---|---|---|---|---|---|
recca0120/laravel-repository | https://github.com/recca0120/laravel-repository/blob/d506fdc8c602e0ccaa52aea2d2f8ee3380dbbedd/src/SqliteModel.php | src/SqliteModel.php | <?php
namespace Recca0120\Repository;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Recca0120\Repository\SqliteConnectionResolver as ConnectionResolver;
abstract class SqliteModel extends Model
{
/**
* $tableCreated.
*
* @var array
*/
protected static $tableCreated = [];
/**
* Get the table associated with the model.
*
* @return string
*/
public function getTable()
{
return $this->createTable(parent::getTable());
}
/**
* Resolve a connection instance.
*
* @param string|null $connection
* @return ConnectionInterface
*/
public static function resolveConnection($connection = null)
{
return ConnectionResolver::getInstance()->connection($connection);
}
/**
* {@inheritdoc}
*
* @param string $table
* @return string
*/
protected function createTable($table)
{
if (isset(static::$tableCreated[$table]) === true) {
return $table;
}
$schema = $this->getConnection()->getSchemaBuilder();
if ($schema->hasTable($table) === false) {
$schema->create($table, function (Blueprint $table) {
$this->createSchema($table);
});
static::$tableCreated[$table] = true;
if ($this instanceof FileModel === true) {
$this->initializeTable($table);
}
}
return $table;
}
/**
* createSchema.
*
* @return void
*/
abstract protected function createSchema(Blueprint $table);
}
| php | MIT | d506fdc8c602e0ccaa52aea2d2f8ee3380dbbedd | 2026-01-05T05:08:03.638560Z | false |
recca0120/laravel-repository | https://github.com/recca0120/laravel-repository/blob/d506fdc8c602e0ccaa52aea2d2f8ee3380dbbedd/src/FileModel.php | src/FileModel.php | <?php
namespace Recca0120\Repository;
use Illuminate\Support\Collection;
abstract class FileModel extends SqliteModel
{
/**
* loadFromResource.
*
* @return Collection
*/
abstract protected function loadFromResource();
/**
* initializeTable.
*
* @param string $table
* @return void
*/
protected function initializeTable($table)
{
$this->loadFromResource()->chunk(10)->each(function ($items) {
$this->newQuery()->insert($items->toArray());
});
}
}
| php | MIT | d506fdc8c602e0ccaa52aea2d2f8ee3380dbbedd | 2026-01-05T05:08:03.638560Z | false |
recca0120/laravel-repository | https://github.com/recca0120/laravel-repository/blob/d506fdc8c602e0ccaa52aea2d2f8ee3380dbbedd/src/polyfill.php | src/polyfill.php | <?php
use Recca0120\Repository\HigherOrderTapProxy;
if (! function_exists('tap')) {
/**
* Call the given Closure with the given value then return the value.
*
* @param mixed $value
* @param callable|null $callback
* @return mixed
*/
function tap($value, $callback = null)
{
if (is_null($callback)) {
return new HigherOrderTapProxy($value);
}
$callback($value);
return $value;
}
}
| php | MIT | d506fdc8c602e0ccaa52aea2d2f8ee3380dbbedd | 2026-01-05T05:08:03.638560Z | false |
recca0120/laravel-repository | https://github.com/recca0120/laravel-repository/blob/d506fdc8c602e0ccaa52aea2d2f8ee3380dbbedd/src/Contracts/EloquentRepository.php | src/Contracts/EloquentRepository.php | <?php
namespace Recca0120\Repository\Contracts;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Contracts\Pagination\Paginator;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use InvalidArgumentException;
use Recca0120\Repository\Criteria;
use Throwable;
interface EloquentRepository
{
/**
* Find a model by its primary key.
*
* @param mixed $id
* @param array $columns
* @return Model|Collection|static[]|static|null
*/
public function find($id, $columns = ['*']);
/**
* Find multiple models by their primary keys.
*
* @param Arrayable|array $ids
* @param array $columns
* @return Collection
*/
public function findMany($ids, $columns = ['*']);
/**
* Find a model by its primary key or throw an exception.
*
* @param mixed $id
* @param array $columns
* @return Model|Collection
*
* @throws ModelNotFoundException
*/
public function findOrFail($id, $columns = ['*']);
/**
* Find a model by its primary key or return fresh model instance.
*
* @param mixed $id
* @param array $columns
* @return Model
*/
public function findOrNew($id, $columns = ['*']);
/**
* Get the first record matching the attributes or instantiate it.
*
* @return Model
*/
public function firstOrNew(array $attributes, array $values = []);
/**
* Get the first record matching the attributes or create it.
*
* @return Model
*/
public function firstOrCreate(array $attributes, array $values = []);
/**
* Create or update a record matching the attributes, and fill it with values.
*
* @return Model
*/
public function updateOrCreate(array $attributes, array $values = []);
/**
* Execute the query and get the first result or throw an exception.
*
* @param array $columns
* @param Criteria[]|Criteria $criteria
* @return Model|static
*
* @throws ModelNotFoundException
*/
public function firstOrFail($criteria = [], $columns = ['*']);
/**
* create.
*
* @param array $attributes
* @return Model
*
* @throws Throwable
*/
public function create($attributes);
/**
* Save a new model and return the instance.
*
* @param array $attributes
* @return Model
*
* @throws Throwable
*/
public function forceCreate($attributes);
/**
* update.
*
* @param array $attributes
* @param mixed $id
* @return Model
*
* @throws Throwable
*/
public function update($id, $attributes);
/**
* forceCreate.
*
* @param array $attributes
* @param mixed $id
* @return Model
*
* @throws Throwable
*/
public function forceUpdate($id, $attributes);
/**
* delete.
*
* @param mixed $id
*/
public function delete($id);
/**
* Force a hard delete on a soft deleted model.
*
* This method protects developers from running forceDelete when trait is missing.
*
* @param mixed $id
* @return bool|null
*/
public function forceDelete($id);
/**
* Create a new model instance that is existing.
*
* @param array $attributes
* @return Model
*/
public function newInstance($attributes = [], $exists = false);
/**
* Execute the query as a "select" statement.
*
* @param Criteria[]|Criteria $criteria
* @param array $columns
* @return \Illuminate\Support\Collection
*/
public function get($criteria = [], $columns = ['*']);
/**
* Chunk the results of the query.
*
* @param Criteria[]|Criteria $criteria
* @param int $count
* @return bool
*/
public function chunk($criteria, $count, callable $callback);
/**
* Execute a callback over each item while chunking.
*
* @param Criteria[]|Criteria $criteria
* @param int $count
* @return bool
*/
public function each($criteria, callable $callback, $count = 1000);
/**
* Execute the query and get the first result.
*
* @param Criteria[]|Criteria $criteria
* @param array $columns
* @return Model|static|null
*/
public function first($criteria = [], $columns = ['*']);
/**
* Paginate the given query.
*
* @param Criteria[]|Criteria $criteria
* @param int $perPage
* @param array $columns
* @param string $pageName
* @param int|null $page
* @return LengthAwarePaginator
*
* @throws InvalidArgumentException
*/
public function paginate($criteria = [], $perPage = null, $columns = ['*'], $pageName = 'page', $page = null);
/**
* Paginate the given query into a simple paginator.
*
* @param Criteria[]|Criteria $criteria
* @param int $perPage
* @param array $columns
* @param string $pageName
* @param int|null $page
* @return Paginator
*/
public function simplePaginate($criteria = [], $perPage = null, $columns = ['*'], $pageName = 'page', $page = null);
/**
* Retrieve the "count" result of the query.
*
* @param Criteria[]|Criteria $criteria
* @param string $columns
* @return int
*/
public function count($criteria = [], $columns = '*');
/**
* Retrieve the minimum value of a given column.
*
* @param Criteria[]|Criteria $criteria
* @param string $column
* @return mixed
*/
public function min($criteria, $column);
/**
* Retrieve the maximum value of a given column.
*
* @param Criteria[]|Criteria $criteria
* @param string $column
* @return mixed
*/
public function max($criteria, $column);
/**
* Retrieve the sum of the values of a given column.
*
* @param Criteria[]|Criteria $criteria
* @param string $column
* @return mixed
*/
public function sum($criteria, $column);
/**
* Retrieve the average of the values of a given column.
*
* @param Criteria[]|Criteria $criteria
* @param string $column
* @return mixed
*/
public function avg($criteria, $column);
/**
* Alias for the "avg" method.
*
* @param Criteria[]|Criteria $criteria
* @param string $column
* @return mixed
*/
public function average($criteria, $column);
/**
* matching.
*
* @param Criteria[]|Criteria $criteria
* @return Builder
*/
public function matching($criteria);
/**
* getQuery.
*
* @param Criteria[]|Criteria $criteria
* @return Builder
*/
public function getQuery($criteria = []);
/**
* getModel.
*
* @return Model
*/
public function getModel();
/**
* Get a new query builder for the model's table.
*
* @return Builder
*/
public function newQuery();
}
| php | MIT | d506fdc8c602e0ccaa52aea2d2f8ee3380dbbedd | 2026-01-05T05:08:03.638560Z | false |
recca0120/laravel-repository | https://github.com/recca0120/laravel-repository/blob/d506fdc8c602e0ccaa52aea2d2f8ee3380dbbedd/src/Concerns/SoftDeletingScope.php | src/Concerns/SoftDeletingScope.php | <?php
namespace Recca0120\Repository\Concerns;
use Recca0120\Repository\Method;
trait SoftDeletingScope
{
/**
* Add the with-trashed extension to the builder.
*
* @return $this
*/
public function withTrashed()
{
$this->methods[] = new Method(__FUNCTION__);
return $this;
}
/**
* Add the without-trashed extension to the builder.
*
* @return $this
*/
public function withoutTrashed()
{
$this->methods[] = new Method(__FUNCTION__);
return $this;
}
/**
* Add the only-trashed extension to the builder.
*
* @return $this
*/
public function onlyTrashed()
{
$this->methods[] = new Method(__FUNCTION__);
return $this;
}
}
| php | MIT | d506fdc8c602e0ccaa52aea2d2f8ee3380dbbedd | 2026-01-05T05:08:03.638560Z | false |
recca0120/laravel-repository | https://github.com/recca0120/laravel-repository/blob/d506fdc8c602e0ccaa52aea2d2f8ee3380dbbedd/tests/MethodTest.php | tests/MethodTest.php | <?php
namespace Recca0120\Repository\Tests;
use PHPUnit\Framework\TestCase;
use Recca0120\Repository\Method;
class MethodTest extends TestCase
{
public function test_instance()
{
$method = new Method('run', ['foo', 'bar']);
$this->assertInstanceOf(Method::class, $method);
$this->assertEquals('run', $method->name);
$this->assertEquals(['foo', 'bar'], $method->parameters);
}
}
| php | MIT | d506fdc8c602e0ccaa52aea2d2f8ee3380dbbedd | 2026-01-05T05:08:03.638560Z | false |
recca0120/laravel-repository | https://github.com/recca0120/laravel-repository/blob/d506fdc8c602e0ccaa52aea2d2f8ee3380dbbedd/tests/CollectionTest.php | tests/CollectionTest.php | <?php
namespace Recca0120\Repository\Tests;
use Illuminate\Database\Schema\Blueprint;
use PHPUnit\Framework\TestCase;
use Recca0120\Repository\CollectionModel;
use Recca0120\Repository\EloquentRepository;
class CollectionTest extends TestCase
{
public function test_find()
{
$fakeModel = new FakeCollectionModel;
$fakeRepository = new FakeCollectionRepository($fakeModel);
$instance = $fakeRepository->find(1);
$this->assertInstanceOf(FakeCollectionModel::class, $instance);
$this->assertTrue($instance->exists);
}
}
class FakeCollectionModel extends CollectionModel
{
protected $items = [
['id' => 1, 'foo' => 'bar'],
];
protected $fillable = [
'foo',
];
protected function createSchema(Blueprint $table)
{
$table->increments('id');
$table->string('foo');
$table->timestamps();
}
}
class FakeCollectionRepository extends EloquentRepository {}
| php | MIT | d506fdc8c602e0ccaa52aea2d2f8ee3380dbbedd | 2026-01-05T05:08:03.638560Z | false |
recca0120/laravel-repository | https://github.com/recca0120/laravel-repository/blob/d506fdc8c602e0ccaa52aea2d2f8ee3380dbbedd/tests/CriteriaTest.php | tests/CriteriaTest.php | <?php
namespace Recca0120\Repository\Tests;
use Illuminate\Database\Query\Grammars\MySqlGrammar;
use PHPUnit\Framework\TestCase;
use Recca0120\Repository\Criteria;
use Recca0120\Repository\Expression;
class CriteriaTest extends TestCase
{
public function test_instance()
{
$this->assertInstanceOf(Criteria::class, new Criteria);
}
public function test_create()
{
$criteria = Criteria::create();
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_expr()
{
$expression = Criteria::expr('foo = bar');
$this->assertInstanceOf(Expression::class, $expression);
$this->assertEquals('foo = bar', $expression->getValue(new MySqlGrammar));
}
public function test_dynamic_where()
{
$criteria = Criteria::create()->whereUrl('https://foo.com')->whereName('foo');
$this->assertEquals([
[
'method' => 'dynamicWhere',
'parameters' => ['whereUrl', ['https://foo.com']],
],
[
'method' => 'dynamicWhere',
'parameters' => ['whereName', ['foo']],
],
], $criteria->toArray());
}
}
| php | MIT | d506fdc8c602e0ccaa52aea2d2f8ee3380dbbedd | 2026-01-05T05:08:03.638560Z | false |
recca0120/laravel-repository | https://github.com/recca0120/laravel-repository/blob/d506fdc8c602e0ccaa52aea2d2f8ee3380dbbedd/tests/bootstrap.php | tests/bootstrap.php | <?php
/*
|--------------------------------------------------------------------------
| Register The Composer Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any our classes "manually". Feels great to relax.
|
*/
require __DIR__.'/../vendor/autoload.php';
use Carbon\Carbon;
if (class_exists('PHPUnit\Framework\TestCase') === false) {
class_alias('PHPUnit_Framework_TestCase', 'PHPUnit\Framework\TestCase');
}
/*
|--------------------------------------------------------------------------
| Set The Default Timezone
|--------------------------------------------------------------------------
|
| Here we will set the default timezone for PHP. PHP is notoriously mean
| if the timezone is not explicitly set. This will be used by each of
| the PHP date and date-time functions throughout the application.
|
*/
date_default_timezone_set('UTC');
Carbon::setTestNow(Carbon::now());
if (function_exists('env') === false) {
function env($env)
{
switch ($env) {
case 'APP_ENV':
return 'local';
break;
case 'APP_DEBUG':
return true;
break;
}
}
}
if (class_exists('Route') === false) {
class bootstrap
{
public static function __callStatic($method, $arguments)
{
return new static;
}
public function __call($method, $arguments) {}
}
}
| php | MIT | d506fdc8c602e0ccaa52aea2d2f8ee3380dbbedd | 2026-01-05T05:08:03.638560Z | false |
recca0120/laravel-repository | https://github.com/recca0120/laravel-repository/blob/d506fdc8c602e0ccaa52aea2d2f8ee3380dbbedd/tests/EloquentRepositoryTest.php | tests/EloquentRepositoryTest.php | <?php
namespace Recca0120\Repository\Tests;
use Faker\Factory as FakerFactory;
use Faker\Generator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Schema\Blueprint;
use PHPUnit\Framework\TestCase;
use Recca0120\Repository\Criteria;
use Recca0120\Repository\EloquentRepository;
use Recca0120\Repository\SqliteModel;
class EloquentRepositoryTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
$faker = FakerFactory::create();
$factory = new Factory($faker);
$factory->define(FakeModel::class, function (Generator $faker) {
return ['foo' => $faker->name];
});
$factory->of(FakeModel::class)->times(50)->create();
}
protected function tearDown(): void
{
parent::tearDown();
$fakeModel = new FakeModel;
$fakeModel->truncate();
}
public function test_find()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$instance = $fakeRepository->find(1);
$this->assertInstanceOf(FakeModel::class, $instance);
$this->assertTrue($instance->exists);
}
public function test_find_many()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$instances = $fakeRepository->findMany([1, 2]);
$instances->each(function ($instance) {
$this->assertInstanceOf(FakeModel::class, $instance);
$this->assertTrue($instance->exists);
});
}
public function test_find_or_fail()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$instance = $fakeRepository->findOrFail(1);
$this->assertInstanceOf(FakeModel::class, $instance);
$this->assertTrue($instance->exists);
}
public function test_find_or_new()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$instance = $fakeRepository->findOrNew(1000000);
$this->assertInstanceOf(FakeModel::class, $instance);
$this->assertFalse($instance->exists);
}
public function test_first_or_new()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$instance = $fakeRepository->firstOrNew(['id' => 10000], ['foo' => 'bar']);
$this->assertInstanceOf(FakeModel::class, $instance);
$this->assertEquals('bar', $instance->foo);
$this->assertFalse($instance->exists);
}
public function test_first_or_create()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$instance = $fakeRepository->firstOrCreate(['id' => 10000], ['foo' => 'bar']);
$this->assertInstanceOf(FakeModel::class, $instance);
$this->assertEquals('bar', $instance->foo);
$this->assertTrue($instance->exists);
}
public function test_update_or_create()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$instance = $fakeRepository->updateOrCreate(['id' => 1], ['foo' => 'bar']);
$this->assertInstanceOf(FakeModel::class, $instance);
$this->assertEquals('bar', $instance->foo);
$this->assertTrue($instance->exists);
}
public function test_first_or_fail()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$model = $fakeRepository->firstOrFail(Criteria::create()->where('id', '>', 0));
$this->assertInstanceOf('Illuminate\Database\Eloquent\Model', $model);
}
public function test_create()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$instance = $fakeRepository->create(['foo' => 'bar']);
$this->assertInstanceOf(Model::class, $instance);
$this->assertEquals('bar', $instance->foo);
$this->assertTrue($instance->exists);
}
public function test_force_create()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$instance = $fakeRepository->forceCreate(['foo' => 'bar']);
$this->assertInstanceOf(Model::class, $instance);
$this->assertEquals('bar', $instance->foo);
$this->assertTrue($instance->exists);
}
public function test_update()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$instance = $fakeRepository->update(1, ['id' => 50000, 'foo' => 'bar']);
$this->assertInstanceOf(Model::class, $instance);
$this->assertEquals('bar', $instance->foo);
$this->assertEquals(1, $instance->id);
$this->assertTrue($instance->exists);
}
public function test_force_update()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$instance = $fakeRepository->forceUpdate(1, ['id' => 50000, 'foo' => 'bar']);
$this->assertInstanceOf(Model::class, $instance);
$this->assertEquals('bar', $instance->foo);
$this->assertEquals(50000, $instance->id);
$this->assertTrue($instance->exists);
}
public function test_delete()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$this->assertTrue($fakeRepository->delete(1));
$this->assertNull($fakeRepository->find(1));
}
public function test_restore()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$fakeRepository->delete(1);
$this->assertNull($fakeRepository->find(1));
$this->assertEquals(1, $fakeRepository->get(Criteria::create()->whereIn('id', [1, 2]))->count());
$this->assertEquals(2, $fakeRepository->get(Criteria::create()->whereIn('id', [1, 2])->withTrashed())->count());
$this->assertEquals(1, $fakeRepository->get(Criteria::create()->whereIn('id', [1, 2])->onlyTrashed())->count());
$fakeRepository->restore(1);
$this->assertNotNull($fakeRepository->find(1));
}
public function test_force_delete()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$this->assertTrue($fakeRepository->forceDelete(1));
}
public function test_new_instance()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$instance = $fakeRepository->newInstance(['foo' => 'bar']);
$this->assertInstanceOf(FakeModel::class, $instance);
$this->assertEquals('bar', $instance->foo);
$this->assertFalse($instance->exists);
}
public function test_matching()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$criteria = [
Criteria::create()->whereIn('id', [5, 9]),
Criteria::create()->orWhereIn('id', [1, 3]),
Criteria::create()->orderBy('id'),
];
$this->assertEquals(
FakeModel::query()->whereIn('id', [5, 9])->orWhereIn('id', [1, 3])->orderBY('id')->get()->toArray(),
$fakeRepository->matching($criteria)->get()->toArray()
);
}
public function test_get()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$criteria = [
Criteria::create()->where(function ($query) {
$query->whereIn('id', [1, 3])->orWhereIn('id', [5, 9]);
}),
Criteria::create()->orderBy('id'),
];
$this->assertEquals(
FakeModel::query()->whereIn('id', [5, 9])->orWhereIn('id', [1, 3])->orderBY('id')->get()->toArray(),
$fakeRepository->get($criteria)->toArray()
);
}
public function test_chunk()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$fakeRepository->chunk(Criteria::create()->where('id', '>', Criteria::expr(0)), 10, function ($collection) {
$this->assertEquals(10, $collection->count());
});
}
public function test_each()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$fakeRepository->each(Criteria::create()->where('id', '>', Criteria::raw(0)), function ($model) {
$this->assertInstanceOf(Model::class, $model);
});
}
public function test_first()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$model = $fakeRepository->first(Criteria::create()->where('id', '>', 0));
$this->assertInstanceOf(Model::class, $model);
}
public function test_paginate()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$paginate = $fakeRepository->paginate(Criteria::create()->where('id', '>', 0));
$this->assertEquals(1, $paginate->currentPage());
}
public function test_simple_paginate()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$paginate = $fakeRepository->simplePaginate(Criteria::create()->where('id', '>', 0));
$this->assertEquals(1, $paginate->currentPage());
}
public function test_count()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$this->assertEquals(50, $fakeRepository->count(Criteria::create()->where('id', '>', 0)));
}
public function test_min()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$this->assertEquals(10, $fakeRepository->min(Criteria::create()->where('id', '>=', 10), 'id'));
}
public function test_max()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$this->assertEquals(10, $fakeRepository->max(Criteria::create()->where('id', '<=', 10), 'id'));
}
public function test_sum()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$this->assertEquals(55, $fakeRepository->sum(Criteria::create()->whereBetween('id', [1, 10]), 'id'));
}
public function test_average()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$this->assertEquals(5.5, $fakeRepository->average(Criteria::create()->whereBetween('id', [1, 10]), 'id'));
}
public function test_model_is_query()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository2($fakeModel);
$this->assertEquals(5.5, $fakeRepository->average([], 'id'));
}
public function test_get_query()
{
$fakeModel = new FakeModel;
$fakeRepository = new FakeRepository($fakeModel);
$this->assertEquals(
$fakeRepository->getQuery([
Criteria::create()->where(function ($query) {
$query->whereIn('id', [1, 3])->orWhereIn('id', [5, 9]);
}),
Criteria::create()->orderBy('id'),
])->get()->toArray(),
FakeModel::query()
->whereIn('id', [5, 9])
->orWhereIn('id', [1, 3])
->orderBY('id')
->getQuery()
->get()
->toArray()
);
}
}
/**
* @mixin Builder
*/
class FakeModel extends SqliteModel
{
use SoftDeletes;
protected $table = 'fake_models';
protected $fillable = [
'foo',
];
protected function createSchema(Blueprint $table)
{
$table->increments('id');
$table->string('foo');
$table->timestamps();
$table->softDeletes();
}
}
class FakeRepository extends EloquentRepository {}
class FakeRepository2 extends EloquentRepository
{
public function __construct(Model $model)
{
parent::__construct($model);
$this->model = $this->model->whereBetween('id', [1, 10]);
}
}
| php | MIT | d506fdc8c602e0ccaa52aea2d2f8ee3380dbbedd | 2026-01-05T05:08:03.638560Z | false |
recca0120/laravel-repository | https://github.com/recca0120/laravel-repository/blob/d506fdc8c602e0ccaa52aea2d2f8ee3380dbbedd/tests/Concerns/QueriesRelationshipsTest.php | tests/Concerns/QueriesRelationshipsTest.php | <?php
namespace Recca0120\Repository\Tests\Concerns;
use Illuminate\Database\Eloquent\Builder;
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
use Mockery as m;
use PHPUnit\Framework\TestCase;
use Recca0120\Repository\Criteria;
class QueriesRelationshipsTest extends TestCase
{
use MockeryPHPUnitIntegration;
public function test_has()
{
$criteria = Criteria::create()->has(
$relation = 'foo',
$operator = '<=',
$count = 2,
$boolean = 'or',
$callback = function () {}
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'has',
'parameters' => [$relation, $operator, $count, $boolean, $callback],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_or_has()
{
$criteria = Criteria::create()->orHas(
$relation = 'foo',
$operator = '<=',
$count = 2
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'orHas',
'parameters' => [$relation, $operator, $count],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_doesnt_have()
{
$criteria = Criteria::create()->doesntHave(
$relation = 'foo',
$boolean = 'or',
$callback = function () {}
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'doesntHave',
'parameters' => [$relation, $boolean, $callback],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_where_has()
{
$criteria = Criteria::create()->whereHas(
$relation = 'foo',
$callback = function () {},
$operator = '<=',
$count = 2
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'whereHas',
'parameters' => [$relation, $callback, $operator, $count],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_or_where_has()
{
$criteria = Criteria::create()->orWhereHas(
$relation = 'foo',
$callback = function () {},
$operator = '<=',
$count = 2
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'orWhereHas',
'parameters' => [$relation, $callback, $operator, $count],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_where_doesnt_have()
{
$criteria = Criteria::create()->whereDoesntHave(
$relation = 'foo',
$callback = function () {}
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'whereDoesntHave',
'parameters' => [$relation, $callback],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_with_count()
{
$criteria = Criteria::create()->withCount(
$relation = 'foo'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'withCount',
'parameters' => [$relation],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_with_max()
{
$criteria = Criteria::create()->withMax(
$relation = 'foo',
$column = 'bar'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'withMax',
'parameters' => [$relation, $column],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_with_min()
{
$criteria = Criteria::create()->withMin(
$relation = 'foo',
$column = 'bar'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'withMin',
'parameters' => [$relation, $column],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_with_sum()
{
$criteria = Criteria::create()->withSum(
$relation = 'foo',
$column = 'bar'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'withSum',
'parameters' => [$relation, $column],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_merge_constraints_from()
{
$criteria = Criteria::create()->mergeConstraintsFrom(
$from = m::mock(Builder::class)
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'mergeConstraintsFrom',
'parameters' => [$from],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
}
| php | MIT | d506fdc8c602e0ccaa52aea2d2f8ee3380dbbedd | 2026-01-05T05:08:03.638560Z | false |
recca0120/laravel-repository | https://github.com/recca0120/laravel-repository/blob/d506fdc8c602e0ccaa52aea2d2f8ee3380dbbedd/tests/Concerns/BuildsQueriesTest.php | tests/Concerns/BuildsQueriesTest.php | <?php
namespace Recca0120\Repository\Tests\Concerns;
use Illuminate\Database\Query\Builder;
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
use Mockery as m;
use PHPUnit\Framework\TestCase;
use Recca0120\Repository\Criteria;
class BuildsQueriesTest extends TestCase
{
use MockeryPHPUnitIntegration;
public function test_select()
{
$criteria = Criteria::create()->select($columns = ['foo', 'bar']);
$this->assertEquals($criteria->toArray(), [[
'method' => 'select',
'parameters' => [$columns],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_select_raw()
{
$criteria = Criteria::create()->selectRaw(
$expression = 'MAX(id)',
$bindings = ['foo', 'bar']
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'selectRaw',
'parameters' => [$expression, $bindings],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_select_sub()
{
$criteria = Criteria::create()->selectSub(
$query = 'SELECT * FROM table',
$as = 'foo'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'selectSub',
'parameters' => [$query, $as],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_add_select()
{
$criteria = Criteria::create()->addSelect(
$column = ['foo']
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'addSelect',
'parameters' => [$column],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_distinct()
{
$criteria = Criteria::create()->distinct();
$this->assertEquals($criteria->toArray(), [[
'method' => 'distinct',
'parameters' => [],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_from()
{
$criteria = Criteria::create()->from(
$table = 'table'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'from',
'parameters' => [$table],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_join()
{
$criteria = Criteria::create()->join(
$table = 'table',
$first = 'first',
$operator = '=',
$second = 'second',
$type = 'left join',
$where = 'first.id = second.id'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'join',
'parameters' => [$table, $first, $operator, $second, $type, $where],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_join_where()
{
$criteria = Criteria::create()->joinWhere(
$table = 'table',
$first = 'first',
$operator = '=',
$second = 'second',
$type = 'left join'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'joinWhere',
'parameters' => [$table, $first, $operator, $second, $type],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_left_join()
{
$criteria = Criteria::create()->leftJoin(
$table = 'table',
$first = 'first',
$operator = '=',
$second = 'second'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'leftJoin',
'parameters' => [$table, $first, $operator, $second],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_left_join_where()
{
$criteria = Criteria::create()->leftJoinWhere(
$table = 'table',
$first = 'first',
$operator = '=',
$second = 'second'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'leftJoinWhere',
'parameters' => [$table, $first, $operator, $second],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_right_join()
{
$criteria = Criteria::create()->rightJoin(
$table = 'table',
$first = 'first',
$operator = '=',
$second = 'second'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'rightJoin',
'parameters' => [$table, $first, $operator, $second],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_right_join_where()
{
$criteria = Criteria::create()->rightJoinWhere(
$table = 'table',
$first = 'first',
$operator = '=',
$second = 'second'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'rightJoinWhere',
'parameters' => [$table, $first, $operator, $second],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_cross_join()
{
$criteria = Criteria::create()->crossJoin(
$table = 'table',
$first = 'first',
$operator = '=',
$second = 'second'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'crossJoin',
'parameters' => [$table, $first, $operator, $second],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_tap()
{
$criteria = Criteria::create()->tap($callback = function () {});
$this->assertEquals($criteria->toArray(), [[
'method' => 'tap',
'parameters' => [$callback],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_where()
{
$criteria = Criteria::create()->where(
$column = 'foo',
$operator = '=',
$value = '1',
$boolean = 'or'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'where',
'parameters' => [$column, $operator, $value, $boolean],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_or_where()
{
$criteria = Criteria::create()->orWhere(
$column = 'foo',
$operator = '=',
$value = '1'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'orWhere',
'parameters' => [$column, $operator, $value],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_where_column()
{
$criteria = Criteria::create()->whereColumn(
$first = 'foo',
$operator = '=',
$second = 'bar',
$boolean = 'or'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'whereColumn',
'parameters' => [$first, $operator, $second, $boolean],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_or_where_column()
{
$criteria = Criteria::create()->orWhereColumn(
$first = 'foo',
$operator = '=',
$second = 'bar'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'orWhereColumn',
'parameters' => [$first, $operator, $second],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_where_raw()
{
$criteria = Criteria::create()->whereRaw(
$sql = 'SELECT * FROM table',
$bindings = ['foo', 'bar'],
$boolean = 'or'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'whereRaw',
'parameters' => [$sql, $bindings, $boolean],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_or_where_raw()
{
$criteria = Criteria::create()->orWhereRaw(
$sql = 'SELECT * FROM table',
$bindings = ['foo', 'bar']
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'orWhereRaw',
'parameters' => [$sql, $bindings],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_where_in()
{
$criteria = Criteria::create()->whereIn(
$column = 'foo',
$values = ['foo', 'bar'],
$boolean = 'or',
$not = true
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'whereIn',
'parameters' => [$column, $values, $boolean, $not],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_or_where_in()
{
$criteria = Criteria::create()->orWhereIn(
$column = 'foo',
$values = ['foo', 'bar']
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'orWhereIn',
'parameters' => [$column, $values],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_where_not_in()
{
$criteria = Criteria::create()->whereNotIn(
$column = 'foo',
$values = ['foo', 'bar'],
$boolean = 'or'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'whereNotIn',
'parameters' => [$column, $values, $boolean],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_or_where_not_in()
{
$criteria = Criteria::create()->orWhereNotIn(
$column = 'foo',
$values = ['foo', 'bar']
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'orWhereNotIn',
'parameters' => [$column, $values],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_where_null()
{
$criteria = Criteria::create()->whereNull(
$column = 'foo',
$boolean = 'or',
$not = true
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'whereNull',
'parameters' => [$column, $boolean, $not],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_or_where_null()
{
$criteria = Criteria::create()->orWhereNull(
$column = 'foo'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'orWhereNull',
'parameters' => [$column],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_where_not_null()
{
$criteria = Criteria::create()->whereNotNull(
$column = 'foo',
$boolean = 'or'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'whereNotNull',
'parameters' => [$column, $boolean],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_where_between()
{
$criteria = Criteria::create()->whereBetween(
$column = 'foo',
$values = ['foo', 'bar'],
$boolean = 'or',
$not = true
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'whereBetween',
'parameters' => [$column, $values, $boolean, $not],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_or_where_between()
{
$criteria = Criteria::create()->orWhereBetween(
$column = 'foo',
$values = ['foo', 'bar']
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'orWhereBetween',
'parameters' => [$column, $values],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_where_not_between()
{
$criteria = Criteria::create()->whereNotBetween(
$column = 'foo',
$values = ['foo', 'bar'],
$boolean = 'or'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'whereNotBetween',
'parameters' => [$column, $values, $boolean],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_or_where_not_between()
{
$criteria = Criteria::create()->orWhereNotBetween(
$column = 'foo',
$values = ['foo', 'bar']
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'orWhereNotBetween',
'parameters' => [$column, $values],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_or_where_not_null()
{
$criteria = Criteria::create()->orWhereNotNull(
$column = 'foo'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'orWhereNotNull',
'parameters' => [$column],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_where_date()
{
$criteria = Criteria::create()->whereDate(
$column = 'foo',
$operator = '=',
$value = '20170721',
$boolean = 'or'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'whereDate',
'parameters' => [$column, $operator, $value, $boolean],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_or_where_date()
{
$criteria = Criteria::create()->orWhereDate(
$column = 'foo',
$operator = '=',
$value = '20170721'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'orWhereDate',
'parameters' => [$column, $operator, $value],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_where_time()
{
$criteria = Criteria::create()->whereTime(
$column = 'foo',
$operator = '=',
$value = '11:11:11',
$boolean = 'or'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'whereTime',
'parameters' => [$column, $operator, $value, $boolean],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_or_where_time()
{
$criteria = Criteria::create()->orWhereTime(
$column = 'foo',
$operator = '=',
$value = '11:11:11'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'orWhereTime',
'parameters' => [$column, $operator, $value],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_where_day()
{
$criteria = Criteria::create()->whereDay(
$column = 'foo',
$operator = '=',
$value = '01',
$boolean = 'or'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'whereDay',
'parameters' => [$column, $operator, $value, $boolean],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_where_month()
{
$criteria = Criteria::create()->whereMonth(
$column = 'foo',
$operator = '=',
$value = '01',
$boolean = 'or'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'whereMonth',
'parameters' => [$column, $operator, $value, $boolean],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_where_year()
{
$criteria = Criteria::create()->whereYear(
$column = 'foo',
$operator = '=',
$value = '01',
$boolean = 'or'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'whereYear',
'parameters' => [$column, $operator, $value, $boolean],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_where_nested()
{
$criteria = Criteria::create()->whereNested(
$callback = function () {},
$boolean = 'or'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'whereNested',
'parameters' => [$callback, $boolean],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_add_nested_where_query()
{
$criteria = Criteria::create()->addNestedWhereQuery(
$query = m::mock(Builder::class),
$boolean = 'or'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'addNestedWhereQuery',
'parameters' => [$query, $boolean],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_where_exists()
{
$criteria = Criteria::create()->whereExists(
$callback = function () {},
$boolean = 'or',
$not = true
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'whereExists',
'parameters' => [$callback, $boolean, $not],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_or_where_exists()
{
$criteria = Criteria::create()->orWhereExists(
$callback = function () {},
$not = true
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'orWhereExists',
'parameters' => [$callback, $not],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_where_not_exists()
{
$criteria = Criteria::create()->whereNotExists(
$callback = function () {},
$boolean = 'or'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'whereNotExists',
'parameters' => [$callback, $boolean],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_or_where_not_exists()
{
$criteria = Criteria::create()->orWhereNotExists(
$callback = function () {}
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'orWhereNotExists',
'parameters' => [$callback],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_add_where_exists_query()
{
$criteria = Criteria::create()->addWhereExistsQuery(
$query = m::mock('Illuminate\Database\Query\Builder'),
$boolean = 'or',
$not = true
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'addWhereExistsQuery',
'parameters' => [$query, $boolean, $not],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_dynamic_where()
{
$criteria = Criteria::create()->dynamicWhere(
$method = m::mock(Builder::class),
$parameters = ['foo', 'bar']
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'dynamicWhere',
'parameters' => [$method, $parameters],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_group_by()
{
$criteria = Criteria::create()->groupBy(
$group = 'a',
$group2 = 'b',
$group3 = 'c'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'groupBy',
'parameters' => [$group, $group2, $group3],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_having()
{
$criteria = Criteria::create()->having(
$column = 'foo',
$operator = '=',
$value = 'bar',
$boolean = 'or'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'having',
'parameters' => [$column, $operator, $value, $boolean],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_or_having()
{
$criteria = Criteria::create()->orHaving(
$column = 'foo',
$operator = '=',
$value = 'bar'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'orHaving',
'parameters' => [$column, $operator, $value],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_having_raw()
{
$criteria = Criteria::create()->havingRaw(
$sql = 'SELECT * FROM ? = ?',
$bindings = ['foo', 'bar'],
$boolean = 'or'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'havingRaw',
'parameters' => [$sql, $bindings, $boolean],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_or_having_raw()
{
$criteria = Criteria::create()->orHavingRaw(
$sql = 'SELECT * FROM ? = ?',
$bindings = ['foo', 'bar']
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'orHavingRaw',
'parameters' => [$sql, $bindings],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_order_by()
{
$criteria = Criteria::create()->orderBy(
$column = 'foo',
$direction = 'desc'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'orderBy',
'parameters' => [$column, $direction],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_order_desc()
{
$criteria = Criteria::create()->orderByDesc(
$column = 'foo'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'orderByDesc',
'parameters' => [$column],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_latest()
{
$criteria = Criteria::create()->latest(
$column = 'foo'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'latest',
'parameters' => [$column],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_oldest()
{
$criteria = Criteria::create()->oldest(
$column = 'foo'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'oldest',
'parameters' => [$column],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_in_random_order()
{
$criteria = Criteria::create()->inRandomOrder(
$column = 'foo'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'inRandomOrder',
'parameters' => [$column],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_order_by_raw()
{
$criteria = Criteria::create()->orderByRaw(
$sql = 'ORDER BY ? DESC',
$binding = ['foo']
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'orderByRaw',
'parameters' => [$sql, $binding],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_skip()
{
$criteria = Criteria::create()->skip(
$value = 5
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'skip',
'parameters' => [$value],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_offset()
{
$criteria = Criteria::create()->offset(
$value = 5
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'offset',
'parameters' => [$value],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_take()
{
$criteria = Criteria::create()->take(
$value = 5
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'take',
'parameters' => [$value],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_limit()
{
$criteria = Criteria::create()->limit(
$value = 5
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'limit',
'parameters' => [$value],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_for_page()
{
$criteria = Criteria::create()->forPage(
$page = 5,
$perPage = 10
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'forPage',
'parameters' => [$page, $perPage],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_for_page_after_id()
{
$criteria = Criteria::create()->forPageAfterId(
$perPage = 10,
$lastId = 1,
$column = 'foo'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'forPageAfterId',
'parameters' => [$perPage, $lastId, $column],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_union()
{
$criteria = Criteria::create()->union(
$query = 'SELECT * FROM table',
$all = true
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'union',
'parameters' => [$query, $all],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_union_all()
{
$criteria = Criteria::create()->unionAll(
$query = 'SELECT * FROM table'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'unionAll',
'parameters' => [$query],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_lock()
{
$criteria = Criteria::create()->lock(
$value = false
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'lock',
'parameters' => [$value],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_lock_for_update()
{
$criteria = Criteria::create()->lockForUpdate();
$this->assertEquals($criteria->toArray(), [[
'method' => 'lockForUpdate',
'parameters' => [],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_shared_lock()
{
$criteria = Criteria::create()->sharedLock();
$this->assertEquals($criteria->toArray(), [[
'method' => 'sharedLock',
'parameters' => [],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_when()
{
$criteria = Criteria::create()->when(
$value = true,
$callback = function () {},
$default = function () {}
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'when',
'parameters' => [$value, $callback, $default],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_unless()
{
$criteria = Criteria::create()->unless(
$value = true,
$callback = function () {},
$default = function () {}
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'unless',
'parameters' => [$value, $callback, $default],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_use_write_pdo()
{
$criteria = Criteria::create()->useWritePdo();
$this->assertEquals($criteria->toArray(), [[
'method' => 'useWritePdo',
'parameters' => [],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
}
| php | MIT | d506fdc8c602e0ccaa52aea2d2f8ee3380dbbedd | 2026-01-05T05:08:03.638560Z | false |
recca0120/laravel-repository | https://github.com/recca0120/laravel-repository/blob/d506fdc8c602e0ccaa52aea2d2f8ee3380dbbedd/tests/Concerns/EloquentBuildsQueriesTest.php | tests/Concerns/EloquentBuildsQueriesTest.php | <?php
namespace Recca0120\Repository\Tests\Concerns;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Query\Builder;
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
use Mockery as m;
use PHPUnit\Framework\TestCase;
use Recca0120\Repository\Criteria;
class EloquentBuildsQueriesTest extends TestCase
{
use MockeryPHPUnitIntegration;
public function test_where_key()
{
$criteria = Criteria::create()->whereKey($id = 'foo');
$this->assertEquals($criteria->toArray(), [[
'method' => 'whereKey',
'parameters' => [$id],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_where_key_not()
{
$criteria = Criteria::create()->whereKeyNot($id = 'foo');
$this->assertEquals($criteria->toArray(), [[
'method' => 'whereKeyNot',
'parameters' => [$id],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_with()
{
$criteria = Criteria::create()->with(
$relations = 'foo'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'with',
'parameters' => [$relations],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_without()
{
$criteria = Criteria::create()->without(
$relations = 'foo'
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'without',
'parameters' => [$relations],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_set_query()
{
$criteria = Criteria::create()->setQuery(
$query = m::mock(Builder::class)
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'setQuery',
'parameters' => [$query],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_set_model()
{
$criteria = Criteria::create()->setModel(
$model = m::mock(Model::class)
);
$this->assertEquals($criteria->toArray(), [[
'method' => 'setModel',
'parameters' => [$model],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
public function test_on_write_connection()
{
$criteria = Criteria::create()->onWriteConnection();
$this->assertEquals($criteria->toArray(), [[
'method' => 'useWritePdo',
'parameters' => [],
]]);
$this->assertInstanceOf(Criteria::class, $criteria);
}
}
| php | MIT | d506fdc8c602e0ccaa52aea2d2f8ee3380dbbedd | 2026-01-05T05:08:03.638560Z | false |
ThePixelDeveloper/Sitemap | https://github.com/ThePixelDeveloper/Sitemap/blob/ee4cbd1406f1250534860b8c9b74020fee0c3650/src/Sitemap.php | src/Sitemap.php | <?php declare(strict_types=1);
namespace Thepixeldeveloper\Sitemap;
use DateTimeInterface;
use Thepixeldeveloper\Sitemap\Interfaces\DriverInterface;
use Thepixeldeveloper\Sitemap\Interfaces\VisitorInterface;
class Sitemap implements VisitorInterface
{
/**
* Location (URL).
*
* @var string
*/
private $loc;
/**
* Last modified time.
*
* @var DateTimeInterface
*/
private $lastMod;
public function __construct(string $loc)
{
$this->loc = $loc;
}
/**
* @return string
*/
public function getLoc(): string
{
return $this->loc;
}
/**
* @return DateTimeInterface|null
*/
public function getLastMod()
{
return $this->lastMod;
}
/**
* @param DateTimeInterface $lastMod
*/
public function setLastMod(DateTimeInterface $lastMod)
{
$this->lastMod = $lastMod;
}
public function accept(DriverInterface $driver)
{
$driver->visitSitemap($this);
}
}
| php | MIT | ee4cbd1406f1250534860b8c9b74020fee0c3650 | 2026-01-05T05:08:07.161661Z | false |
ThePixelDeveloper/Sitemap | https://github.com/ThePixelDeveloper/Sitemap/blob/ee4cbd1406f1250534860b8c9b74020fee0c3650/src/Collection.php | src/Collection.php | <?php declare(strict_types=1);
namespace Thepixeldeveloper\Sitemap;
use Thepixeldeveloper\Sitemap\Interfaces\VisitorInterface;
abstract class Collection implements VisitorInterface
{
/**
* @var VisitorInterface[]
*/
private $items = [];
public function add(VisitorInterface $value)
{
$type = $this->type();
if ($value instanceof $type) {
$this->items[] = $value;
} else {
throw new \InvalidArgumentException('$value needs to be an instance of ' . $type);
}
}
/**
* @return VisitorInterface[]
*/
public function all(): array
{
return $this->items;
}
abstract public function type(): string;
}
| php | MIT | ee4cbd1406f1250534860b8c9b74020fee0c3650 | 2026-01-05T05:08:07.161661Z | false |
ThePixelDeveloper/Sitemap | https://github.com/ThePixelDeveloper/Sitemap/blob/ee4cbd1406f1250534860b8c9b74020fee0c3650/src/SitemapIndex.php | src/SitemapIndex.php | <?php declare(strict_types=1);
namespace Thepixeldeveloper\Sitemap;
use Thepixeldeveloper\Sitemap\Interfaces\DriverInterface;
class SitemapIndex extends Collection
{
public function type(): string
{
return Sitemap::class;
}
public function accept(DriverInterface $driver)
{
$driver->visitSitemapIndex($this);
}
}
| php | MIT | ee4cbd1406f1250534860b8c9b74020fee0c3650 | 2026-01-05T05:08:07.161661Z | false |
ThePixelDeveloper/Sitemap | https://github.com/ThePixelDeveloper/Sitemap/blob/ee4cbd1406f1250534860b8c9b74020fee0c3650/src/ChunkedUrlset.php | src/ChunkedUrlset.php | <?php declare(strict_types=1);
namespace Thepixeldeveloper\Sitemap;
class ChunkedUrlset extends ChunkedCollection
{
protected function getCollectionClass(): Collection
{
return new Urlset();
}
}
| php | MIT | ee4cbd1406f1250534860b8c9b74020fee0c3650 | 2026-01-05T05:08:07.161661Z | false |
ThePixelDeveloper/Sitemap | https://github.com/ThePixelDeveloper/Sitemap/blob/ee4cbd1406f1250534860b8c9b74020fee0c3650/src/ChunkedCollection.php | src/ChunkedCollection.php | <?php declare(strict_types=1);
namespace Thepixeldeveloper\Sitemap;
use Thepixeldeveloper\Sitemap\Interfaces\VisitorInterface;
abstract class ChunkedCollection
{
const LIMIT = 50000;
/**
* @var Collection[]
*/
private $collections;
/**
* @var int
*/
private $count;
/**
* SitemapSplitter constructor.
*/
public function __construct()
{
$this->collections = [];
$this->count = 0;
}
public function add(VisitorInterface $visitor)
{
if ($this->count === 0 || $this->count === self::LIMIT) {
$this->count = 0; $this->collections[] = $this->getCollectionClass();
}
$this->collections[count($this->collections) - 1]->add($visitor);
$this->count++;
}
/**
* @return Collection[]
*/
public function getCollections(): array
{
return $this->collections;
}
abstract protected function getCollectionClass(): Collection;
}
| php | MIT | ee4cbd1406f1250534860b8c9b74020fee0c3650 | 2026-01-05T05:08:07.161661Z | false |
ThePixelDeveloper/Sitemap | https://github.com/ThePixelDeveloper/Sitemap/blob/ee4cbd1406f1250534860b8c9b74020fee0c3650/src/Url.php | src/Url.php | <?php declare(strict_types=1);
namespace Thepixeldeveloper\Sitemap;
use DateTimeInterface;
use Thepixeldeveloper\Sitemap\Interfaces\DriverInterface;
use Thepixeldeveloper\Sitemap\Interfaces\VisitorInterface;
class Url implements VisitorInterface
{
/**
* Location (URL).
*
* @var string
*/
private $loc;
/**
* Last modified time.
*
* @var DateTimeInterface
*/
private $lastMod;
/**
* Change frequency of the location.
*
* @var string
*/
private $changeFreq;
/**
* Priority of page importance.
*
* @var string
*/
private $priority;
/**
* Array of sub-elements.
*
* @var VisitorInterface[]
*/
private $extensions = [];
public function __construct(string $loc)
{
$this->loc = $loc;
}
/**
* @return string
*/
public function getLoc(): string
{
return $this->loc;
}
/**
* @return DateTimeInterface|null
*/
public function getLastMod()
{
return $this->lastMod;
}
/**
* @param DateTimeInterface $lastMod
*/
public function setLastMod(DateTimeInterface $lastMod)
{
$this->lastMod = $lastMod;
}
/**
* @return string
*/
public function getChangeFreq()
{
return $this->changeFreq;
}
/**
* @param string $changeFreq
*/
public function setChangeFreq(string $changeFreq)
{
$this->changeFreq = $changeFreq;
}
/**
* @return string
*/
public function getPriority()
{
return $this->priority;
}
/**
* @param string $priority
*/
public function setPriority(string $priority)
{
$this->priority = $priority;
}
/**
* @param VisitorInterface $extension
*/
public function addExtension(VisitorInterface $extension)
{
$this->extensions[] = $extension;
}
/**
* @return VisitorInterface[]
*/
public function getExtensions(): array
{
return $this->extensions;
}
public function accept(DriverInterface $driver)
{
$driver->visitUrl($this);
}
}
| php | MIT | ee4cbd1406f1250534860b8c9b74020fee0c3650 | 2026-01-05T05:08:07.161661Z | false |
ThePixelDeveloper/Sitemap | https://github.com/ThePixelDeveloper/Sitemap/blob/ee4cbd1406f1250534860b8c9b74020fee0c3650/src/Urlset.php | src/Urlset.php | <?php declare(strict_types=1);
namespace Thepixeldeveloper\Sitemap;
use Thepixeldeveloper\Sitemap\Interfaces\DriverInterface;
class Urlset extends Collection
{
public function type(): string
{
return Url::class;
}
public function accept(DriverInterface $driver)
{
$driver->visitUrlset($this);
}
}
| php | MIT | ee4cbd1406f1250534860b8c9b74020fee0c3650 | 2026-01-05T05:08:07.161661Z | false |
ThePixelDeveloper/Sitemap | https://github.com/ThePixelDeveloper/Sitemap/blob/ee4cbd1406f1250534860b8c9b74020fee0c3650/src/Interfaces/DriverInterface.php | src/Interfaces/DriverInterface.php | <?php declare(strict_types=1);
namespace Thepixeldeveloper\Sitemap\Interfaces;
use Thepixeldeveloper\Sitemap\Extensions\Image;
use Thepixeldeveloper\Sitemap\Extensions\Link;
use Thepixeldeveloper\Sitemap\Extensions\Mobile;
use Thepixeldeveloper\Sitemap\Extensions\News;
use Thepixeldeveloper\Sitemap\Extensions\Video;
use Thepixeldeveloper\Sitemap\Sitemap;
use Thepixeldeveloper\Sitemap\SitemapIndex;
use Thepixeldeveloper\Sitemap\Url;
use Thepixeldeveloper\Sitemap\Urlset;
interface DriverInterface
{
public function visitSitemapIndex(SitemapIndex $sitemapIndex);
public function visitSitemap(Sitemap $sitemap);
public function visitUrlset(Urlset $urlset);
public function visitUrl(Url $url);
public function visitImageExtension(Image $image);
public function visitLinkExtension(Link $link);
public function visitMobileExtension(Mobile $mobile);
public function visitNewsExtension(News $news);
public function visitVideoExtension(Video $video);
public function output(): string;
}
| php | MIT | ee4cbd1406f1250534860b8c9b74020fee0c3650 | 2026-01-05T05:08:07.161661Z | false |
ThePixelDeveloper/Sitemap | https://github.com/ThePixelDeveloper/Sitemap/blob/ee4cbd1406f1250534860b8c9b74020fee0c3650/src/Interfaces/VisitorInterface.php | src/Interfaces/VisitorInterface.php | <?php declare(strict_types=1);
namespace Thepixeldeveloper\Sitemap\Interfaces;
interface VisitorInterface
{
public function accept(DriverInterface $driver);
}
| php | MIT | ee4cbd1406f1250534860b8c9b74020fee0c3650 | 2026-01-05T05:08:07.161661Z | false |
ThePixelDeveloper/Sitemap | https://github.com/ThePixelDeveloper/Sitemap/blob/ee4cbd1406f1250534860b8c9b74020fee0c3650/src/Drivers/XmlWriterDriver.php | src/Drivers/XmlWriterDriver.php | <?php declare(strict_types=1);
namespace Thepixeldeveloper\Sitemap\Drivers;
use Thepixeldeveloper\Sitemap\Extensions\Image;
use Thepixeldeveloper\Sitemap\Extensions\Link;
use Thepixeldeveloper\Sitemap\Extensions\Mobile;
use Thepixeldeveloper\Sitemap\Extensions\News;
use Thepixeldeveloper\Sitemap\Extensions\Video;
use Thepixeldeveloper\Sitemap\Interfaces\DriverInterface;
use Thepixeldeveloper\Sitemap\Sitemap;
use Thepixeldeveloper\Sitemap\SitemapIndex;
use Thepixeldeveloper\Sitemap\Url;
use Thepixeldeveloper\Sitemap\Urlset;
use XMLWriter;
/**
* Class XmlWriterDriver
*
* Because this driver is forward only (can't go back and
* define additional attributes) there's some logic
*
* @package Thepixeldeveloper\Sitemap\Drivers
*/
class XmlWriterDriver implements DriverInterface
{
/**
* @var XMLWriter
*/
private $writer;
/**
* @var array
*/
private $extensionAttributes = [
Video::class => [
'name' => 'xmlns:video',
'content' => 'http://www.google.com/schemas/sitemap-video/1.1',
],
News::class => [
'name' => 'xmlns:news',
'content' => 'http://www.google.com/schemas/sitemap-news/0.9',
],
Mobile::class => [
'name' => 'xmlns:mobile',
'content' => 'http://www.google.com/schemas/sitemap-mobile/1.0',
],
Link::class => [
'name' => 'xmlns:xhtml',
'content' => 'http://www.w3.org/1999/xhtml',
],
Image::class => [
'name' => 'xmlns:image',
'content' => 'http://www.google.com/schemas/sitemap-image/1.1',
],
];
/**
* @var array
*/
private $extensions = [];
/**
* XmlWriterDriver constructor.
*/
public function __construct()
{
$writer = new XMLWriter();
$writer->openMemory();
$writer->startDocument('1.0', 'UTF-8');
$this->writer = $writer;
}
public function addProcessingInstructions(string $target, string $content)
{
$this->writer->writePI($target, $content);
}
public function addComment(string $comment)
{
$this->writer->writeComment($comment);
}
private function writeElement(string $name, $content)
{
if (!$content) {
return;
}
if ($content instanceof \DateTimeInterface) {
$this->writer->writeElement($name, $content->format(DATE_W3C));
} else {
$this->writer->writeElement($name, (string) $content);
}
}
public function visitSitemapIndex(SitemapIndex $sitemapIndex)
{
$this->writer->startElement('sitemapindex');
$this->writer->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
$this->writer->writeAttribute(
'xsi:schemaLocation',
'http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/siteindex.xsd'
);
$this->writer->writeAttribute(
'xmlns',
'http://www.sitemaps.org/schemas/sitemap/0.9'
);
foreach ($sitemapIndex->all() as $item) {
$item->accept($this);
}
$this->writer->endElement();
}
public function visitSitemap(Sitemap $sitemap)
{
$this->writer->startElement('sitemap');
$this->writer->writeElement('loc', $sitemap->getLoc());
$this->writeElement('lastmod', $sitemap->getLastMod());
$this->writer->endElement();
}
public function visitUrlset(Urlset $urlset)
{
$this->writer->startElement('urlset');
$this->writer->writeAttribute(
'xmlns:xsi',
'http://www.w3.org/2001/XMLSchema-instance'
);
$this->writer->writeAttribute(
'xsi:schemaLocation',
'http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd'
);
$this->writer->writeAttribute(
'xmlns',
'http://www.sitemaps.org/schemas/sitemap/0.9'
);
/**
* @var Url $item
*/
foreach ($urlset->all() as $item) {
foreach ($item->getExtensions() as $extension) {
$extensionClass = get_class($extension);
$extensionAttributes = $this->extensionAttributes[$extensionClass];
if (!in_array($extensionClass, $this->extensions, true)) {
$this->extensions[] = $extensionClass;
$this->writer->writeAttribute($extensionAttributes['name'], $extensionAttributes['content']);
}
}
}
foreach ($urlset->all() as $item) {
$item->accept($this);
}
$this->writer->endElement();
}
public function visitUrl(Url $url)
{
$this->writer->startElement('url');
$this->writeElement('loc', $url->getLoc());
$this->writeElement('lastmod', $url->getLastMod());
$this->writeElement('changefreq', $url->getChangeFreq());
$this->writeElement('priority', $url->getPriority());
foreach ($url->getExtensions() as $extension) {
$extension->accept($this);
}
$this->writer->endElement();
}
public function visitImageExtension(Image $image)
{
$this->writer->startElement('image:image');
$this->writeElement('image:loc', $image->getLoc());
$this->writeElement('image:caption', $image->getCaption());
$this->writeElement('image:geo_location', $image->getGeoLocation());
$this->writeElement('image:title', $image->getTitle());
$this->writeElement('image:license', $image->getLicense());
$this->writer->endElement();
}
public function visitLinkExtension(Link $link)
{
$this->writer->startElement('xhtml:link');
$this->writer->writeAttribute('rel', 'alternate');
$this->writer->writeAttribute('hreflang', $link->getHrefLang());
$this->writer->writeAttribute('href', $link->getHref());
$this->writer->endElement();
}
public function visitMobileExtension(Mobile $mobile)
{
$this->writer->writeElement('mobile:mobile');
}
public function visitNewsExtension(News $news)
{
$this->writer->startElement('news:news');
$this->writer->startElement('news:publication');
$this->writeElement('news:name', $news->getPublicationName());
$this->writeElement('news:language', $news->getPublicationLanguage());
$this->writer->endElement();
$this->writeElement('news:access', $news->getAccess());
$this->writeElement('news:genres', $news->getGenres());
$this->writeElement('news:publication_date', $news->getPublicationDate());
$this->writeElement('news:title', $news->getTitle());
$this->writeElement('news:keywords', $news->getKeywords());
$this->writer->endElement();
}
public function visitVideoExtension(Video $video)
{
$this->writer->startElement('video:video');
$this->writeElement('video:thumbnail_loc', $video->getThumbnailLoc());
$this->writeElement('video:title', $video->getTitle());
$this->writeElement('video:description', $video->getDescription());
$this->writeElement('video:content_loc', $video->getContentLoc());
$this->writeElement('video:player_loc', $video->getPlayerLoc());
$this->writeElement('video:duration', $video->getDuration());
$this->writeElement('video:expiration_date', $video->getExpirationDate());
$this->writeElement('video:rating', $video->getRating());
$this->writeElement('video:view_count', $video->getViewCount());
$this->writeElement('video:publication_date', $video->getPublicationDate());
$this->writeElement('video:family_friendly', $video->getFamilyFriendly());
$this->writeElement('video:category', $video->getCategory());
$this->writeElement('video:restriction', $video->getRestriction());
$this->writeElement('video:gallery_loc', $video->getGalleryLoc());
if ($price = $video->getPrice()) {
$this->writer->startElement('video:price');
if ($currency = $video->getCurrency()) {
$this->writer->writeAttribute('currency', $currency);
}
$this->writer->writeRaw($price);
$this->writer->endElement();
}
$this->writeElement('video:requires_subscription', $video->getRequiresSubscription());
$this->writeElement('video:uploader', $video->getUploader());
$this->writeElement('video:platform', $video->getPlatform());
$this->writeElement('video:live', $video->getLive());
foreach ($video->getTags() as $tag) {
$this->writeElement('video:tag', $tag);
}
$this->writer->endElement();
}
public function output(): string
{
return $this->writer->flush();
}
}
| php | MIT | ee4cbd1406f1250534860b8c9b74020fee0c3650 | 2026-01-05T05:08:07.161661Z | false |
ThePixelDeveloper/Sitemap | https://github.com/ThePixelDeveloper/Sitemap/blob/ee4cbd1406f1250534860b8c9b74020fee0c3650/src/Extensions/Link.php | src/Extensions/Link.php | <?php
namespace Thepixeldeveloper\Sitemap\Extensions;
use Thepixeldeveloper\Sitemap\Interfaces\DriverInterface;
use Thepixeldeveloper\Sitemap\Interfaces\VisitorInterface;
/**
* Class Link
*
* @package Thepixeldeveloper\Sitemap\Subelements
*/
class Link implements VisitorInterface
{
/**
* Language code for the page.
*
* @var string
*/
protected $hrefLang;
/**
* Location of the translated page.
*
* @var string
*/
protected $href;
/**
* Link constructor.
*
* @param string $hrefLang
* @param string $href
*/
public function __construct(string $hrefLang, string $href)
{
$this->hrefLang = $hrefLang;
$this->href = $href;
}
/**
* Location of the translated page.
*
* @return string
*/
public function getHref(): string
{
return $this->href;
}
/**
* Language code for the page.
*
* @return string
*/
public function getHrefLang(): string
{
return $this->hrefLang;
}
public function accept(DriverInterface $driver)
{
$driver->visitLinkExtension($this);
}
}
| php | MIT | ee4cbd1406f1250534860b8c9b74020fee0c3650 | 2026-01-05T05:08:07.161661Z | false |
ThePixelDeveloper/Sitemap | https://github.com/ThePixelDeveloper/Sitemap/blob/ee4cbd1406f1250534860b8c9b74020fee0c3650/src/Extensions/Video.php | src/Extensions/Video.php | <?php
namespace Thepixeldeveloper\Sitemap\Extensions;
use Thepixeldeveloper\Sitemap\Interfaces\DriverInterface;
use Thepixeldeveloper\Sitemap\Interfaces\VisitorInterface;
class Video implements VisitorInterface
{
/**
* URL pointing to an image thumbnail.
*
* @var string
*/
protected $thumbnailLoc;
/**
* Title of the video, max 100 characters.
*
* @var string
*/
protected $title;
/**
* Description of the video, max 2048 characters.
*
* @var string
*/
protected $description;
/**
* URL pointing to the actual media file (mp4).
*
* @var string
*/
protected $contentLoc;
/**
* URL pointing to the player file (normally a SWF).
*
* @var string
*/
protected $playerLoc;
/**
* Indicates whether the video is live.
*
* @var boolean
*/
protected $live;
/**
* Duration of the video in seconds.
*
* @var integer
*/
protected $duration;
/**
* String of space delimited platform values.
*
* Allowed values are web, mobile, and tv.
*
* @var string
*/
protected $platform;
/**
* Does the video require a subscription?
*
* @var boolean
*/
protected $requiresSubscription;
/**
* The price to download or view the video in ISO 4217 format.
*
* @link https://en.wikipedia.org/wiki/ISO_4217
*
* @var string
*/
protected $price;
/**
* The currency used for the price.
*
* @var string
*/
protected $currency;
/**
* Link to gallery of which this video appears in.
*
* @var string
*/
protected $galleryLoc;
/**
* A space-delimited list of countries where the video may or may not be played.
*
* @var string
*/
protected $restriction;
/**
* A tag associated with the video.
*
* @var array
*/
protected $tags = [];
/**
* The video's category. For example, cooking.
*
* @var string
*/
protected $category;
/**
* No if the video should be available only to users with SafeSearch turned off.
*
* @var string
*/
protected $familyFriendly;
/**
* The date the video was first published.
*
* @var \DateTimeInterface
*/
protected $publicationDate;
/**
* The number of times the video has been viewed.
*
* @var integer
*/
protected $viewCount;
/**
* The video uploader's name. Only one <video:uploader> is allowed per video.
*
* @var string
*/
protected $uploader;
/**
* The rating of the video. Allowed values are float numbers in the range 0.0 to 5.0.
*
* @var float
*/
protected $rating;
/**
* The date after which the video will no longer be available
*
* @var \DateTimeInterface
*/
protected $expirationDate;
/**
* Video constructor.
*
* @param string $thumbnailLoc
* @param string $title
* @param string $description
*/
public function __construct($thumbnailLoc, $title, $description)
{
$this->thumbnailLoc = $thumbnailLoc;
$this->title = $title;
$this->description = $description;
}
/**
* URL pointing to the player file (normally a SWF).
*
* @return string
*/
public function getPlayerLoc()
{
return $this->playerLoc;
}
/**
* URL pointing to the player file (normally a SWF).
*
* @param string $playerLoc
*
* @return $this
*/
public function setPlayerLoc($playerLoc)
{
$this->playerLoc = $playerLoc;
return $this;
}
/**
* URL pointing to an image thumbnail.
*
* @return string
*/
public function getThumbnailLoc()
{
return $this->thumbnailLoc;
}
/**
* Title of the video, max 100 characters.
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Description of the video, max 2048 characters.
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* URL pointing to the actual media file (mp4).
*
* @return string
*/
public function getContentLoc()
{
return $this->contentLoc;
}
/**
* URL pointing to the actual media file (mp4).
*
* @param string $contentLoc
*
* @return $this
*/
public function setContentLoc($contentLoc)
{
$this->contentLoc = $contentLoc;
return $this;
}
/**
* Duration of the video in seconds.
*
* @return integer
*/
public function getDuration()
{
return $this->duration;
}
/**
* Duration of the video in seconds.
*
* @param integer $duration
*
* @return $this
*/
public function setDuration($duration)
{
$this->duration = $duration;
return $this;
}
/**
* The date after which the video will no longer be available.
*
* @return \DateTimeInterface
*/
public function getExpirationDate()
{
return $this->expirationDate;
}
/**
* The date after which the video will no longer be available.
*
* @param \DateTimeInterface $expirationDate
*
* @return $this
*/
public function setExpirationDate(\DateTimeInterface $expirationDate)
{
$this->expirationDate = $expirationDate;
return $this;
}
/**
* The rating of the video. Allowed values are float numbers in the range 0.0 to 5.0.
*
* @return float
*/
public function getRating()
{
return $this->rating;
}
/**
* The rating of the video. Allowed values are float numbers in the range 0.0 to 5.0.
*
* @param float $rating
*
* @return $this
*/
public function setRating($rating)
{
$this->rating = $rating;
return $this;
}
/**
* The number of times the video has been viewed.
*
* @return integer
*/
public function getViewCount()
{
return $this->viewCount;
}
/**
* The number of times the video has been viewed.
*
* @param integer $viewCount
*
* @return $this
*/
public function setViewCount($viewCount)
{
$this->viewCount = $viewCount;
return $this;
}
/**
* The date the video was first published, in W3C format.
*
* @return \DateTimeInterface
*/
public function getPublicationDate()
{
return $this->publicationDate;
}
/**
* The date the video was first published, in W3C format.
*
* @param \DateTimeInterface $publicationDate
*
* @return $this
*/
public function setPublicationDate(\DateTimeInterface $publicationDate)
{
$this->publicationDate = $publicationDate;
return $this;
}
/**
* No if the video should be available only to users with SafeSearch turned off.
*
* @return string
*/
public function getFamilyFriendly()
{
return $this->familyFriendly;
}
/**
* No if the video should be available only to users with SafeSearch turned off.
*
* @param string $familyFriendly
*
* @return $this
*/
public function setFamilyFriendly($familyFriendly)
{
$this->familyFriendly = $familyFriendly;
return $this;
}
/**
* A tag associated with the video.
*
* @return array
*/
public function getTags()
{
return $this->tags;
}
/**
* A tag associated with the video.
*
* @param array $tags
*
* @return $this
*/
public function setTags($tags)
{
$this->tags = $tags;
return $this;
}
/**
* The video's category. For example, cooking.
*
* @return string
*/
public function getCategory()
{
return $this->category;
}
/**
* The video's category. For example, cooking.
*
* @param string $category
*
* @return $this
*/
public function setCategory($category)
{
$this->category = $category;
return $this;
}
/**
* A space-delimited list of countries where the video may or may not be played.
*
* @return string
*/
public function getRestriction()
{
return $this->restriction;
}
/**
* A space-delimited list of countries where the video may or may not be played.
*
* @param string $restriction
*
* @return $this
*/
public function setRestriction($restriction)
{
$this->restriction = $restriction;
return $this;
}
/**
* Link to gallery of which this video appears in.
*
* @return string
*/
public function getGalleryLoc()
{
return $this->galleryLoc;
}
/**
* Link to gallery of which this video appears in.
*
* @param string $galleryLoc
*
* @return $this
*/
public function setGalleryLoc($galleryLoc)
{
$this->galleryLoc = $galleryLoc;
return $this;
}
/**
* The price to download or view the video in ISO 4217 format.
*
* @return string
*/
public function getPrice()
{
return $this->price;
}
/**
* The price to download or view the video in ISO 4217 format.
*
* @param string $price
*
* @return $this
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* The currency used for the price.
*
* @return string
*/
public function getCurrency()
{
return $this->currency;
}
/**
* The currency used for the price.
*
* @param string $currency
*/
public function setCurrency($currency)
{
$this->currency = $currency;
}
/**
* Does the video require a subscription?
*
* @return boolean
*/
public function getRequiresSubscription()
{
return $this->requiresSubscription;
}
/**
* Does the video require a subscription?
*
* @param boolean $requiresSubscription
*
* @return $this
*/
public function setRequiresSubscription($requiresSubscription)
{
$this->requiresSubscription = $requiresSubscription;
return $this;
}
/**
* The video uploader's name. Only one <video:uploader> is allowed per video.
*
* @return string
*/
public function getUploader()
{
return $this->uploader;
}
/**
* The video uploader's name. Only one <video:uploader> is allowed per video.
*
* @param string $uploader
*
* @return $this
*/
public function setUploader($uploader)
{
$this->uploader = $uploader;
return $this;
}
/**
* String of space delimited platform values.
*
* Allowed values are web, mobile, and tv.
*
* @return string
*/
public function getPlatform()
{
return $this->platform;
}
/**
* String of space delimited platform values.
*
* Allowed values are web, mobile, and tv.
*
* @param string $platform
*
* @return $this
*/
public function setPlatform($platform)
{
$this->platform = $platform;
return $this;
}
/**
* Indicates whether the video is live.
*
* @return boolean
*/
public function getLive()
{
return $this->live;
}
/**
* Indicates whether the video is live.
*
* @param boolean $live
*
* @return $this
*/
public function setLive($live)
{
$this->live = $live;
return $this;
}
public function accept(DriverInterface $driver)
{
$driver->visitVideoExtension($this);
}
}
| php | MIT | ee4cbd1406f1250534860b8c9b74020fee0c3650 | 2026-01-05T05:08:07.161661Z | false |
ThePixelDeveloper/Sitemap | https://github.com/ThePixelDeveloper/Sitemap/blob/ee4cbd1406f1250534860b8c9b74020fee0c3650/src/Extensions/Mobile.php | src/Extensions/Mobile.php | <?php
namespace Thepixeldeveloper\Sitemap\Extensions;
use Thepixeldeveloper\Sitemap\Interfaces\DriverInterface;
use Thepixeldeveloper\Sitemap\Interfaces\VisitorInterface;
use XMLWriter;
/**
* Class Mobile
*
* @package Thepixeldeveloper\Sitemap\Subelements
*/
class Mobile implements VisitorInterface
{
public function accept(DriverInterface $driver)
{
$driver->visitMobileExtension($this);
}
}
| php | MIT | ee4cbd1406f1250534860b8c9b74020fee0c3650 | 2026-01-05T05:08:07.161661Z | false |
ThePixelDeveloper/Sitemap | https://github.com/ThePixelDeveloper/Sitemap/blob/ee4cbd1406f1250534860b8c9b74020fee0c3650/src/Extensions/Image.php | src/Extensions/Image.php | <?php
namespace Thepixeldeveloper\Sitemap\Extensions;
use Thepixeldeveloper\Sitemap\Interfaces\DriverInterface;
use Thepixeldeveloper\Sitemap\Interfaces\VisitorInterface;
class Image implements VisitorInterface
{
/**
* Location (URL).
*
* @var string
*/
protected $loc;
/**
* The caption of the image.
*
* @var string
*/
protected $caption;
/**
* The geographic location of the image.
*
* @var string
*/
protected $geoLocation;
/**
* The title of the image.
*
* @var string
*/
protected $title;
/**
* A URL to the license of the image.
*
* @var string
*/
protected $license;
/**
* Image constructor
*
* @param string $loc
*/
public function __construct($loc)
{
$this->loc = $loc;
}
/**
* Location (URL).
*
* @return string
*/
public function getLoc()
{
return $this->loc;
}
/**
* The caption of the image.
*
* @return string
*/
public function getCaption()
{
return $this->caption;
}
/**
* Set the caption of the image.
*
* @param string $caption
*
* @return $this
*/
public function setCaption($caption)
{
$this->caption = $caption;
return $this;
}
/**
* The geographic location of the image.
*
* @return string
*/
public function getGeoLocation()
{
return $this->geoLocation;
}
/**
* Set the geographic location of the image.
*
* @param string $geoLocation
*
* @return $this
*/
public function setGeoLocation($geoLocation)
{
$this->geoLocation = $geoLocation;
return $this;
}
/**
* The title of the image.
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set the title of the image.
*
* @param string $title
*
* @return $this
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* A URL to the license of the image.
*
* @return string
*/
public function getLicense()
{
return $this->license;
}
/**
* Set a URL to the license of the image.
*
* @param string $license
*
* @return $this
*/
public function setLicense($license)
{
$this->license = $license;
return $this;
}
public function accept(DriverInterface $driver)
{
$driver->visitImageExtension($this);
}
}
| php | MIT | ee4cbd1406f1250534860b8c9b74020fee0c3650 | 2026-01-05T05:08:07.161661Z | false |
ThePixelDeveloper/Sitemap | https://github.com/ThePixelDeveloper/Sitemap/blob/ee4cbd1406f1250534860b8c9b74020fee0c3650/src/Extensions/News.php | src/Extensions/News.php | <?php
namespace Thepixeldeveloper\Sitemap\Extensions;
use Thepixeldeveloper\Sitemap\Interfaces\DriverInterface;
use Thepixeldeveloper\Sitemap\Interfaces\VisitorInterface;
/**
* Class Image
*
* @package Thepixeldeveloper\Sitemap\Subelements
*/
class News implements VisitorInterface
{
/**
* Location (URL).
*
* @var string
*/
protected $loc;
/**
* Publication name.
*
* @var string
*/
protected $publicationName;
/**
* Publication language.
*
* @var string
*/
protected $publicationLanguage;
/**
* Access.
*
* @var string
*/
protected $access;
/**
* List of genres, comma-separated string values.
*
* @var string
*/
protected $genres;
/**
* Date of publication.
*
* @var \DateTimeInterface
*/
protected $publicationDate;
/**
* Title.
*
* @var string
*/
protected $title;
/**
* Key words, comma-separated string values.
*
* @var string
*/
protected $keywords;
/**
* Publication name.
*
* @return string
*/
public function getPublicationName()
{
return $this->publicationName;
}
/**
* Set the publication name.
*
* @param string $publicationName
*
* @return $this
*/
public function setPublicationName($publicationName)
{
$this->publicationName = $publicationName;
return $this;
}
/**
* Publication language.
*
* @return string
*/
public function getPublicationLanguage()
{
return $this->publicationLanguage;
}
/**
* Set the publication language.
*
* @param string $publicationLanguage
*
* @return $this
*/
public function setPublicationLanguage($publicationLanguage)
{
$this->publicationLanguage = $publicationLanguage;
return $this;
}
/**
* Access.
*
* @return string
*/
public function getAccess()
{
return $this->access;
}
/**
* Set access.
*
* @param string $access
*
* @return $this
*/
public function setAccess($access)
{
$this->access = $access;
return $this;
}
/**
* List of genres, comma-separated string values.
*
* @return string
*/
public function getGenres()
{
return $this->genres;
}
/**
* Set list of genres, comma-separated string values.
*
* @param string $genres
*
* @return $this
*/
public function setGenres($genres)
{
$this->genres = $genres;
return $this;
}
/**
* Date of publication.
*
* @return \DateTimeInterface
*/
public function getPublicationDate()
{
return $this->publicationDate;
}
/**
* Set date of publication.
*
* @param \DateTimeInterface $publicationDate
*
* @return $this
*/
public function setPublicationDate(\DateTimeInterface $publicationDate)
{
$this->publicationDate = $publicationDate;
return $this;
}
/**
* Title.
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set title.
*
* @param string $title
*
* @return $this
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Key words, comma-separated string values.
*
* @return string
*/
public function getKeywords()
{
return $this->keywords;
}
/**
* Set key words, comma-separated string values.
*
* @param string $keywords
*
* @return $this
*/
public function setKeywords($keywords)
{
$this->keywords = $keywords;
return $this;
}
public function accept(DriverInterface $driver)
{
$driver->visitNewsExtension($this);
}
}
| php | MIT | ee4cbd1406f1250534860b8c9b74020fee0c3650 | 2026-01-05T05:08:07.161661Z | false |
ThePixelDeveloper/Sitemap | https://github.com/ThePixelDeveloper/Sitemap/blob/ee4cbd1406f1250534860b8c9b74020fee0c3650/tests/CompleteTest.php | tests/CompleteTest.php | <?php declare(strict_types=1);
namespace Tests\Thepixeldeveloper\Sitemap;
use PHPUnit\Framework\TestCase;
use Thepixeldeveloper\Sitemap\Drivers\XmlWriterDriver;
use Thepixeldeveloper\Sitemap\Extensions\Image;
use Thepixeldeveloper\Sitemap\Extensions\Link;
use Thepixeldeveloper\Sitemap\Extensions\Mobile;
use Thepixeldeveloper\Sitemap\Extensions\News;
use Thepixeldeveloper\Sitemap\Extensions\Video;
use Thepixeldeveloper\Sitemap\Sitemap;
use Thepixeldeveloper\Sitemap\SitemapIndex;
use Thepixeldeveloper\Sitemap\Url;
use Thepixeldeveloper\Sitemap\Urlset;
class CompleteTest extends TestCase
{
public function testCompleteSitemap()
{
$extensions = [
new Image('http://example.com'),
new Link('en-GB', 'http://example.com'),
new Mobile(),
new News(),
new Video('http://example.com/thumbnail', 'title', 'description'),
];
$urlset = new Urlset();
foreach ($extensions as $extension) {
$url = new Url('http://example.com');
$url->addExtension($extension);
$urlset->add($url);
}
$driver = new XmlWriterDriver();
$urlset->accept($driver);
$expected = <<<XML
<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xmlns:xhtml="http://www.w3.org/1999/xhtml"
xmlns:mobile="http://www.google.com/schemas/sitemap-mobile/1.0"
xmlns:news="http://www.google.com/schemas/sitemap-news/0.9"
xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">
<url>
<loc>http://example.com</loc>
<image:image>
<image:loc>http://example.com</image:loc>
</image:image>
</url>
<url>
<loc>http://example.com</loc>
<xhtml:link rel="alternate" hreflang="en-GB" href="http://example.com"/>
</url>
<url>
<loc>http://example.com</loc>
<mobile:mobile/>
</url>
<url>
<loc>http://example.com</loc>
<news:news>
<news:publication/>
</news:news>
</url>
<url>
<loc>http://example.com</loc>
<video:video>
<video:thumbnail_loc>http://example.com/thumbnail</video:thumbnail_loc>
<video:title>title</video:title>
<video:description>description</video:description>
</video:video>
</url>
</urlset>
XML;
$this->assertXmlStringEqualsXmlString($expected, $driver->output());
}
public function testCompleteIndex()
{
$sitemap = new Sitemap('http://example.com');
$sitemapIndex = new SitemapIndex();
$sitemapIndex->add($sitemap);
$driver = new XmlWriterDriver();
$sitemapIndex->accept($driver);
$expected = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/siteindex.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap>
<loc>http://example.com</loc>
</sitemap>
</sitemapindex>
XML;
$this->assertXmlStringEqualsXmlString($expected, $driver->output());
}
}
| php | MIT | ee4cbd1406f1250534860b8c9b74020fee0c3650 | 2026-01-05T05:08:07.161661Z | false |
ThePixelDeveloper/Sitemap | https://github.com/ThePixelDeveloper/Sitemap/blob/ee4cbd1406f1250534860b8c9b74020fee0c3650/tests/SitemapTest.php | tests/SitemapTest.php | <?php declare(strict_types=1);
namespace Tests\Thepixeldeveloper\Sitemap;
use PHPUnit\Framework\TestCase;
use Thepixeldeveloper\Sitemap\Sitemap;
class SitemapTest extends TestCase
{
public function testGetters()
{
$location = 'https://example.com';
$sitemap = new Sitemap($location);
$this->assertSame($location, $sitemap->getLoc());
$this->assertNull($sitemap->getLastMod());
}
}
| php | MIT | ee4cbd1406f1250534860b8c9b74020fee0c3650 | 2026-01-05T05:08:07.161661Z | false |
ThePixelDeveloper/Sitemap | https://github.com/ThePixelDeveloper/Sitemap/blob/ee4cbd1406f1250534860b8c9b74020fee0c3650/tests/UrlsetTest.php | tests/UrlsetTest.php | <?php declare(strict_types=1);
namespace Tests\Thepixeldeveloper\Sitemap;
use PHPUnit\Framework\TestCase;
use Thepixeldeveloper\Sitemap\Sitemap;
use Thepixeldeveloper\Sitemap\Url;
use Thepixeldeveloper\Sitemap\Urlset;
class UrlsetTest extends TestCase
{
/**
* @expectedException \InvalidArgumentException
*/
public function testCollectionType()
{
$sitemap = new Sitemap('https://example.com');
$urlset = new Urlset();
$urlset->add($sitemap);
}
}
| php | MIT | ee4cbd1406f1250534860b8c9b74020fee0c3650 | 2026-01-05T05:08:07.161661Z | false |
ThePixelDeveloper/Sitemap | https://github.com/ThePixelDeveloper/Sitemap/blob/ee4cbd1406f1250534860b8c9b74020fee0c3650/tests/UrlTest.php | tests/UrlTest.php | <?php declare(strict_types=1);
namespace Tests\Thepixeldeveloper\Sitemap;
use PHPUnit\Framework\TestCase;
use Thepixeldeveloper\Sitemap\Url;
class UrlTest extends TestCase
{
public function testGetters()
{
$location = 'https://example.com';
$url = new Url($location);
$url->setChangeFreq('monthly');
$url->setPriority('0.8');
$this->assertSame($location, $url->getLoc());
$this->assertSame([], $url->getExtensions());
$this->assertSame('monthly', $url->getChangeFreq());
$this->assertSame('0.8', $url->getPriority());
$this->assertNull($url->getLastMod());
}
}
| php | MIT | ee4cbd1406f1250534860b8c9b74020fee0c3650 | 2026-01-05T05:08:07.161661Z | false |
ThePixelDeveloper/Sitemap | https://github.com/ThePixelDeveloper/Sitemap/blob/ee4cbd1406f1250534860b8c9b74020fee0c3650/tests/SitemapIndexTest.php | tests/SitemapIndexTest.php | <?php declare(strict_types=1);
namespace Tests\Thepixeldeveloper\Sitemap;
use PHPUnit\Framework\TestCase;
use Thepixeldeveloper\Sitemap\SitemapIndex;
use Thepixeldeveloper\Sitemap\Url;
class SitemapIndexTest extends TestCase
{
/**
* @expectedException \InvalidArgumentException
*/
public function testCollectionType()
{
$sitemap = new Url('https://example.com');
$sitemapIndex = new SitemapIndex();
$sitemapIndex->add($sitemap);
}
}
| php | MIT | ee4cbd1406f1250534860b8c9b74020fee0c3650 | 2026-01-05T05:08:07.161661Z | false |
ThePixelDeveloper/Sitemap | https://github.com/ThePixelDeveloper/Sitemap/blob/ee4cbd1406f1250534860b8c9b74020fee0c3650/tests/ChunkedUrlsetTest.php | tests/ChunkedUrlsetTest.php | <?php declare(strict_types=1);
namespace Tests\Thepixeldeveloper\Sitemap;
use PHPUnit\Framework\TestCase;
use Thepixeldeveloper\Sitemap\ChunkedUrlset;
use Thepixeldeveloper\Sitemap\Url;
class ChunkedUrlsetTest extends TestCase
{
public function testChunkingWithOne()
{
$url = new Url('https://example.com');
$urlset = new ChunkedUrlset();
$urlset->add($url);
$this->assertCount(1, $urlset->getCollections());
}
public function testChunkingWithMultiple()
{
$url = new Url('https://example.com');
$urlset = new ChunkedUrlset();
for ($i = 0; $i < 50001; $i++) {
$urlset->add($url);
}
$this->assertCount(2, $urlset->getCollections());
}
}
| php | MIT | ee4cbd1406f1250534860b8c9b74020fee0c3650 | 2026-01-05T05:08:07.161661Z | false |
ThePixelDeveloper/Sitemap | https://github.com/ThePixelDeveloper/Sitemap/blob/ee4cbd1406f1250534860b8c9b74020fee0c3650/tests/Drivers/XmlWriterDriverTest.php | tests/Drivers/XmlWriterDriverTest.php | <?php declare(strict_types=1);
namespace Tests\Thepixeldeveloper\Sitemap\Drivers;
use PHPUnit\Framework\TestCase;
use Thepixeldeveloper\Sitemap\Drivers\XmlWriterDriver;
use Thepixeldeveloper\Sitemap\Extensions\Image;
use Thepixeldeveloper\Sitemap\Extensions\Link;
use Thepixeldeveloper\Sitemap\Extensions\Mobile;
use Thepixeldeveloper\Sitemap\Extensions\News;
use Thepixeldeveloper\Sitemap\Extensions\Video;
use Thepixeldeveloper\Sitemap\Sitemap;
use Thepixeldeveloper\Sitemap\SitemapIndex;
use Thepixeldeveloper\Sitemap\Url;
use Thepixeldeveloper\Sitemap\Urlset;
class XmlWriterDriverTest extends TestCase
{
public function testProcessingInstructions()
{
$driver = new XmlWriterDriver();
$driver->addProcessingInstructions('xml-stylesheet', 'type="text/xsl" href="/path/to/xslt/main-sitemap.xsl"');
$expected = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="/path/to/xslt/main-sitemap.xsl"?>
XML;
$this->assertSame($expected, $driver->output());
}
public function testComments()
{
$date = date('Y-m-d H:i:s');
$driver = new XmlWriterDriver();
$driver->addComment('This XML file was written on ' . $date . '. Bye!');
$expected = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<!--This XML file was written on $date. Bye!-->
XML;
$this->assertSame($expected, $driver->output());
}
public function testSitemapIndex()
{
$sitemapIndex = new SitemapIndex();
$driver = new XmlWriterDriver();
$driver->visitSitemapIndex($sitemapIndex);
$expected = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/siteindex.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"/>
XML;
$this->assertSame($expected, $driver->output());
}
public function testSitemap()
{
$date = new \DateTime();
$sitemap = new Sitemap('https://example.com');
$sitemap->setLastMod($date);
$driver = new XmlWriterDriver();
$driver->visitSitemap($sitemap);
$expected = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<sitemap><loc>https://example.com</loc><lastmod>{$date->format(DATE_W3C)}</lastmod></sitemap>
XML;
$this->assertSame($expected, $driver->output());
}
public function testUrlset()
{
$urlset = new Urlset();
$driver = new XmlWriterDriver();
$driver->visitUrlset($urlset);
$expected = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"/>
XML;
$this->assertSame($expected, $driver->output());
}
public function testUrl()
{
$date = new \DateTime();
$url = new Url('https://example.com');
$url->setLastMod($date);
$driver = new XmlWriterDriver();
$driver->visitUrl($url);
$expected = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<url><loc>https://example.com</loc><lastmod>{$date->format(DATE_W3C)}</lastmod></url>
XML;
$this->assertSame($expected, $driver->output());
}
public function testImageExtension()
{
$image = new Image('https://example.com');
$image->setTitle('Title');
$image->setCaption('Captain');
$image->setLicense('MIT');
$image->setGeoLocation('Limerick, Ireland');
$driver = new XmlWriterDriver();
$driver->visitImageExtension($image);
$expected = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<image:image><image:loc>https://example.com</image:loc><image:caption>Captain</image:caption><image:geo_location>Limerick, Ireland</image:geo_location><image:title>Title</image:title><image:license>MIT</image:license></image:image>
XML;
$this->assertSame($expected, $driver->output());
}
public function testLinkExtension()
{
$image = new Link('en_GB', 'https://example.com');
$driver = new XmlWriterDriver();
$driver->visitLinkExtension($image);
$expected = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<xhtml:link rel="alternate" hreflang="en_GB" href="https://example.com"/>
XML;
$this->assertSame($expected, $driver->output());
}
public function testMobileExtension()
{
$mobile = new Mobile();
$driver = new XmlWriterDriver();
$driver->visitMobileExtension($mobile);
$expected = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<mobile:mobile/>
XML;
$this->assertSame($expected, $driver->output());
}
public function testNewsExtension()
{
$news = new News();
$news->setPublicationName('Example Publisher');
$news->setTitle('Example Title');
$news->setPublicationLanguage('en');
$news->setAccess('Subscription');
$news->setKeywords('hello, world');
$news->setPublicationDate(new \DateTime('2017-11-05T12:01:27+00:00'));
$news->setGenres('Satire,Blog');
$driver = new XmlWriterDriver();
$driver->visitNewsExtension($news);
$expected = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<news:news><news:publication><news:name>Example Publisher</news:name><news:language>en</news:language></news:publication><news:access>Subscription</news:access><news:genres>Satire,Blog</news:genres><news:publication_date>2017-11-05T12:01:27+00:00</news:publication_date><news:title>Example Title</news:title><news:keywords>hello, world</news:keywords></news:news>
XML;
$this->assertSame($expected, $driver->output());
}
public function testVideoExtension()
{
$video = new Video('https://example.com', 'Title', 'Description');
$video->setPlayerLoc('http://example.com/player');
$video->setContentLoc('https://example.com/content');
$video->setDuration(3600);
$video->setExpirationDate(new \DateTime('2017-11-05T12:01:27+00:00'));
$video->setRating(4.2);
$video->setViewCount(100);
$video->setPublicationDate(new \DateTime('2017-11-05T12:01:27+00:00'));
$video->setFamilyFriendly('yes');
$video->setTags(['summer']);
$video->setCategory('Baking');
$video->setRestriction('IE GB US CA');
$video->setGalleryLoc('https://example.com/gallery');
$video->setPrice('100');
$video->setCurrency('EUR');
$video->setRequiresSubscription(true);
$video->setUploader('GrillyMcGrillerson');
$video->setPlatform('web mobile');
$video->setLive(false);
$driver = new XmlWriterDriver();
$driver->visitVideoExtension($video);
$expected = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<video:video><video:thumbnail_loc>https://example.com</video:thumbnail_loc><video:title>Title</video:title><video:description>Description</video:description><video:content_loc>https://example.com/content</video:content_loc><video:player_loc>http://example.com/player</video:player_loc><video:duration>3600</video:duration><video:expiration_date>2017-11-05T12:01:27+00:00</video:expiration_date><video:rating>4.2</video:rating><video:view_count>100</video:view_count><video:publication_date>2017-11-05T12:01:27+00:00</video:publication_date><video:family_friendly>yes</video:family_friendly><video:category>Baking</video:category><video:restriction>IE GB US CA</video:restriction><video:gallery_loc>https://example.com/gallery</video:gallery_loc><video:price currency="EUR">100</video:price><video:requires_subscription>1</video:requires_subscription><video:uploader>GrillyMcGrillerson</video:uploader><video:platform>web mobile</video:platform><video:tag>summer</video:tag></video:video>
XML;
$this->assertSame($expected, $driver->output());
}
}
| php | MIT | ee4cbd1406f1250534860b8c9b74020fee0c3650 | 2026-01-05T05:08:07.161661Z | false |
illuminate/events | https://github.com/illuminate/events/blob/4cd2bf391de735f631e57b4398d51b611f1a410e/InvokeQueuedClosure.php | InvokeQueuedClosure.php | <?php
namespace Illuminate\Events;
use Illuminate\Support\Collection;
class InvokeQueuedClosure
{
/**
* Handle the event.
*
* @param \Laravel\SerializableClosure\SerializableClosure $closure
* @param array $arguments
* @return void
*/
public function handle($closure, array $arguments)
{
call_user_func($closure->getClosure(), ...$arguments);
}
/**
* Handle a job failure.
*
* @param \Laravel\SerializableClosure\SerializableClosure $closure
* @param array $arguments
* @param array $catchCallbacks
* @param \Throwable $exception
* @return void
*/
public function failed($closure, array $arguments, array $catchCallbacks, $exception)
{
$arguments[] = $exception;
(new Collection($catchCallbacks))->each->__invoke(...$arguments);
}
}
| php | MIT | 4cd2bf391de735f631e57b4398d51b611f1a410e | 2026-01-05T05:08:15.237387Z | false |
illuminate/events | https://github.com/illuminate/events/blob/4cd2bf391de735f631e57b4398d51b611f1a410e/QueuedClosure.php | QueuedClosure.php | <?php
namespace Illuminate\Events;
use Closure;
use Illuminate\Support\Collection;
use Laravel\SerializableClosure\SerializableClosure;
use function Illuminate\Support\enum_value;
class QueuedClosure
{
/**
* The underlying Closure.
*
* @var \Closure
*/
public $closure;
/**
* The name of the connection the job should be sent to.
*
* @var string|null
*/
public $connection;
/**
* The name of the queue the job should be sent to.
*
* @var string|null
*/
public $queue;
/**
* The job "group" the job should be sent to.
*
* @var string|null
*/
public $messageGroup;
/**
* The job deduplicator callback the job should use to generate the deduplication ID.
*
* @var \Laravel\SerializableClosure\SerializableClosure|null
*/
public $deduplicator;
/**
* The number of seconds before the job should be made available.
*
* @var \DateTimeInterface|\DateInterval|int|null
*/
public $delay;
/**
* All of the "catch" callbacks for the queued closure.
*
* @var array
*/
public $catchCallbacks = [];
/**
* Create a new queued closure event listener resolver.
*
* @param \Closure $closure
*/
public function __construct(Closure $closure)
{
$this->closure = $closure;
}
/**
* Set the desired connection for the job.
*
* @param \UnitEnum|string|null $connection
* @return $this
*/
public function onConnection($connection)
{
$this->connection = enum_value($connection);
return $this;
}
/**
* Set the desired queue for the job.
*
* @param \UnitEnum|string|null $queue
* @return $this
*/
public function onQueue($queue)
{
$this->queue = enum_value($queue);
return $this;
}
/**
* Set the desired job "group".
*
* This feature is only supported by some queues, such as Amazon SQS.
*
* @param \UnitEnum|string $group
* @return $this
*/
public function onGroup($group)
{
$this->messageGroup = enum_value($group);
return $this;
}
/**
* Set the desired job deduplicator callback.
*
* This feature is only supported by some queues, such as Amazon SQS FIFO.
*
* @param callable|null $deduplicator
* @return $this
*/
public function withDeduplicator($deduplicator)
{
$this->deduplicator = $deduplicator instanceof Closure
? new SerializableClosure($deduplicator)
: $deduplicator;
return $this;
}
/**
* Set the desired delay in seconds for the job.
*
* @param \DateTimeInterface|\DateInterval|int|null $delay
* @return $this
*/
public function delay($delay)
{
$this->delay = $delay;
return $this;
}
/**
* Specify a callback that should be invoked if the queued listener job fails.
*
* @param \Closure $closure
* @return $this
*/
public function catch(Closure $closure)
{
$this->catchCallbacks[] = $closure;
return $this;
}
/**
* Resolve the actual event listener callback.
*
* @return \Closure
*/
public function resolve()
{
return function (...$arguments) {
dispatch(new CallQueuedListener(InvokeQueuedClosure::class, 'handle', [
'closure' => new SerializableClosure($this->closure),
'arguments' => $arguments,
'catch' => (new Collection($this->catchCallbacks))
->map(fn ($callback) => new SerializableClosure($callback))
->all(),
]))
->onConnection($this->connection)
->onQueue($this->queue)
->delay($this->delay)
->onGroup($this->messageGroup)
->withDeduplicator($this->deduplicator);
};
}
}
| php | MIT | 4cd2bf391de735f631e57b4398d51b611f1a410e | 2026-01-05T05:08:15.237387Z | false |
illuminate/events | https://github.com/illuminate/events/blob/4cd2bf391de735f631e57b4398d51b611f1a410e/CallQueuedListener.php | CallQueuedListener.php | <?php
namespace Illuminate\Events;
use Illuminate\Bus\Queueable;
use Illuminate\Container\Container;
use Illuminate\Contracts\Queue\Job;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
class CallQueuedListener implements ShouldQueue
{
use InteractsWithQueue, Queueable;
/**
* The listener class name.
*
* @var class-string
*/
public $class;
/**
* The listener method.
*
* @var string
*/
public $method;
/**
* The data to be passed to the listener.
*
* @var array
*/
public $data;
/**
* The number of times the job may be attempted.
*
* @var int
*/
public $tries;
/**
* The maximum number of exceptions allowed, regardless of attempts.
*
* @var int
*/
public $maxExceptions;
/**
* The number of seconds to wait before retrying a job that encountered an uncaught exception.
*
* @var int
*/
public $backoff;
/**
* The timestamp indicating when the job should timeout.
*
* @var int
*/
public $retryUntil;
/**
* The number of seconds the job can run before timing out.
*
* @var int
*/
public $timeout;
/**
* Indicates if the job should fail if the timeout is exceeded.
*
* @var bool
*/
public $failOnTimeout = false;
/**
* Indicates if the job should be encrypted.
*
* @var bool
*/
public $shouldBeEncrypted = false;
/**
* Indicates if the job should be deleted when models are missing.
*
* @var bool
*/
public $deleteWhenMissingModels;
/**
* Create a new job instance.
*
* @param class-string $class
* @param string $method
* @param array $data
*/
public function __construct($class, $method, $data)
{
$this->data = $data;
$this->class = $class;
$this->method = $method;
}
/**
* Handle the queued job.
*
* @param \Illuminate\Container\Container $container
* @return void
*/
public function handle(Container $container)
{
$this->prepareData();
$handler = $this->setJobInstanceIfNecessary(
$this->job, $container->make($this->class)
);
$handler->{$this->method}(...array_values($this->data));
}
/**
* Set the job instance of the given class if necessary.
*
* @param \Illuminate\Contracts\Queue\Job $job
* @param object $instance
* @return object
*/
protected function setJobInstanceIfNecessary(Job $job, $instance)
{
if (in_array(InteractsWithQueue::class, class_uses_recursive($instance))) {
$instance->setJob($job);
}
return $instance;
}
/**
* Call the failed method on the job instance.
*
* The event instance and the exception will be passed.
*
* @param \Throwable $e
* @return void
*/
public function failed($e)
{
$this->prepareData();
$handler = Container::getInstance()->make($this->class);
$parameters = array_merge(array_values($this->data), [$e]);
if (method_exists($handler, 'failed')) {
$handler->failed(...$parameters);
}
}
/**
* Unserialize the data if needed.
*
* @return void
*/
protected function prepareData()
{
if (is_string($this->data)) {
$this->data = unserialize($this->data);
}
}
/**
* Get the display name for the queued job.
*
* @return string
*/
public function displayName()
{
return $this->class;
}
/**
* Prepare the instance for cloning.
*
* @return void
*/
public function __clone()
{
$this->data = array_map(function ($data) {
return is_object($data) ? clone $data : $data;
}, $this->data);
}
}
| php | MIT | 4cd2bf391de735f631e57b4398d51b611f1a410e | 2026-01-05T05:08:15.237387Z | false |
illuminate/events | https://github.com/illuminate/events/blob/4cd2bf391de735f631e57b4398d51b611f1a410e/functions.php | functions.php | <?php
namespace Illuminate\Events;
use Closure;
if (! function_exists('Illuminate\Events\queueable')) {
/**
* Create a new queued Closure event listener.
*
* @param \Closure $closure
*/
function queueable(Closure $closure): QueuedClosure
{
return new QueuedClosure($closure);
}
}
| php | MIT | 4cd2bf391de735f631e57b4398d51b611f1a410e | 2026-01-05T05:08:15.237387Z | false |
illuminate/events | https://github.com/illuminate/events/blob/4cd2bf391de735f631e57b4398d51b611f1a410e/Dispatcher.php | Dispatcher.php | <?php
namespace Illuminate\Events;
use Closure;
use Exception;
use Illuminate\Container\Container;
use Illuminate\Contracts\Broadcasting\Factory as BroadcastFactory;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Contracts\Container\Container as ContainerContract;
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Contracts\Events\ShouldHandleEventsAfterCommit;
use Illuminate\Contracts\Queue\ShouldBeEncrypted;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Contracts\Queue\ShouldQueueAfterCommit;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\Macroable;
use Illuminate\Support\Traits\ReflectsClosures;
use ReflectionClass;
use function Illuminate\Support\enum_value;
class Dispatcher implements DispatcherContract
{
use Macroable, ReflectsClosures;
/**
* The IoC container instance.
*
* @var \Illuminate\Contracts\Container\Container
*/
protected $container;
/**
* The registered event listeners.
*
* @var array<string, callable|array|class-string|null>
*/
protected $listeners = [];
/**
* The wildcard listeners.
*
* @var array<string, \Closure|string>
*/
protected $wildcards = [];
/**
* The cached wildcard listeners.
*
* @var array<string, \Closure|string>
*/
protected $wildcardsCache = [];
/**
* The queue resolver instance.
*
* @var callable(): \Illuminate\Contracts\Queue\Queue
*/
protected $queueResolver;
/**
* The database transaction manager resolver instance.
*
* @var callable
*/
protected $transactionManagerResolver;
/**
* The currently deferred events.
*
* @var array
*/
protected $deferredEvents = [];
/**
* Indicates if events should be deferred.
*
* @var bool
*/
protected $deferringEvents = false;
/**
* The specific events to defer (null means defer all events).
*
* @var string[]|null
*/
protected $eventsToDefer = null;
/**
* Create a new event dispatcher instance.
*
* @param \Illuminate\Contracts\Container\Container|null $container
*/
public function __construct(?ContainerContract $container = null)
{
$this->container = $container ?: new Container;
}
/**
* Register an event listener with the dispatcher.
*
* @param \Illuminate\Events\QueuedClosure|callable|array|class-string|string $events
* @param \Illuminate\Events\QueuedClosure|callable|array|class-string|null $listener
* @return void
*/
public function listen($events, $listener = null)
{
if ($events instanceof Closure) {
return (new Collection($this->firstClosureParameterTypes($events)))
->each(function ($event) use ($events) {
$this->listen($event, $events);
});
} elseif ($events instanceof QueuedClosure) {
return (new Collection($this->firstClosureParameterTypes($events->closure)))
->each(function ($event) use ($events) {
$this->listen($event, $events->resolve());
});
} elseif ($listener instanceof QueuedClosure) {
$listener = $listener->resolve();
}
foreach ((array) $events as $event) {
if (str_contains($event, '*')) {
$this->setupWildcardListen($event, $listener);
} else {
$this->listeners[$event][] = $listener;
}
}
}
/**
* Setup a wildcard listener callback.
*
* @param string $event
* @param \Closure|string $listener
* @return void
*/
protected function setupWildcardListen($event, $listener)
{
$this->wildcards[$event][] = $listener;
$this->wildcardsCache = [];
}
/**
* Determine if a given event has listeners.
*
* @param string $eventName
* @return bool
*/
public function hasListeners($eventName)
{
return isset($this->listeners[$eventName]) ||
isset($this->wildcards[$eventName]) ||
$this->hasWildcardListeners($eventName);
}
/**
* Determine if the given event has any wildcard listeners.
*
* @param string $eventName
* @return bool
*/
public function hasWildcardListeners($eventName)
{
foreach ($this->wildcards as $key => $listeners) {
if (Str::is($key, $eventName)) {
return true;
}
}
return false;
}
/**
* Register an event and payload to be fired later.
*
* @param string $event
* @param object|array $payload
* @return void
*/
public function push($event, $payload = [])
{
$this->listen($event.'_pushed', function () use ($event, $payload) {
$this->dispatch($event, $payload);
});
}
/**
* Flush a set of pushed events.
*
* @param string $event
* @return void
*/
public function flush($event)
{
$this->dispatch($event.'_pushed');
}
/**
* Register an event subscriber with the dispatcher.
*
* @param object|string $subscriber
* @return void
*/
public function subscribe($subscriber)
{
$subscriber = $this->resolveSubscriber($subscriber);
$events = $subscriber->subscribe($this);
if (is_array($events)) {
foreach ($events as $event => $listeners) {
foreach (Arr::wrap($listeners) as $listener) {
if (is_string($listener) && method_exists($subscriber, $listener)) {
$this->listen($event, [get_class($subscriber), $listener]);
continue;
}
$this->listen($event, $listener);
}
}
}
}
/**
* Resolve the subscriber instance.
*
* @param object|class-string $subscriber
* @return $subscriber is object ? object : mixed
*/
protected function resolveSubscriber($subscriber)
{
if (is_string($subscriber)) {
return $this->container->make($subscriber);
}
return $subscriber;
}
/**
* Fire an event until the first non-null response is returned.
*
* @param string|object $event
* @param mixed $payload
* @return array|null
*/
public function until($event, $payload = [])
{
return $this->dispatch($event, $payload, true);
}
/**
* Fire an event and call the listeners.
*
* @param string|object $event
* @param mixed $payload
* @param bool $halt
* @return array|null
*/
public function dispatch($event, $payload = [], $halt = false)
{
// When the given "event" is actually an object, we will assume it is an event
// object, and use the class as the event name and this event itself as the
// payload to the handler, which makes object-based events quite simple.
[$isEventObject, $parsedEvent, $parsedPayload] = [
is_object($event),
...$this->parseEventAndPayload($event, $payload),
];
if ($this->shouldDeferEvent($parsedEvent)) {
$this->deferredEvents[] = func_get_args();
return null;
}
// If the event is not intended to be dispatched unless the current database
// transaction is successful, we'll register a callback which will handle
// dispatching this event on the next successful DB transaction commit.
if ($isEventObject &&
$parsedPayload[0] instanceof ShouldDispatchAfterCommit &&
! is_null($transactions = $this->resolveTransactionManager())) {
$transactions->addCallback(
fn () => $this->invokeListeners($parsedEvent, $parsedPayload, $halt)
);
return null;
}
return $this->invokeListeners($parsedEvent, $parsedPayload, $halt);
}
/**
* Broadcast an event and call its listeners.
*
* @param string|object $event
* @param mixed $payload
* @param bool $halt
* @return array|null
*/
protected function invokeListeners($event, $payload, $halt = false)
{
if ($this->shouldBroadcast($payload)) {
$this->broadcastEvent($payload[0]);
}
$responses = [];
foreach ($this->getListeners($event) as $listener) {
$response = $listener($event, $payload);
// If a response is returned from the listener and event halting is enabled
// we will just return this response, and not call the rest of the event
// listeners. Otherwise we will add the response on the response list.
if ($halt && ! is_null($response)) {
return $response;
}
// If a boolean false is returned from a listener, we will stop propagating
// the event to any further listeners down in the chain, else we keep on
// looping through the listeners and firing every one in our sequence.
if ($response === false) {
break;
}
$responses[] = $response;
}
return $halt ? null : $responses;
}
/**
* Parse the given event and payload and prepare them for dispatching.
*
* @param mixed $event
* @param mixed $payload
* @return array{string, array}
*/
protected function parseEventAndPayload($event, $payload)
{
if (is_object($event)) {
[$payload, $event] = [[$event], get_class($event)];
}
return [$event, Arr::wrap($payload)];
}
/**
* Determine if the payload has a broadcastable event.
*
* @param array $payload
* @return bool
*/
protected function shouldBroadcast(array $payload)
{
return isset($payload[0]) &&
$payload[0] instanceof ShouldBroadcast &&
$this->broadcastWhen($payload[0]);
}
/**
* Check if the event should be broadcasted by the condition.
*
* @param mixed $event
* @return bool
*/
protected function broadcastWhen($event)
{
return method_exists($event, 'broadcastWhen')
? $event->broadcastWhen()
: true;
}
/**
* Broadcast the given event class.
*
* @param \Illuminate\Contracts\Broadcasting\ShouldBroadcast $event
* @return void
*/
protected function broadcastEvent($event)
{
$this->container->make(BroadcastFactory::class)->queue($event);
}
/**
* Get all of the listeners for a given event name.
*
* @param string $eventName
* @return array
*/
public function getListeners($eventName)
{
$listeners = array_merge(
$this->prepareListeners($eventName),
$this->wildcardsCache[$eventName] ?? $this->getWildcardListeners($eventName)
);
return class_exists($eventName, false)
? $this->addInterfaceListeners($eventName, $listeners)
: $listeners;
}
/**
* Get the wildcard listeners for the event.
*
* @param string $eventName
* @return array
*/
protected function getWildcardListeners($eventName)
{
$wildcards = [];
foreach ($this->wildcards as $key => $listeners) {
if (Str::is($key, $eventName)) {
foreach ($listeners as $listener) {
$wildcards[] = $this->makeListener($listener, true);
}
}
}
return $this->wildcardsCache[$eventName] = $wildcards;
}
/**
* Add the listeners for the event's interfaces to the given array.
*
* @param string $eventName
* @param array $listeners
* @return array
*/
protected function addInterfaceListeners($eventName, array $listeners = [])
{
foreach (class_implements($eventName) as $interface) {
if (isset($this->listeners[$interface])) {
foreach ($this->prepareListeners($interface) as $names) {
$listeners = array_merge($listeners, (array) $names);
}
}
}
return $listeners;
}
/**
* Prepare the listeners for a given event.
*
* @param string $eventName
* @return \Closure[]
*/
protected function prepareListeners(string $eventName)
{
$listeners = [];
foreach ($this->listeners[$eventName] ?? [] as $listener) {
$listeners[] = $this->makeListener($listener);
}
return $listeners;
}
/**
* Register an event listener with the dispatcher.
*
* @param \Closure|string|array{class-string, string} $listener
* @param bool $wildcard
* @return \Closure
*/
public function makeListener($listener, $wildcard = false)
{
if (is_string($listener)) {
return $this->createClassListener($listener, $wildcard);
}
if (is_array($listener) && isset($listener[0]) && is_string($listener[0])) {
return $this->createClassListener($listener, $wildcard);
}
return function ($event, $payload) use ($listener, $wildcard) {
if ($wildcard) {
return $listener($event, $payload);
}
return $listener(...array_values($payload));
};
}
/**
* Create a class based listener using the IoC container.
*
* @param string $listener
* @param bool $wildcard
* @return \Closure
*/
public function createClassListener($listener, $wildcard = false)
{
return function ($event, $payload) use ($listener, $wildcard) {
if ($wildcard) {
return call_user_func($this->createClassCallable($listener), $event, $payload);
}
$callable = $this->createClassCallable($listener);
return $callable(...array_values($payload));
};
}
/**
* Create the class based event callable.
*
* @param array{class-string, string}|string $listener
* @return callable
*/
protected function createClassCallable($listener)
{
[$class, $method] = is_array($listener)
? $listener
: $this->parseClassCallable($listener);
if (! method_exists($class, $method)) {
$method = '__invoke';
}
if ($this->handlerShouldBeQueued($class)) {
return $this->createQueuedHandlerCallable($class, $method);
}
$listener = $this->container->make($class);
return $this->handlerShouldBeDispatchedAfterDatabaseTransactions($listener)
? $this->createCallbackForListenerRunningAfterCommits($listener, $method)
: [$listener, $method];
}
/**
* Parse the class listener into class and method.
*
* @param string $listener
* @return array{class-string, string}
*/
protected function parseClassCallable($listener)
{
return Str::parseCallback($listener, 'handle');
}
/**
* Determine if the event handler class should be queued.
*
* @param class-string $class
* @return bool
*
* @phpstan-assert-if-true \Illuminate\Contracts\Queue\ShouldQueue $class
*/
protected function handlerShouldBeQueued($class)
{
try {
return (new ReflectionClass($class))->implementsInterface(
ShouldQueue::class
);
} catch (Exception) {
return false;
}
}
/**
* Create a callable for putting an event handler on the queue.
*
* @param class-string $class
* @param string $method
* @return \Closure(): void
*/
protected function createQueuedHandlerCallable($class, $method)
{
return function () use ($class, $method) {
$arguments = array_map(function ($a) {
return is_object($a) ? clone $a : $a;
}, func_get_args());
if ($this->handlerWantsToBeQueued($class, $arguments)) {
$this->queueHandler($class, $method, $arguments);
}
};
}
/**
* Determine if the given event handler should be dispatched after all database transactions have committed.
*
* @param mixed $listener
* @return bool
*/
protected function handlerShouldBeDispatchedAfterDatabaseTransactions($listener)
{
return (($listener->afterCommit ?? null) ||
$listener instanceof ShouldHandleEventsAfterCommit) &&
$this->resolveTransactionManager();
}
/**
* Create a callable for dispatching a listener after database transactions.
*
* @param mixed $listener
* @param string $method
* @return \Closure
*/
protected function createCallbackForListenerRunningAfterCommits($listener, $method)
{
return function () use ($method, $listener) {
$payload = func_get_args();
$this->resolveTransactionManager()->addCallback(
function () use ($listener, $method, $payload) {
$listener->$method(...$payload);
}
);
};
}
/**
* Determine if the event handler wants to be queued.
*
* @param class-string $class
* @param array $arguments
* @return bool
*/
protected function handlerWantsToBeQueued($class, $arguments)
{
$instance = $this->container->make($class);
if (method_exists($instance, 'shouldQueue')) {
return $instance->shouldQueue($arguments[0]);
}
return true;
}
/**
* Queue the handler class.
*
* @param string $class
* @param string $method
* @param array $arguments
* @return void
*/
protected function queueHandler($class, $method, $arguments)
{
[$listener, $job] = $this->createListenerAndJob($class, $method, $arguments);
$connection = $this->resolveQueue()->connection(method_exists($listener, 'viaConnection')
? (isset($arguments[0]) ? $listener->viaConnection($arguments[0]) : $listener->viaConnection())
: $listener->connection ?? null);
$queue = method_exists($listener, 'viaQueue')
? (isset($arguments[0]) ? $listener->viaQueue($arguments[0]) : $listener->viaQueue())
: $listener->queue ?? null;
$delay = method_exists($listener, 'withDelay')
? (isset($arguments[0]) ? $listener->withDelay($arguments[0]) : $listener->withDelay())
: $listener->delay ?? null;
is_null($delay)
? $connection->pushOn(enum_value($queue), $job)
: $connection->laterOn(enum_value($queue), $delay, $job);
}
/**
* Create the listener and job for a queued listener.
*
* @template TListener
*
* @param class-string<TListener> $class
* @param string $method
* @param array $arguments
* @return array{TListener, mixed}
*/
protected function createListenerAndJob($class, $method, $arguments)
{
$listener = (new ReflectionClass($class))->newInstanceWithoutConstructor();
return [$listener, $this->propagateListenerOptions(
$listener, new CallQueuedListener($class, $method, $arguments)
)];
}
/**
* Propagate listener options to the job.
*
* @param mixed $listener
* @param \Illuminate\Events\CallQueuedListener $job
* @return \Illuminate\Events\CallQueuedListener
*/
protected function propagateListenerOptions($listener, $job)
{
return tap($job, function ($job) use ($listener) {
$data = array_values($job->data);
if ($listener instanceof ShouldQueueAfterCommit) {
$job->afterCommit = true;
} else {
$job->afterCommit = property_exists($listener, 'afterCommit') ? $listener->afterCommit : null;
}
$job->backoff = method_exists($listener, 'backoff') ? $listener->backoff(...$data) : ($listener->backoff ?? null);
$job->maxExceptions = $listener->maxExceptions ?? null;
$job->retryUntil = method_exists($listener, 'retryUntil') ? $listener->retryUntil(...$data) : null;
$job->shouldBeEncrypted = $listener instanceof ShouldBeEncrypted;
$job->timeout = $listener->timeout ?? null;
$job->failOnTimeout = $listener->failOnTimeout ?? false;
$job->deleteWhenMissingModels = $listener->deleteWhenMissingModels ?? false;
$job->tries = method_exists($listener, 'tries') ? $listener->tries(...$data) : ($listener->tries ?? null);
$job->messageGroup = method_exists($listener, 'messageGroup') ? $listener->messageGroup(...$data) : ($listener->messageGroup ?? null);
$job->withDeduplicator(method_exists($listener, 'deduplicator')
? $listener->deduplicator(...$data)
: (method_exists($listener, 'deduplicationId') ? $listener->deduplicationId(...) : null)
);
$job->through(array_merge(
method_exists($listener, 'middleware') ? $listener->middleware(...$data) : [],
$listener->middleware ?? []
));
});
}
/**
* Remove a set of listeners from the dispatcher.
*
* @param string $event
* @return void
*/
public function forget($event)
{
if (str_contains($event, '*')) {
unset($this->wildcards[$event]);
} else {
unset($this->listeners[$event]);
}
foreach ($this->wildcardsCache as $key => $listeners) {
if (Str::is($event, $key)) {
unset($this->wildcardsCache[$key]);
}
}
}
/**
* Forget all of the pushed listeners.
*
* @return void
*/
public function forgetPushed()
{
foreach ($this->listeners as $key => $value) {
if (str_ends_with($key, '_pushed')) {
$this->forget($key);
}
}
}
/**
* Get the queue implementation from the resolver.
*
* @return \Illuminate\Contracts\Queue\Queue
*/
protected function resolveQueue()
{
return call_user_func($this->queueResolver);
}
/**
* Set the queue resolver implementation.
*
* @param callable(): \Illuminate\Contracts\Queue\Queue $resolver
* @return $this
*/
public function setQueueResolver(callable $resolver)
{
$this->queueResolver = $resolver;
return $this;
}
/**
* Get the database transaction manager implementation from the resolver.
*
* @return \Illuminate\Database\DatabaseTransactionsManager|null
*/
protected function resolveTransactionManager()
{
return call_user_func($this->transactionManagerResolver);
}
/**
* Set the database transaction manager resolver implementation.
*
* @param (callable(): \Illuminate\Database\DatabaseTransactionsManager|null) $resolver
* @return $this
*/
public function setTransactionManagerResolver(callable $resolver)
{
$this->transactionManagerResolver = $resolver;
return $this;
}
/**
* Execute the given callback while deferring events, then dispatch all deferred events.
*
* @template TResult
*
* @param callable(): TResult $callback
* @param string[]|null $events
* @return TResult
*/
public function defer(callable $callback, ?array $events = null)
{
$wasDeferring = $this->deferringEvents;
$previousDeferredEvents = $this->deferredEvents;
$previousEventsToDefer = $this->eventsToDefer;
$this->deferringEvents = true;
$this->deferredEvents = [];
$this->eventsToDefer = $events;
try {
$result = $callback();
$this->deferringEvents = false;
foreach ($this->deferredEvents as $args) {
$this->dispatch(...$args);
}
return $result;
} finally {
$this->deferringEvents = $wasDeferring;
$this->deferredEvents = $previousDeferredEvents;
$this->eventsToDefer = $previousEventsToDefer;
}
}
/**
* Determine if the given event should be deferred.
*
* @param string $event
* @return bool
*/
protected function shouldDeferEvent(string $event)
{
return $this->deferringEvents && ($this->eventsToDefer === null || in_array($event, $this->eventsToDefer));
}
/**
* Gets the raw, unprepared listeners.
*
* @return array
*/
public function getRawListeners()
{
return $this->listeners;
}
}
| php | MIT | 4cd2bf391de735f631e57b4398d51b611f1a410e | 2026-01-05T05:08:15.237387Z | false |
illuminate/events | https://github.com/illuminate/events/blob/4cd2bf391de735f631e57b4398d51b611f1a410e/NullDispatcher.php | NullDispatcher.php | <?php
namespace Illuminate\Events;
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Support\Traits\ForwardsCalls;
class NullDispatcher implements DispatcherContract
{
use ForwardsCalls;
/**
* The underlying event dispatcher instance.
*
* @var \Illuminate\Contracts\Events\Dispatcher
*/
protected $dispatcher;
/**
* Create a new event dispatcher instance that does not fire.
*
* @param \Illuminate\Contracts\Events\Dispatcher $dispatcher
*/
public function __construct(DispatcherContract $dispatcher)
{
$this->dispatcher = $dispatcher;
}
/**
* Don't fire an event.
*
* @param string|object $event
* @param mixed $payload
* @param bool $halt
* @return void
*/
public function dispatch($event, $payload = [], $halt = false)
{
//
}
/**
* Don't register an event and payload to be fired later.
*
* @param string $event
* @param array $payload
* @return void
*/
public function push($event, $payload = [])
{
//
}
/**
* Don't dispatch an event.
*
* @param string|object $event
* @param mixed $payload
* @return mixed
*/
public function until($event, $payload = [])
{
//
}
/**
* Register an event listener with the dispatcher.
*
* @param \Closure|string|array $events
* @param \Closure|string|array|null $listener
* @return void
*/
public function listen($events, $listener = null)
{
$this->dispatcher->listen($events, $listener);
}
/**
* Determine if a given event has listeners.
*
* @param string $eventName
* @return bool
*/
public function hasListeners($eventName)
{
return $this->dispatcher->hasListeners($eventName);
}
/**
* Register an event subscriber with the dispatcher.
*
* @param object|string $subscriber
* @return void
*/
public function subscribe($subscriber)
{
$this->dispatcher->subscribe($subscriber);
}
/**
* Flush a set of pushed events.
*
* @param string $event
* @return void
*/
public function flush($event)
{
$this->dispatcher->flush($event);
}
/**
* Remove a set of listeners from the dispatcher.
*
* @param string $event
* @return void
*/
public function forget($event)
{
$this->dispatcher->forget($event);
}
/**
* Forget all of the queued listeners.
*
* @return void
*/
public function forgetPushed()
{
$this->dispatcher->forgetPushed();
}
/**
* Dynamically pass method calls to the underlying dispatcher.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
return $this->forwardDecoratedCallTo($this->dispatcher, $method, $parameters);
}
}
| php | MIT | 4cd2bf391de735f631e57b4398d51b611f1a410e | 2026-01-05T05:08:15.237387Z | false |
illuminate/events | https://github.com/illuminate/events/blob/4cd2bf391de735f631e57b4398d51b611f1a410e/EventServiceProvider.php | EventServiceProvider.php | <?php
namespace Illuminate\Events;
use Illuminate\Contracts\Queue\Factory as QueueFactoryContract;
use Illuminate\Support\ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton('events', function ($app) {
return (new Dispatcher($app))->setQueueResolver(function () use ($app) {
return $app->make(QueueFactoryContract::class);
})->setTransactionManagerResolver(function () use ($app) {
return $app->bound('db.transactions')
? $app->make('db.transactions')
: null;
});
});
}
}
| php | MIT | 4cd2bf391de735f631e57b4398d51b611f1a410e | 2026-01-05T05:08:15.237387Z | false |
renoki-co/laravel-sns-events | https://github.com/renoki-co/laravel-sns-events/blob/a36a61aff3fb3005aafda799d5d6c69e72a71a9c/src/LaravelSnsEventsServiceProvider.php | src/LaravelSnsEventsServiceProvider.php | <?php
namespace Rennokki\LaravelSnsEvents;
use Illuminate\Support\ServiceProvider;
class LaravelSnsEventsServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
//
}
}
| php | Apache-2.0 | a36a61aff3fb3005aafda799d5d6c69e72a71a9c | 2026-01-05T05:08:32.238986Z | false |
renoki-co/laravel-sns-events | https://github.com/renoki-co/laravel-sns-events/blob/a36a61aff3fb3005aafda799d5d6c69e72a71a9c/src/Http/Controllers/SnsController.php | src/Http/Controllers/SnsController.php | <?php
namespace Rennokki\LaravelSnsEvents\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Rennokki\LaravelSnsEvents\Concerns\HandlesSns;
use Rennokki\LaravelSnsEvents\Events\SnsNotification;
use Rennokki\LaravelSnsEvents\Events\SnsSubscriptionConfirmation;
class SnsController extends Controller
{
use HandlesSns;
/**
* Handle the incoming SNS event.
*
* @param \Illuminate\Http\Request $request
* @return mixed
*/
public function handle(Request $request)
{
if (! $this->snsMessageIsValid($request)) {
return $this->okStatus();
}
$snsMessage = $this->getSnsMessage($request)->toArray();
if (isset($snsMessage['Type'])) {
if ($snsMessage['Type'] === 'SubscriptionConfirmation') {
@file_get_contents($snsMessage['SubscribeURL']);
$class = $this->getSubscriptionConfirmationEventClass();
event(new $class(
$this->getSubscriptionConfirmationPayload($snsMessage, $request)
));
call_user_func([$this, 'onSubscriptionConfirmation'], $snsMessage, $request);
}
if ($snsMessage['Type'] === 'Notification') {
$class = $this->getNotificationEventClass();
event(new $class(
$this->getNotificationPayload($snsMessage, $request)
));
call_user_func([$this, 'onNotification'], $snsMessage, $request);
}
}
return $this->okStatus();
}
/**
* Get the event payload to stream to the event in case
* AWS sent a notification payload.
*
* @param array $snsMessage
* @param \Illuminate\Http\Request $request
* @return array
*/
protected function getNotificationPayload(array $snsMessage, Request $request): array
{
return [
'message' => $snsMessage,
'headers' => $request->headers->all(),
];
}
/**
* Get the event payload to stream to the event in case
* AWS sent a subscription confirmation payload.
*
* @param array $snsMessage
* @param \Illuminate\Http\Request $request
* @return array
*/
protected function getSubscriptionConfirmationPayload(array $snsMessage, Request $request): array
{
return $this->getNotificationPayload($snsMessage, $request);
}
/**
* Get the event class to trigger during subscription confirmation.
*
* @return string
*/
protected function getSubscriptionConfirmationEventClass(): string
{
return SnsSubscriptionConfirmation::class;
}
/**
* Get the event class to trigger during SNS event.
*
* @return string
*/
protected function getNotificationEventClass(): string
{
return SnsNotification::class;
}
/**
* Handle logic at the controller level on notification.
*
* @param array $snsMessage
* @param \Illuminate\Http\Request $request
* @return void
*/
protected function onNotification(array $snsMessage, Request $request): void
{
//
}
/**
* Handle logic at the controller level on subscription.
*
* @param array $snsMessage
* @param \Illuminate\Http\Request $request
* @return void
*/
protected function onSubscriptionConfirmation(array $snsMessage, Request $request): void
{
//
}
/**
* Get a 200 OK status.
*
* @return \Illuminate\Http\Response
*/
protected function okStatus()
{
return response('OK', 200);
}
}
| php | Apache-2.0 | a36a61aff3fb3005aafda799d5d6c69e72a71a9c | 2026-01-05T05:08:32.238986Z | false |
renoki-co/laravel-sns-events | https://github.com/renoki-co/laravel-sns-events/blob/a36a61aff3fb3005aafda799d5d6c69e72a71a9c/src/Concerns/HandlesSns.php | src/Concerns/HandlesSns.php | <?php
namespace Rennokki\LaravelSnsEvents\Concerns;
use Aws\Sns\Message;
use Aws\Sns\MessageValidator;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
trait HandlesSns
{
/**
* Get the SNS message as array.
*
* @param \Illuminate\Http\Request $request
* @return \Aws\Sns\Message
*/
public function getSnsMessage(Request $request)
{
try {
return Message::fromJsonString(
$request->getContent() ?: file_get_contents('php://input')
);
} catch (Exception $e) {
return new Message([]);
}
}
/**
* Check if the SNS message is valid.
*
* @param \Illuminate\Http\Request $request
* @return bool
*/
public function snsMessageIsValid(Request $request): bool
{
try {
return $this->getMessageValidator($request)->isValid(
$this->getSnsMessage($request)
);
} catch (Exception $e) {
return false;
}
}
/**
* Get the message validator instance.
*
* @param \Illuminate\Http\Request $request
* @return \Aws\Sns\MessageValidator
*/
protected function getMessageValidator(Request $request)
{
if (App::environment(['testing', 'local'])) {
return new MessageValidator(function ($url) use ($request) {
if ($certificate = $request->sns_certificate) {
return $certificate;
}
if ($certificate = $request->header('X-Sns-Testing-Certificate')) {
return $certificate;
}
return $url;
});
}
return new MessageValidator;
}
}
| php | Apache-2.0 | a36a61aff3fb3005aafda799d5d6c69e72a71a9c | 2026-01-05T05:08:32.238986Z | false |
renoki-co/laravel-sns-events | https://github.com/renoki-co/laravel-sns-events/blob/a36a61aff3fb3005aafda799d5d6c69e72a71a9c/src/Concerns/GeneratesSnsMessages.php | src/Concerns/GeneratesSnsMessages.php | <?php
namespace Rennokki\LaravelSnsEvents\Concerns;
use Aws\Sns\Message;
use Aws\Sns\MessageValidator;
trait GeneratesSnsMessages
{
/**
* Get the private key to sign the request for SNS.
*
* @var string
*/
protected static $snsPrivateKey;
/**
* The certificate to sign the request for SNS.
*
* @var string
*/
protected static $snsCertificate;
/**
* An valid certificate URL to test SNS.
*
* @var string
*/
public static $snsValidCertUrl = 'https://sns.us-west-2.amazonaws.com/bar.pem';
/**
* Initialize the SSL keys and private keys.
*
* @return void
*/
protected static function initializeSsl(): void
{
static::$snsPrivateKey = openssl_pkey_new();
$csr = openssl_csr_new([], static::$snsPrivateKey);
$x509 = openssl_csr_sign($csr, null, static::$snsPrivateKey, 1);
openssl_x509_export($x509, static::$snsCertificate);
}
/**
* Get the signature for the message.
*
* @param string $stringToSign
* @return string
*/
protected function getSignature($stringToSign)
{
static::initializeSsl();
openssl_sign($stringToSign, $signature, static::$snsPrivateKey);
return base64_encode($signature);
}
/**
* Get an example subscription payload for testing.
*
* @param array $custom
* @return array
*/
protected function getSubscriptionConfirmationPayload(array $custom = []): array
{
$validator = new MessageValidator;
$message = array_merge([
'Type' => 'SubscriptionConfirmation',
'MessageId' => '165545c9-2a5c-472c-8df2-7ff2be2b3b1b',
'Token' => '2336412f37...',
'TopicArn' => 'arn:aws:sns:us-west-2:123456789012:MyTopic',
'Message' => 'You have chosen to subscribe to the topic arn:aws:sns:us-west-2:123456789012:MyTopic.\nTo confirm the subscription, visit the SubscribeURL included in this message.',
'SubscribeURL' => 'https://example.com',
'Timestamp' => now()->toDateTimeString(),
'SignatureVersion' => '1',
'Signature' => true,
'SigningCertURL' => static::$snsValidCertUrl,
], $custom);
$message['Signature'] = $this->getSignature(
$validator->getStringToSign(new Message($message))
);
return $message;
}
/**
* Get an example notification payload for testing.
*
* @param array $payload
* @param array $custom
* @return array
*/
protected function getNotificationPayload(array $payload = [], array $custom = []): array
{
$validator = new MessageValidator;
$payload = json_encode($payload);
$message = array_merge([
'Type' => 'Notification',
'MessageId' => '22b80b92-fdea-4c2c-8f9d-bdfb0c7bf324',
'TopicArn' => 'arn:aws:sns:us-west-2:123456789012:MyTopic',
'Subject' => 'My First Message',
'Message' => "{$payload}",
'Timestamp' => now()->toDateTimeString(),
'SignatureVersion' => '1',
'Token' => '2336412f37...',
'Signature' => true,
'SigningCertURL' => static::$snsValidCertUrl,
'UnsubscribeURL' => 'https://sns.us-west-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-west-2:123456789012:MyTopic:c9135db0-26c4-47ec-8998-413945fb5a96',
], $custom);
$message['Signature'] = $this->getSignature(
$validator->getStringToSign(new Message($message))
);
return $message;
}
/**
* Send the SNS-signed message to the given URL.
*
* @param string $url
* @param array $snsPayload
* @return \Illuminate\Testing\TestResponse
*/
protected function sendSnsMessage($url, array $snsPayload = [])
{
/** @var \Illuminate\Foundation\Testing\Concerns\MakesHttpRequests&\Rennokki\LaravelSnsEvents\Concerns\GeneratesSnsMessages $this */
return $this->withHeaders($this->getHeadersForMessage($snsPayload))
->withHeaders(['X-Sns-Testing-Certificate' => static::$snsCertificate])
->json('POST', $url, $snsPayload);
}
/**
* Get the right headers for a SNS message.
*
* @param array $message
* @return array
*/
protected function getHeadersForMessage(array $message): array
{
return [
'X-AMZ-SNS-MESSAGE-TYPE' => $message['Type'] ?? null,
'X-AMZ-SNS-MESSAGE-ID' => $message['MessageId'] ?? null,
'X-AMZ-SNS-TOPIC-ARN' => $message['TopicArn'] ?? null,
'X-AMZ-SNS-SUBSCRIPTION-ARN' => ($message['TopicArn'] ?? null).':c9135db0-26c4-47ec-8998-413945fb5a96',
];
}
}
| php | Apache-2.0 | a36a61aff3fb3005aafda799d5d6c69e72a71a9c | 2026-01-05T05:08:32.238986Z | false |
renoki-co/laravel-sns-events | https://github.com/renoki-co/laravel-sns-events/blob/a36a61aff3fb3005aafda799d5d6c69e72a71a9c/src/Events/SnsNotification.php | src/Events/SnsNotification.php | <?php
namespace Rennokki\LaravelSnsEvents\Events;
class SnsNotification
{
/**
* The payload to be delivered in the listeners.
*
* @var array
*/
public $payload;
/**
* Create a new event instance.
*
* @param array $payload
* @return void
*/
public function __construct($payload)
{
$this->payload = $payload;
}
}
| php | Apache-2.0 | a36a61aff3fb3005aafda799d5d6c69e72a71a9c | 2026-01-05T05:08:32.238986Z | false |
renoki-co/laravel-sns-events | https://github.com/renoki-co/laravel-sns-events/blob/a36a61aff3fb3005aafda799d5d6c69e72a71a9c/src/Events/SnsSubscriptionConfirmation.php | src/Events/SnsSubscriptionConfirmation.php | <?php
namespace Rennokki\LaravelSnsEvents\Events;
class SnsSubscriptionConfirmation extends SnsNotification
{
//
}
| php | Apache-2.0 | a36a61aff3fb3005aafda799d5d6c69e72a71a9c | 2026-01-05T05:08:32.238986Z | false |
renoki-co/laravel-sns-events | https://github.com/renoki-co/laravel-sns-events/blob/a36a61aff3fb3005aafda799d5d6c69e72a71a9c/tests/EventTest.php | tests/EventTest.php | <?php
namespace Rennokki\LaravelSnsEvents\Tests;
use Illuminate\Support\Facades\Event;
use Rennokki\LaravelSnsEvents\Events\SnsNotification;
use Rennokki\LaravelSnsEvents\Events\SnsSubscriptionConfirmation;
use Rennokki\LaravelSnsEvents\Tests\Events\CustomSnsEvent;
use Rennokki\LaravelSnsEvents\Tests\Events\CustomSubscriptionConfirmation;
class EventTest extends TestCase
{
public function test_no_event_triggering_on_bad_request()
{
Event::fake();
$this->sendSnsMessage(route('sns'))->assertSee('OK');
Event::assertNotDispatched(SnsNotification::class);
Event::assertNotDispatched(SnsSubscriptionConfirmation::class);
$this->sendSnsMessage(route('sns'))->assertSee('OK');
Event::assertNotDispatched(SnsNotification::class);
Event::assertNotDispatched(SnsSubscriptionConfirmation::class);
$payload = $this->getSubscriptionConfirmationPayload();
$this->sendSnsMessage(route('sns'))->assertSee('OK');
Event::assertNotDispatched(SnsNotification::class);
Event::assertNotDispatched(SnsSubscriptionConfirmation::class);
}
public function test_subscription_confirmation()
{
Event::fake();
$payload = $this->getSubscriptionConfirmationPayload();
$this->withHeaders(['x-test-header' => 1])
->sendSnsMessage(route('sns'), $payload)
->assertSee('OK');
Event::assertNotDispatched(SnsNotification::class);
Event::assertDispatched(SnsSubscriptionConfirmation::class, function ($event) {
$this->assertTrue(
isset($event->payload['headers']['x-test-header'])
);
return true;
});
}
public function test_notification_confirmation()
{
Event::fake();
$payload = $this->getNotificationPayload([
'test' => 1,
'sns' => true,
]);
$this->withHeaders(['x-test-header' => 1])
->sendSnsMessage(route('sns'), $payload)
->assertSee('OK');
Event::assertNotDispatched(SnsSubscriptionConfirmation::class);
Event::assertDispatched(SnsNotification::class, function ($event) {
$this->assertTrue(
isset($event->payload['headers']['x-test-header'])
);
$message = json_decode(
$event->payload['message']['Message'], true
);
$this->assertEquals(1, $message['test']);
$this->assertEquals(true, $message['sns']);
return true;
});
}
public function test_custom_controller_confirmation()
{
Event::fake();
$payload = $this->getSubscriptionConfirmationPayload();
$this->withHeaders(['x-test-header' => 1])
->sendSnsMessage(route('custom-sns', ['test' => 'some-string']), $payload)
->assertSee('OK');
Event::assertNotDispatched(CustomSnsEvent::class);
Event::assertDispatched(CustomSubscriptionConfirmation::class, function ($event) {
$this->assertEquals(
'some-string', $event->payload['confirmation_test']
);
$this->assertFalse(
isset($event->payload['headers'])
);
return true;
});
}
public function test_custom_controller_notification()
{
Event::fake();
$payload = $this->getNotificationPayload([
'test' => 1,
'sns' => true,
]);
$this->withHeaders(['x-test-header' => 1])
->sendSnsMessage(route('custom-sns', ['test' => 'some-string']), $payload)
->assertSee('OK');
Event::assertNotDispatched(CustomSubscriptionConfirmation::class);
Event::assertDispatched(CustomSnsEvent::class, function ($event) {
$this->assertEquals(
'some-string', $event->payload['test']
);
$this->assertFalse(
isset($event->payload['headers'])
);
$message = json_decode(
$event->payload['message']['Message'], true
);
$this->assertEquals(1, $message['test']);
$this->assertEquals(true, $message['sns']);
return true;
});
}
}
| php | Apache-2.0 | a36a61aff3fb3005aafda799d5d6c69e72a71a9c | 2026-01-05T05:08:32.238986Z | false |
renoki-co/laravel-sns-events | https://github.com/renoki-co/laravel-sns-events/blob/a36a61aff3fb3005aafda799d5d6c69e72a71a9c/tests/TestCase.php | tests/TestCase.php | <?php
namespace Rennokki\LaravelSnsEvents\Tests;
use Orchestra\Testbench\TestCase as Orchestra;
use Rennokki\LaravelSnsEvents\Concerns\GeneratesSnsMessages;
class TestCase extends Orchestra
{
use GeneratesSnsMessages;
/**
* Get package providers.
*
* @param \Illuminate\Foundation\Application $app
* @return array
*/
protected function getPackageProviders($app)
{
return [
\Rennokki\LaravelSnsEvents\LaravelSnsEventsServiceProvider::class,
TestServiceProvider::class,
];
}
/**
* {@inheritdoc}
*/
protected function getEnvironmentSetUp($app)
{
$app['config']->set('app.key', '6rE9Nz59bGRbeMATftriyQjrpF7DcOQm');
}
}
| php | Apache-2.0 | a36a61aff3fb3005aafda799d5d6c69e72a71a9c | 2026-01-05T05:08:32.238986Z | false |
renoki-co/laravel-sns-events | https://github.com/renoki-co/laravel-sns-events/blob/a36a61aff3fb3005aafda799d5d6c69e72a71a9c/tests/TestServiceProvider.php | tests/TestServiceProvider.php | <?php
namespace Rennokki\LaravelSnsEvents\Tests;
use Illuminate\Support\ServiceProvider;
class TestServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
$this->loadRoutesFrom(__DIR__.'/routes/web.php');
}
}
| php | Apache-2.0 | a36a61aff3fb3005aafda799d5d6c69e72a71a9c | 2026-01-05T05:08:32.238986Z | false |
renoki-co/laravel-sns-events | https://github.com/renoki-co/laravel-sns-events/blob/a36a61aff3fb3005aafda799d5d6c69e72a71a9c/tests/Controllers/CustomSnsController.php | tests/Controllers/CustomSnsController.php | <?php
namespace Rennokki\LaravelSnsEvents\Tests\Controllers;
use Illuminate\Http\Request;
use Rennokki\LaravelSnsEvents\Http\Controllers\SnsController;
use Rennokki\LaravelSnsEvents\Tests\Events\CustomSnsEvent;
use Rennokki\LaravelSnsEvents\Tests\Events\CustomSubscriptionConfirmation;
class CustomSnsController extends SnsController
{
/**
* Get the event payload to stream to the event in case
* AWS sent a notification payload.
*
* @param array $snsMessage
* @param \Illuminate\Http\Request $request
* @return array
*/
protected function getNotificationPayload(array $snsMessage, Request $request): array
{
return [
'message' => $snsMessage,
'test' => $request->query('test'),
];
}
/**
* Get the event payload to stream to the event in case
* AWS sent a subscription confirmation payload.
*
* @param array $snsMessage
* @param \Illuminate\Http\Request $request
* @return array
*/
protected function getSubscriptionConfirmationPayload(array $snsMessage, Request $request): array
{
return [
'message' => $snsMessage,
'confirmation_test' => $request->query('test'),
'on_subscription_confirmation' => $request->onSubscriptionConfirmation,
'on_notification' => $request->onNotification,
];
}
/**
* Get the event class to trigger during subscription confirmation.
*
* @return string
*/
protected function getSubscriptionConfirmationEventClass(): string
{
return CustomSubscriptionConfirmation::class;
}
/**
* Get the event class to trigger during SNS event.
*
* @return string
*/
protected function getNotificationEventClass(): string
{
return CustomSnsEvent::class;
}
/**
* Handle logic at the controller level on notification.
*
* @param array $snsMessage
* @param \Illuminate\Http\Request $request
* @return void
*/
protected function onNotification(array $snsMessage, Request $request): void
{
mt_rand(0, 10000);
}
/**
* Handle logic at the controller level on subscription.
*
* @param array $snsMessage
* @param \Illuminate\Http\Request $request
* @return void
*/
protected function onSubscriptionConfirmation(array $snsMessage, Request $request): void
{
mt_rand(0, 10000);
}
}
| php | Apache-2.0 | a36a61aff3fb3005aafda799d5d6c69e72a71a9c | 2026-01-05T05:08:32.238986Z | false |
renoki-co/laravel-sns-events | https://github.com/renoki-co/laravel-sns-events/blob/a36a61aff3fb3005aafda799d5d6c69e72a71a9c/tests/Controllers/SnsController.php | tests/Controllers/SnsController.php | <?php
namespace Rennokki\LaravelSnsEvents\Tests\Controllers;
use Rennokki\LaravelSnsEvents\Http\Controllers\SnsController as BaseSnsController;
class SnsController extends BaseSnsController
{
//
}
| php | Apache-2.0 | a36a61aff3fb3005aafda799d5d6c69e72a71a9c | 2026-01-05T05:08:32.238986Z | false |
renoki-co/laravel-sns-events | https://github.com/renoki-co/laravel-sns-events/blob/a36a61aff3fb3005aafda799d5d6c69e72a71a9c/tests/routes/web.php | tests/routes/web.php | <?php
use Illuminate\Support\Facades\Route;
Route::any('/sns', 'Rennokki\LaravelSnsEvents\Tests\Controllers\SnsController@handle')
->name('sns');
Route::any('/sns-custom', 'Rennokki\LaravelSnsEvents\Tests\Controllers\CustomSnsController@handle')
->name('custom-sns');
| php | Apache-2.0 | a36a61aff3fb3005aafda799d5d6c69e72a71a9c | 2026-01-05T05:08:32.238986Z | false |
renoki-co/laravel-sns-events | https://github.com/renoki-co/laravel-sns-events/blob/a36a61aff3fb3005aafda799d5d6c69e72a71a9c/tests/Events/CustomSubscriptionConfirmation.php | tests/Events/CustomSubscriptionConfirmation.php | <?php
namespace Rennokki\LaravelSnsEvents\Tests\Events;
use Rennokki\LaravelSnsEvents\Events\SnsSubscriptionConfirmation;
class CustomSubscriptionConfirmation extends SnsSubscriptionConfirmation
{
//
}
| php | Apache-2.0 | a36a61aff3fb3005aafda799d5d6c69e72a71a9c | 2026-01-05T05:08:32.238986Z | false |
renoki-co/laravel-sns-events | https://github.com/renoki-co/laravel-sns-events/blob/a36a61aff3fb3005aafda799d5d6c69e72a71a9c/tests/Events/CustomSnsEvent.php | tests/Events/CustomSnsEvent.php | <?php
namespace Rennokki\LaravelSnsEvents\Tests\Events;
use Rennokki\LaravelSnsEvents\Events\SnsNotification;
class CustomSnsEvent extends SnsNotification
{
//
}
| php | Apache-2.0 | a36a61aff3fb3005aafda799d5d6c69e72a71a9c | 2026-01-05T05:08:32.238986Z | false |
yiisoft/yii2-twig | https://github.com/yiisoft/yii2-twig/blob/1bae7be1e52f5b120fcdcebc4ccd91cdd861a592/src/Extension.php | src/Extension.php | <?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
namespace yii\twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
use yii\base\InvalidCallException;
use yii\helpers\Inflector;
use yii\helpers\StringHelper;
use yii\helpers\Url;
use yii\web\AssetBundle;
/**
* Extension provides Yii-specific syntax for Twig templates.
*
* @author Andrey Grachov <andrey.grachov@gmail.com>
* @author Alexander Makarov <sam@rmcreative.ru>
*/
class Extension extends AbstractExtension
{
/**
* @var array used namespaces
*/
protected $namespaces = [];
/**
* @var array used class aliases
*/
protected $aliases = [];
/**
* @var array used widgets
*/
protected $widgets = [];
/**
* Little hack to work with twig 3.9
* see explanation at the end of yii\twig\ViewRenderer::render function
*
* @var bool
*/
protected $viewEndPage = false;
public function withViewEndPage(): bool
{
return $this->viewEndPage;
}
/**
* Creates new instance
*
* @param array $uses namespaces and classes to use in the template
*/
public function __construct(array $uses = [])
{
$this->addUses($uses);
}
/**
* @inheritdoc
*/
public function getNodeVisitors()
{
return [
new Optimizer(),
new GetAttrAdjuster(),
];
}
/**
* @inheritdoc
*/
public function getFunctions()
{
$options = [
'is_safe' => ['html'],
];
$functions = [
new TwigFunction('use', [$this, 'addUses'], $options),
new TwigFunction('*_begin', [$this, 'beginWidget'], $options),
new TwigFunction('*_end', [$this, 'endWidget'], $options),
new TwigFunction('widget_end', [$this, 'endWidget'], $options),
new TwigFunction('*_widget', [$this, 'widget'], $options),
new TwigFunction('path', [$this, 'path']),
new TwigFunction('url', [$this, 'url']),
new TwigFunction('void', function(){}),
new TwigFunction('set', [$this, 'setProperty']),
new TwigFunction('t', [\Yii::class,'t']),
];
$options = array_merge($options, [
'needs_context' => true,
]);
$functions[] = new TwigFunction('register_*', [$this, 'registerAsset'], $options);
$functions[] = new TwigFunction('register_asset_bundle', [$this, 'registerAssetBundle'], $options);
foreach (['begin_page', 'end_page', 'begin_body', 'end_body', 'head'] as $helper) {
$functions[] = new TwigFunction($helper, [$this, 'viewHelper'], $options);
}
return $functions;
}
/**
* Function for registering an asset
*
* ```
* {{ use('yii/web/JqueryAsset') }}
* {{ register_jquery_asset() }}
* ```
*
* @param array $context context information
* @param string $asset asset name
* @return mixed
*/
public function registerAsset($context, $asset)
{
return $this->resolveAndCall($asset, 'register', [
isset($context['this']) ? $context['this'] : null,
]);
}
/**
* Function for additional syntax of registering asset bundles
*
* ```
* {{ register_asset_bundle('yii/web/JqueryAsset') }}
* ```
*
* @param array $context context information
* @param string $bundle asset bundle class fully qualified name
* @param bool $return indicates if AssetBundle should be returned
*
* @return void|AssetBundle
* @since 2.0.4
*/
public function registerAssetBundle($context, $bundle, $return = false)
{
$bundle = str_replace('/', '\\', $bundle);
$bundle = $this->call($bundle, 'register', [
isset($context['this']) ? $context['this'] : null,
]);
if ($return) {
return $bundle;
}
}
/**
* Function for *_begin syntax support
*
* @param string $widget widget name
* @param array $config widget config
* @return mixed
*/
public function beginWidget($widget, $config = [])
{
$widget = $this->resolveClassName($widget);
$this->widgets[] = $widget;
return $this->call($widget, 'begin', [
$config,
]);
}
/**
* Function for *_end syntax support
*
* @param string $widget widget name
*/
public function endWidget($widget = null)
{
if ($widget === null) {
if (empty($this->widgets)) {
throw new InvalidCallException('Unexpected end_widget() call. A matching begin_widget() is not found.');
}
$this->call(array_pop($this->widgets), 'end');
} else {
array_pop($this->widgets);
$this->resolveAndCall($widget, 'end');
}
}
/**
* Function for *_widget syntax support
*
* @param string $widget widget name
* @param array $config widget config
* @return mixed
*/
public function widget($widget, $config = [])
{
return $this->resolveAndCall($widget, 'widget', [
$config,
]);
}
/**
* Used for 'begin_page', 'end_page', 'begin_body', 'end_body', 'head'
*
* @param array $context context information
* @param string $name
*/
public function viewHelper($context, $name = null)
{
if ($name !== null && isset($context['this'])) {
if ($name === 'end_page') {
$this->viewEndPage = true;
} else {
$this->call($context['this'], Inflector::variablize($name));
}
}
}
/**
* Resolves a method from widget and asset syntax and calls it
*
* @param string $className class name
* @param string $method method name
* @param array $arguments
* @return mixed
*/
public function resolveAndCall($className, $method, $arguments = null)
{
return $this->call($this->resolveClassName($className), $method, $arguments);
}
/**
* Calls a method
*
* @param string $className class name
* @param string $method method name
* @param array $arguments
* @return mixed
*/
public function call($className, $method, $arguments = null)
{
$callable = [$className, $method];
if ($arguments === null) {
return call_user_func($callable);
} else {
return call_user_func_array($callable, $arguments);
}
}
/**
* Resolves class name from widget and asset syntax
*
* @param string $className class name
* @return string
*/
public function resolveClassName($className)
{
$className = Inflector::id2camel($className, '_');
if (isset($this->aliases[$className])) {
return $this->aliases[$className];
}
foreach ($this->namespaces as $namespace) {
$resolvedClassName = $namespace . '\\' . $className;
if (class_exists($resolvedClassName)) {
return $this->aliases[$className] = $resolvedClassName;
}
}
return $className;
}
/**
* Adds namespaces and aliases from constructor
*
* @param array $args namespaces and classes to use in the template
*/
public function addUses($args)
{
foreach ((array)$args as $key => $value) {
$value = str_replace('/', '\\', $value);
if (is_int($key)) {
// namespace or class import
if (class_exists($value)) {
// class import
$this->aliases[StringHelper::basename($value)] = $value;
} else {
// namespace
$this->namespaces[] = $value;
}
} else {
// aliased class import
$this->aliases[$key] = $value;
}
}
}
/**
* Generates relative URL
*
* @param string $path the parameter to be used to generate a valid URL
* @param array $args arguments
* @return string the generated relative URL
*/
public function path($path, $args = [])
{
if (is_array($path)) {
$path = array_merge($path, $args);
} elseif ($args !== []) {
$path = array_merge([$path], $args);
}
return Url::to($path);
}
/**
* Generates absolute URL
*
* @param string $path the parameter to be used to generate a valid URL
* @param array $args arguments
* @return string the generated absolute URL
*/
public function url($path, $args = [])
{
if (is_array($path)) {
$path = array_merge($path, $args);
} elseif ($args !== []) {
$path = array_merge([$path], $args);
}
return Url::to($path, true);
}
/**
* Sets object property
*
* @param \stdClass $object
* @param string $property
* @param mixed $value
*/
public function setProperty($object, $property, $value)
{
$object->$property = $value;
}
/**
* @inheritdoc
*/
public function getName()
{
return 'yii2-twig';
}
}
| php | BSD-3-Clause | 1bae7be1e52f5b120fcdcebc4ccd91cdd861a592 | 2026-01-05T05:08:39.408608Z | false |
yiisoft/yii2-twig | https://github.com/yiisoft/yii2-twig/blob/1bae7be1e52f5b120fcdcebc4ccd91cdd861a592/src/Profile.php | src/Profile.php | <?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
namespace yii\twig;
use Twig\Extension\ProfilerExtension;
use Twig\Profiler\Dumper\TextDumper;
use \Twig\Profiler\Profile as TwigProfile;
use yii\web\View;
class Profile extends ProfilerExtension
{
protected $view;
protected $profiler;
public function __construct(TwigProfile $profile)
{
$profile = new TwigProfile();
$dumper = new TextDumper();
parent::__construct($profile);
$view = \Yii::$app->getView();
$view->on(View::EVENT_AFTER_RENDER, function () use ($profile, $dumper) {
\Yii::trace($dumper->dump($profile));
});
}
}
| php | BSD-3-Clause | 1bae7be1e52f5b120fcdcebc4ccd91cdd861a592 | 2026-01-05T05:08:39.408608Z | false |
yiisoft/yii2-twig | https://github.com/yiisoft/yii2-twig/blob/1bae7be1e52f5b120fcdcebc4ccd91cdd861a592/src/ViewRenderer.php | src/ViewRenderer.php | <?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
namespace yii\twig;
use Twig\Environment;
use Twig\Lexer;
use Twig\Loader\FilesystemLoader;
use Yii;
use yii\base\View;
use yii\base\ViewRenderer as BaseViewRenderer;
/**
* TwigViewRenderer allows you to use Twig templates in views.
*
* @property-write array $lexerOptions @see self::$lexerOptions.
*
* @author Alexander Makarov <sam@rmcreative.ru>
* @since 2.0
*/
class ViewRenderer extends BaseViewRenderer
{
/**
* @var string the directory or path alias pointing to where Twig cache will be stored. Set to false to disable
* templates cache.
*/
public $cachePath = '@runtime/Twig/cache';
/**
* @var array Twig options.
* @see https://twig.symfony.com/doc/api.html#environment-options
*/
public $options = [];
/**
* @var array Global variables.
* Keys of the array are names to call in template, values are scalar or objects or names of static classes.
* Example: `['html' => ['class' => '\yii\helpers\Html'], 'debug' => YII_DEBUG]`.
* In the template you can use it like this: `{{ html.a('Login', 'site/login') | raw }}`.
*/
public $globals = [];
/**
* @var array Custom functions.
* Keys of the array are names to call in template, values are names of functions or static methods of some class.
* Example: `['rot13' => 'str_rot13', 'a' => '\yii\helpers\Html::a']`.
* In the template you can use it like this: `{{ rot13('test') }}` or `{{ a('Login', 'site/login') | raw }}`.
*/
public $functions = [];
/**
* @var array Custom filters.
* Keys of the array are names to call in template, values are names of functions or static methods of some class.
* Example: `['rot13' => 'str_rot13', 'jsonEncode' => '\yii\helpers\Json::encode']`.
* In the template you can use it like this: `{{ 'test'|rot13 }}` or `{{ model|jsonEncode }}`.
*/
public $filters = [];
/**
* @var array Custom extensions.
* Example: `['Twig_Extension_Sandbox', new \Twig_Extension_Text()]`
*/
public $extensions = [];
/**
* @var array Twig lexer options.
*
* Example: Smarty-like syntax:
* ```php
* [
* 'tag_comment' => ['{*', '*}'],
* 'tag_block' => ['{', '}'],
* 'tag_variable' => ['{$', '}']
* ]
* ```
* @see https://twig.symfony.com/doc/recipes.html#customizing-the-syntax
*/
public $lexerOptions = [];
/**
* @var array namespaces and classes to import.
*
* Example:
*
* ```php
* [
* 'yii\bootstrap',
* 'app\assets',
* \yii\bootstrap\NavBar::class,
* ]
* ```
*/
public $uses = [];
/**
* @var Environment twig environment object that renders twig templates
*/
public $twig;
/**
* @var string twig namespace to use in templates
* @since 2.0.5
*/
public $twigViewsNamespace = FilesystemLoader::MAIN_NAMESPACE;
/**
* @var string twig namespace to use in modules templates
* @since 2.0.5
*/
public $twigModulesNamespace = 'modules';
/**
* @var string twig namespace to use in widgets templates
* @since 2.0.5
*/
public $twigWidgetsNamespace = 'widgets';
/**
* @var array twig fallback paths
* @since 2.0.5
*/
public $twigFallbackPaths = [];
/**
* Custom Extension for twig
* Need this in the render function for twig3.9 fix.
*
* @var Extension
*/
protected $extension;
public function init()
{
// Create environment with empty loader
$loader = new TwigEmptyLoader();
$this->twig = new Environment($loader, array_merge([
'cache' => Yii::getAlias($this->cachePath),
'charset' => Yii::$app->charset,
'use_yield' => false
], $this->options));
// Adding custom globals (objects or static classes)
if (!empty($this->globals)) {
$this->addGlobals($this->globals);
}
// Adding custom functions
if (!empty($this->functions)) {
$this->addFunctions($this->functions);
}
// Adding custom filters
if (!empty($this->filters)) {
$this->addFilters($this->filters);
}
$this->extension = new Extension($this->uses);
$this->addExtensions([$this->extension]);
// Adding custom extensions
if (!empty($this->extensions)) {
$this->addExtensions($this->extensions);
}
$this->twig->addGlobal('app', \Yii::$app);
}
/**
* Renders a view file.
*
* This method is invoked by [[View]] whenever it tries to render a view.
* Child classes must implement this method to render the given view file.
*
* @param View $view the view object used for rendering the file.
* @param string $file the view file.
* @param array $params the parameters to be passed to the view file.
*
* @return string the rendering result
*/
public function render($view, $file, $params)
{
$this->twig->addGlobal('this', $view);
$loader = new FilesystemLoader(dirname($file));
if ($view instanceof View) {
$this->addFallbackPaths($loader, $view->theme);
}
$this->addAliases($loader, Yii::$aliases);
$this->twig->setLoader($loader);
// Change lexer syntax (must be set after other settings)
if (!empty($this->lexerOptions)) {
$this->setLexerOptions($this->lexerOptions);
}
$content = $this->twig->render(pathinfo($file, PATHINFO_BASENAME), $params);
/**
* Hack to work with twig3.9.
* Explanation:
* Twig 3.9 does not hold the contents of the template in the output buffer anymore,
* but it still reads the contents from it (if we stick to use `use_yield` false)
* (it was an internal implementation and this package relied on this fact)
* This means that when the endPage method in the yii2 View class wants to read the output buffer
* to replace the placeholders it will be empty, because twig has already emptied it (and does not hold its state anymore).
*
* By not doing anything in the twig function call yet (see yii\twig\Extension::viewHelper), we can work around this limitation
* by calling the endPage function with the twig render results in the buffer after twig has already done its work.
*/
if ($this->extension->withViewEndPage()) {
// $view->endPage will end the current buffer when calling ob_get_clean and echo the modified(replaced placeholders) contents.
// this means that we need 2 levels deep output buffer.
ob_start();
ob_start();
echo $content;
$view->endPage();
$content = ob_get_clean();
}
return $content;
}
/**
* Adds aliases
*
* @param FilesystemLoader $loader
* @param array $aliases
*/
protected function addAliases($loader, $aliases)
{
foreach ($aliases as $alias => $path) {
if (is_array($path)) {
$this->addAliases($loader, $path);
} elseif (is_string($path) && is_dir($path)) {
$loader->addPath($path, substr($alias, 1));
}
}
}
/**
* Adds fallback paths to twig loader
*
* @param FilesystemLoader $loader
* @param yii\base\Theme|null $theme
* @since 2.0.5
*/
protected function addFallbackPaths($loader, $theme)
{
foreach ($this->twigFallbackPaths as $namespace => $path) {
$path = Yii::getAlias($path);
if (!is_dir($path)) {
continue;
}
if (is_string($namespace)) {
$loader->addPath($path, $namespace);
} else {
$loader->addPath($path);
}
}
if ($theme instanceOf \yii\base\Theme && is_array($theme->pathMap)) {
$pathMap = $theme->pathMap;
if (isset($pathMap['@app/views'])) {
foreach ((array)$pathMap['@app/views'] as $path) {
$path = Yii::getAlias($path);
if (is_dir($path)) {
$loader->addPath($path, $this->twigViewsNamespace);
}
}
}
if (isset($pathMap['@app/modules'])) {
foreach ((array)$pathMap['@app/modules'] as $path) {
$path = Yii::getAlias($path);
if (is_dir($path)) {
$loader->addPath($path, $this->twigModulesNamespace);
}
}
}
if (isset($pathMap['@app/widgets'])) {
foreach ((array)$pathMap['@app/widgets'] as $path) {
$path = Yii::getAlias($path);
if (is_dir($path)) {
$loader->addPath($path, $this->twigWidgetsNamespace);
}
}
}
}
$defaultViewsPath = Yii::getAlias('@app/views');
if (is_dir($defaultViewsPath)) {
$loader->addPath($defaultViewsPath, $this->twigViewsNamespace);
}
$defaultModulesPath = Yii::getAlias('@app/modules');
if (is_dir($defaultModulesPath)) {
$loader->addPath($defaultModulesPath, $this->twigModulesNamespace);
}
$defaultWidgetsPath = Yii::getAlias('@app/widgets');
if (is_dir($defaultWidgetsPath)) {
$loader->addPath($defaultWidgetsPath, $this->twigWidgetsNamespace);
}
}
/**
* Adds global objects or static classes
* @param array $globals @see self::$globals
*/
public function addGlobals($globals)
{
foreach ($globals as $name => $value) {
if (is_array($value) && isset($value['class'])) {
$value = new ViewRendererStaticClassProxy($value['class']);
}
$this->twig->addGlobal($name, $value);
}
}
/**
* Adds custom functions
* @param array $functions @see self::$functions
*/
public function addFunctions($functions)
{
$this->_addCustom('Function', $functions);
}
/**
* Adds custom filters
* @param array $filters @see self::$filters
*/
public function addFilters($filters)
{
$this->_addCustom('Filter', $filters);
}
/**
* Adds custom extensions
* @param array $extensions @see self::$extensions
*/
public function addExtensions($extensions)
{
foreach ($extensions as $extName) {
$this->twig->addExtension(is_object($extName) ? $extName : Yii::createObject($extName));
}
}
/**
* Sets Twig lexer options to change templates syntax
* @param array $options @see self::$lexerOptions
*/
public function setLexerOptions($options)
{
$lexer = new Lexer($this->twig, $options);
$this->twig->setLexer($lexer);
}
/**
* Adds custom function or filter
* @param string $classType 'Function' or 'Filter'
* @param array $elements Parameters of elements to add
* @throws \Exception
*/
private function _addCustom($classType, $elements)
{
$classFunction = 'Twig\Twig' . $classType;
foreach ($elements as $name => $func) {
$twigElement = null;
switch ($func) {
// Callable (including just a name of function).
case is_callable($func):
$twigElement = new $classFunction($name, $func);
break;
// Callable (including just a name of function) + options array.
case is_array($func) && is_callable($func[0]):
$twigElement = new $classFunction($name, $func[0], (!empty($func[1]) && is_array($func[1])) ? $func[1] : []);
break;
case $func instanceof \Twig\TwigFunction || $func instanceof \Twig\TwigFilter:
$twigElement = $func;
}
if ($twigElement !== null) {
$this->twig->{'add'.$classType}($twigElement);
} else {
throw new \Exception("Incorrect options for \"$classType\" $name.");
}
}
}
}
| php | BSD-3-Clause | 1bae7be1e52f5b120fcdcebc4ccd91cdd861a592 | 2026-01-05T05:08:39.408608Z | false |
yiisoft/yii2-twig | https://github.com/yiisoft/yii2-twig/blob/1bae7be1e52f5b120fcdcebc4ccd91cdd861a592/src/GetAttr.php | src/GetAttr.php | <?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
namespace yii\twig;
use Twig\Compiler;
use Twig\Node\Expression\AbstractExpression;
use Twig\Template as TwigTemplate;
class GetAttr extends AbstractExpression
{
/**
* @inheritdoc
*/
public function compile(Compiler $compiler)
{
$compiler->raw(Template::class.'::attribute($this->env, $this->getSourceContext(), ');
if ($this->getAttribute('ignore_strict_check')) {
$this->getNode('node')->setAttribute('ignore_strict_check', true);
}
$compiler->subcompile($this->getNode('node'));
$compiler->raw(', ')->subcompile($this->getNode('attribute'));
// only generate optional arguments when needed (to make generated code more readable)
$needFourth = $this->getAttribute('ignore_strict_check');
$needThird = $needFourth || $this->getAttribute('is_defined_test');
$needSecond = $needThird || TwigTemplate::ANY_CALL !== $this->getAttribute('type');
$needFirst = $needSecond || $this->hasNode('arguments');
if ($needFirst) {
if ($this->hasNode('arguments')) {
$compiler->raw(', ')->subcompile($this->getNode('arguments'));
} else {
$compiler->raw(', array()');
}
}
if ($needSecond) {
$compiler->raw(', ')->repr($this->getAttribute('type'));
}
if ($needThird) {
$compiler->raw(', ')->repr($this->getAttribute('is_defined_test'));
}
if ($needFourth) {
$compiler->raw(', ')->repr($this->getAttribute('ignore_strict_check'));
}
$compiler->raw(')');
}
}
| php | BSD-3-Clause | 1bae7be1e52f5b120fcdcebc4ccd91cdd861a592 | 2026-01-05T05:08:39.408608Z | false |
yiisoft/yii2-twig | https://github.com/yiisoft/yii2-twig/blob/1bae7be1e52f5b120fcdcebc4ccd91cdd861a592/src/TwigEmptyLoader.php | src/TwigEmptyLoader.php | <?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
namespace yii\twig;
use Twig\Error\LoaderError;
use Twig\Loader\LoaderInterface;
use Twig\Source;
/**
* Empty loader used for environment initialisation
*
* @author Andrzej BroΕski <andrzej1_1@o2.pl>
*/
class TwigEmptyLoader implements LoaderInterface
{
/**
* @inheritdoc
*/
public function getSourceContext(string $name): Source
{
throw new LoaderError("Can not render using empty loader");
}
/**
* @inheritdoc
*/
public function getCacheKey(string $name): string
{
throw new LoaderError("Can not render using empty loader");
}
/**
* @inheritdoc
*/
public function isFresh(string $name, int $time): bool
{
throw new LoaderError("Can not render using empty loader");
}
/**
* @inheritdoc
*/
public function exists(string $name)
{
return false;
}
}
| php | BSD-3-Clause | 1bae7be1e52f5b120fcdcebc4ccd91cdd861a592 | 2026-01-05T05:08:39.408608Z | false |
yiisoft/yii2-twig | https://github.com/yiisoft/yii2-twig/blob/1bae7be1e52f5b120fcdcebc4ccd91cdd861a592/src/Template.php | src/Template.php | <?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
namespace yii\twig;
use Twig\Source;
use Twig\Environment;
use Twig\Error\RuntimeError;
use Twig\Template as TwigTemplate;
use Twig\Markup;
use Twig\Extension\CoreExtension;
/**
* Template helper
*/
class Template
{
/**
* Returns the attribute value for a given array/object.
*
* @param Environment $env
* @param Source $source
* @param mixed $object The object or array from where to get the item
* @param mixed $item The item to get from the array or object
* @param array $arguments An array of arguments to pass if the item is an object method
* @param string $type The type of attribute (@see Twig_Template constants)
* @param bool $isDefinedTest Whether this is only a defined check
* @param bool $ignoreStrictCheck Whether to ignore the strict attribute check or not
*
* @return mixed The attribute value, or a Boolean when $isDefinedTest is true, or null when the attribute is not set and $ignoreStrictCheck is true
*
* @throws RuntimeError if the attribute does not exist and Twig is running in strict mode and $isDefinedTest is false
*
* @internal
*/
public static function attribute(Environment $env, Source $source, $object, $item, array $arguments = [], string $type = TwigTemplate::ANY_CALL, bool $isDefinedTest = false, bool $ignoreStrictCheck = false)
{
if (
$type !== TwigTemplate::METHOD_CALL &&
($object instanceof Object || $object instanceof \yii\base\Model) &&
$object->canGetProperty($item)
) {
return $isDefinedTest ? true : $object->$item;
}
// Convert any Twig_Markup arguments back to strings (unless the class *extends* Twig_Markup)
foreach ($arguments as $key => $value) {
if (is_object($value) && get_class($value) === Markup::class) {
$arguments[$key] = (string)$value;
}
}
return CoreExtension::getAttribute($env, $source, $object, $item, $arguments, $type, $isDefinedTest, $ignoreStrictCheck);
}
}
| php | BSD-3-Clause | 1bae7be1e52f5b120fcdcebc4ccd91cdd861a592 | 2026-01-05T05:08:39.408608Z | false |
yiisoft/yii2-twig | https://github.com/yiisoft/yii2-twig/blob/1bae7be1e52f5b120fcdcebc4ccd91cdd861a592/src/ViewRendererStaticClassProxy.php | src/ViewRendererStaticClassProxy.php | <?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
namespace yii\twig;
/**
* Class-proxy for static classes
* Needed because you can't pass static class to Twig other way
*
* @author Leonid Svyatov <leonid@svyatov.ru>
*/
class ViewRendererStaticClassProxy
{
private $_staticClassName;
/**
* @param string $staticClassName
*/
public function __construct($staticClassName)
{
$this->_staticClassName = $staticClassName;
}
/**
* @param string $property
* @return bool
*/
public function __isset($property)
{
$class = new \ReflectionClass($this->_staticClassName);
$staticProps = $class->getStaticProperties();
$constants = $class->getConstants();
return array_key_exists($property, $staticProps) || array_key_exists($property, $constants);
}
/**
* @param string $property
* @return mixed
*/
public function __get($property)
{
$class = new \ReflectionClass($this->_staticClassName);
$constants = $class->getConstants();
if (array_key_exists($property, $constants)) {
return $class->getConstant($property);
}
return $class->getStaticPropertyValue($property);
}
/**
* @param string $property
* @param mixed $value
* @return mixed
*/
public function __set($property, $value)
{
$class = new \ReflectionClass($this->_staticClassName);
$class->setStaticPropertyValue($property, $value);
return $value;
}
/**
* @param string $method
* @param array $arguments
* @return mixed
*/
public function __call($method, $arguments)
{
return call_user_func_array([$this->_staticClassName, $method], $arguments);
}
}
| php | BSD-3-Clause | 1bae7be1e52f5b120fcdcebc4ccd91cdd861a592 | 2026-01-05T05:08:39.408608Z | false |
yiisoft/yii2-twig | https://github.com/yiisoft/yii2-twig/blob/1bae7be1e52f5b120fcdcebc4ccd91cdd861a592/src/Optimizer.php | src/Optimizer.php | <?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
namespace yii\twig;
use Twig\Environment;
use Twig\Node\DoNode;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\Expression\FunctionExpression;
use Twig\Node\Node;
use Twig\Node\PrintNode;
use Twig\NodeVisitor\NodeVisitorInterface;
/**
* Optimizer removes echo before special functions call and injects function name as an argument for the view helper
* calls.
*
* @author Andrey Grachov <andrey.grachov@gmail.com>
* @author Alexander Makarov <sam@rmcreative.ru>
*/
class Optimizer implements NodeVisitorInterface
{
/**
* @inheritdoc
*/
public function enterNode(Node $node, Environment $env): Node
{
return $node;
}
/**
* @inheritdoc
*/
public function leaveNode(Node $node, Environment $env): ?Node
{
if ($node instanceof PrintNode) {
$expression = $node->getNode('expr');
if ($expression instanceof FunctionExpression) {
$name = $expression->getAttribute('name');
if (preg_match('/^(?:register_.+_asset|use|.+_begin|.+_end)$/', $name)) {
return new DoNode($expression, $expression->getTemplateLine());
} elseif (in_array($name, ['begin_page', 'end_page', 'begin_body', 'end_body', 'head'])) {
$arguments = [
new ConstantExpression($name, $expression->getTemplateLine()),
];
if ($expression->hasNode('arguments') && $expression->getNode('arguments') !== null) {
foreach ($expression->getNode('arguments') as $key => $value) {
if (is_int($key)) {
$arguments[] = $value;
} else {
$arguments[$key] = $value;
}
}
}
$expression->setNode('arguments', new Node($arguments));
return new DoNode($expression, $expression->getTemplateLine());
}
}
}
return $node;
}
/**
* @inheritdoc
*/
public function getPriority()
{
return 100;
}
}
| php | BSD-3-Clause | 1bae7be1e52f5b120fcdcebc4ccd91cdd861a592 | 2026-01-05T05:08:39.408608Z | false |
yiisoft/yii2-twig | https://github.com/yiisoft/yii2-twig/blob/1bae7be1e52f5b120fcdcebc4ccd91cdd861a592/src/GetAttrAdjuster.php | src/GetAttrAdjuster.php | <?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
namespace yii\twig;
use Twig\Environment;
use Twig\Node\Expression\GetAttrExpression;
use Twig\Node\Node;
use Twig\NodeVisitor\NodeVisitorInterface;
/**
* GetAttrAdjuster swaps Twig_Node_Expression_GetAttr nodes with [[GetAttr]] nodes.
*/
class GetAttrAdjuster implements NodeVisitorInterface
{
/**
* @inheritdoc
*/
public function enterNode(Node $node, Environment $env): Node
{
// Is it a Twig_Node_Expression_GetAttr (and not a subclass)?
if (get_class($node) === GetAttrExpression::class) {
// "Clone" it into a GetAttr node
$nodes = [
'node' => $node->getNode('node'),
'attribute' => $node->getNode('attribute')
];
if ($node->hasNode('arguments')) {
$nodes['arguments'] = $node->getNode('arguments');
}
$attributes = [
'type' => $node->getAttribute('type'),
'is_defined_test' => $node->getAttribute('is_defined_test'),
'ignore_strict_check' => $node->getAttribute('ignore_strict_check')
];
$node = new GetAttr($nodes, $attributes, $node->getTemplateLine(), $node->getNodeTag());
}
return $node;
}
/**
* @inheritdoc
*/
public function leaveNode(Node $node, Environment $env): ?Node
{
return $node;
}
/**
* @inheritdoc
*/
public function getPriority()
{
return 0;
}
}
| php | BSD-3-Clause | 1bae7be1e52f5b120fcdcebc4ccd91cdd861a592 | 2026-01-05T05:08:39.408608Z | false |
yiisoft/yii2-twig | https://github.com/yiisoft/yii2-twig/blob/1bae7be1e52f5b120fcdcebc4ccd91cdd861a592/src/html/CssStyle_TokenParser.php | src/html/CssStyle_TokenParser.php | <?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
namespace yii\twig\html;
class CssStyle_TokenParser extends BaseCss_TokenParser
{
public function getNodeClass()
{
return '\yii\twig\html\StyleClassNode';
}
public function getTag()
{
return 'css_style';
}
}
| php | BSD-3-Clause | 1bae7be1e52f5b120fcdcebc4ccd91cdd861a592 | 2026-01-05T05:08:39.408608Z | false |
yiisoft/yii2-twig | https://github.com/yiisoft/yii2-twig/blob/1bae7be1e52f5b120fcdcebc4ccd91cdd861a592/src/html/BaseCss_TokenParser.php | src/html/BaseCss_TokenParser.php | <?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
namespace yii\twig\html;
use Twig\Token;
use Twig\TokenParser\AbstractTokenParser;
abstract class BaseCss_TokenParser extends AbstractTokenParser
{
public function parse(Token $token)
{
$parser = $this->parser;
$stream = $parser->getStream();
$name = $stream->expect(Token::NAME_TYPE);
$operator = $stream->expect(Token::OPERATOR_TYPE);
$value = $parser->getExpressionParser()->parseExpression();
$stream->expect(Token::BLOCK_END_TYPE);
$nodeClass = $this->getNodeClass();
return new $nodeClass($name, $value, $operator, $token->getLine(), $this->getTag());
}
abstract public function getNodeClass();
}
| php | BSD-3-Clause | 1bae7be1e52f5b120fcdcebc4ccd91cdd861a592 | 2026-01-05T05:08:39.408608Z | false |
yiisoft/yii2-twig | https://github.com/yiisoft/yii2-twig/blob/1bae7be1e52f5b120fcdcebc4ccd91cdd861a592/src/html/HtmlHelperExtension.php | src/html/HtmlHelperExtension.php | <?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
namespace yii\twig\html;
use Twig\Extension\AbstractExtension;
use Twig\Extension\GlobalsInterface;
use yii\twig\ViewRendererStaticClassProxy;
class HtmlHelperExtension extends AbstractExtension implements GlobalsInterface
{
public function getTokenParsers()
{
return [
new CssClass_TokenParser(),
new CssStyle_TokenParser()
];
}
public function getGlobals(): array
{
return [
'html' => new ViewRendererStaticClassProxy('\yii\helpers\Html'),
];
}
}
| php | BSD-3-Clause | 1bae7be1e52f5b120fcdcebc4ccd91cdd861a592 | 2026-01-05T05:08:39.408608Z | false |
yiisoft/yii2-twig | https://github.com/yiisoft/yii2-twig/blob/1bae7be1e52f5b120fcdcebc4ccd91cdd861a592/src/html/CssClassNode.php | src/html/CssClassNode.php | <?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
namespace yii\twig\html;
use Twig\Token;
use Twig\Error\Error;
class CssClassNode extends BaseClassNode
{
public function __construct(Token $name, $value, Token $operator, $lineno = 0, $tag = null)
{
parent::__construct(array('value' => $value), array('name' => $name, 'operator' => $operator), $lineno, $tag);
}
public function getHelperMethod()
{
$operator = $this->getAttribute('operator')->getValue();
switch ($operator) {
case '+':
return 'addCssClass';
case '-':
return 'removeCssClass';
default:
throw new Error("Operator {$operator} no found;");
}
}
}
| php | BSD-3-Clause | 1bae7be1e52f5b120fcdcebc4ccd91cdd861a592 | 2026-01-05T05:08:39.408608Z | false |
yiisoft/yii2-twig | https://github.com/yiisoft/yii2-twig/blob/1bae7be1e52f5b120fcdcebc4ccd91cdd861a592/src/html/StyleClassNode.php | src/html/StyleClassNode.php | <?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
namespace yii\twig\html;
use Twig\Token;
use Twig\Error\Error;
class StyleClassNode extends BaseClassNode
{
public function __construct(Token $name, $value, Token $operator, $lineno = 0, $tag = null)
{
parent::__construct(array('value' => $value), array('name' => $name, 'operator' => $operator), $lineno, $tag);
}
public function getHelperMethod()
{
$operator = $this->getAttribute('operator')->getValue();
switch ($operator) {
case '+':
return 'addCssStyle';
case '-':
return 'removeCssStyle';
default:
throw new Error("Operator {$operator} no found;");
}
}
}
| php | BSD-3-Clause | 1bae7be1e52f5b120fcdcebc4ccd91cdd861a592 | 2026-01-05T05:08:39.408608Z | false |
yiisoft/yii2-twig | https://github.com/yiisoft/yii2-twig/blob/1bae7be1e52f5b120fcdcebc4ccd91cdd861a592/src/html/CssClass_TokenParser.php | src/html/CssClass_TokenParser.php | <?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
namespace yii\twig\html;
class CssClass_TokenParser extends BaseCss_TokenParser
{
public function getNodeClass()
{
return '\yii\twig\html\CssClassNode';
}
public function getTag()
{
return 'css_class';
}
}
| php | BSD-3-Clause | 1bae7be1e52f5b120fcdcebc4ccd91cdd861a592 | 2026-01-05T05:08:39.408608Z | false |
yiisoft/yii2-twig | https://github.com/yiisoft/yii2-twig/blob/1bae7be1e52f5b120fcdcebc4ccd91cdd861a592/src/html/BaseClassNode.php | src/html/BaseClassNode.php | <?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
namespace yii\twig\html;
use Twig\Node\Node;
use Twig\Compiler;
abstract class BaseClassNode extends Node
{
public function compile(Compiler $compiler)
{
$name = $this->getAttribute('name')->getValue();
$method = $this->getHelperMethod();
$compiler
->addDebugInfo($this)
->write("\yii\helpers\Html::{$method}(\$context[\"{$name}\"],")
->subcompile($this->getNode('value'))
->raw(");\n");
}
abstract public function getHelperMethod();
}
| php | BSD-3-Clause | 1bae7be1e52f5b120fcdcebc4ccd91cdd861a592 | 2026-01-05T05:08:39.408608Z | false |
yiisoft/yii2-twig | https://github.com/yiisoft/yii2-twig/blob/1bae7be1e52f5b120fcdcebc4ccd91cdd861a592/tests/TestCase.php | tests/TestCase.php | <?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
namespace yiiunit\twig;
use yii\di\Container;
use yii\helpers\ArrayHelper;
use Yii;
/**
* This is the base class for all yii framework unit tests.
*/
abstract class TestCase extends \PHPUnit\Framework\TestCase
{
/**
* Clean up after test.
* By default the application created with [[mockApplication]] will be destroyed.
*/
protected function tearDown()
{
parent::tearDown();
$this->destroyApplication();
}
protected function mockWebApplication($config = [], $appClass = '\yii\web\Application')
{
new $appClass(ArrayHelper::merge([
'id' => 'testapp',
'basePath' => __DIR__,
'vendorPath' => dirname(__DIR__) . '/vendor',
'aliases' => [
'@bower' => '@vendor/bower-asset',
'@npm' => '@vendor/npm-asset',
],
'components' => [
'request' => [
'cookieValidationKey' => 'wefJDF8sfdsfSDefwqdxj9oq',
'scriptFile' => __DIR__ .'/index.php',
'scriptUrl' => '/index.php',
],
]
], $config));
}
/**
* Destroys application in Yii::$app by setting it to null.
*/
protected function destroyApplication()
{
Yii::$app = null;
Yii::$container = new Container();
}
}
| php | BSD-3-Clause | 1bae7be1e52f5b120fcdcebc4ccd91cdd861a592 | 2026-01-05T05:08:39.408608Z | false |
yiisoft/yii2-twig | https://github.com/yiisoft/yii2-twig/blob/1bae7be1e52f5b120fcdcebc4ccd91cdd861a592/tests/ViewRendererTest.php | tests/ViewRendererTest.php | <?php
/**
* @link https://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license https://www.yiiframework.com/license/
*/
namespace yiiunit\twig;
use yii\helpers\FileHelper;
use yii\web\AssetManager;
use yii\web\View;
use Yii;
use yiiunit\twig\data\Order;
use yiiunit\twig\data\Singer;
/**
* Tests Twig view renderer
*
* @author Alexander Makarov <sam@rmcreative.ru>
* @author Carsten Brandt <mail@cebe.cc>
*/
class ViewRendererTest extends TestCase
{
public static function setUpBeforeClass()
{
parent::setUpBeforeClass();
Order::setUp();
}
protected function setUp()
{
parent::setUp();
$this->mockWebApplication();
}
protected function tearDown()
{
parent::tearDown();
FileHelper::removeDirectory(Yii::getAlias('@runtime/assets'));
}
/**
* https://github.com/yiisoft/yii2/issues/1755
*/
public function testLayoutAssets()
{
$view = $this->mockView();
$content = $view->renderFile('@yiiunit/twig/views/layout.twig');
$this->assertEquals(1, preg_match('#<script src="/assets/[0-9a-z]+/jquery\\.js"></script>\s*</body>#', $content), 'Content does not contain the jquery js:' . $content);
}
public function testAppGlobal()
{
$view = $this->mockView();
$content = $view->renderFile('@yiiunit/twig/views/layout.twig');
$this->assertEquals(1, preg_match('#<meta charset="' . Yii::$app->charset . '"/>#', $content), 'Content does not contain charset:' . $content);
}
/**
* https://github.com/yiisoft/yii2/issues/3877
*/
public function testLexerOptions()
{
$view = $this->mockView();
$content = $view->renderFile('@yiiunit/twig/views/comments.twig');
$this->assertFalse(strpos($content, 'CUSTOM_LEXER_TWIG_COMMENT'), 'Custom comment lexerOptions were not applied: ' . $content);
$this->assertTrue(strpos($content, 'DEFAULT_TWIG_COMMENT') !== false, 'Default comment style was not modified via lexerOptions:' . $content);
}
public function testForm()
{
$view = $this->mockView();
$model = new Singer();
$content = $view->renderFile('@yiiunit/twig/views/form.twig', ['model' => $model]);
$this->assertEquals(1, preg_match('#<form id="login-form" class="form-horizontal" action="/form-handler" method="post">.*?</form>#s', $content), 'Content does not contain form:' . $content);
}
public function testCalls()
{
$view = $this->mockView();
$model = new Singer();
$content = $view->renderFile('@yiiunit/twig/views/calls.twig', ['model' => $model]);
$this->assertNotContains('silence', $content, 'silence should not be echoed when void() used');
$this->assertContains('echo', $content);
$this->assertContains('variable', $content);
}
public function testInheritance()
{
$view = $this->mockView();
$content = $view->renderFile('@yiiunit/twig/views/extends2.twig');
$this->assertContains('Hello, I\'m inheritance test!', $content);
$this->assertContains('extends2 block', $content);
$this->assertNotContains('extends1 block', $content);
$content = $view->renderFile('@yiiunit/twig/views/extends3.twig');
$this->assertContains('Hello, I\'m inheritance test!', $content);
$this->assertContains('extends3 block', $content);
$this->assertNotContains('extends1 block', $content);
}
public function testChangeTitle()
{
$view = $this->mockView();
$view->title = 'Original title';
$content = $view->renderFile('@yiiunit/twig/views/changeTitle.twig');
$this->assertContains('New title', $content);
$this->assertNotContains('Original title', $content);
}
public function testNullsInAr()
{
$view = $this->mockView();
$order = new Order();
$content = $view->renderFile('@yiiunit/twig/views/nulls.twig', ['order' => $order]);
$this->assertSame('', $content);
}
public function testPropertyAccess()
{
$view = $this->mockView();
$order = new Order();
$order->total = 42;
$content = $view->renderFile('@yiiunit/twig/views/property.twig', ['order' => $order]);
$this->assertContains('42', $content);
}
public function testSimpleFilters()
{
$view = $this->mockView();
$content = $view->renderFile('@yiiunit/twig/views/simpleFilters1.twig');
$this->assertEquals($content, 'Gjvt');
$content = $view->renderFile('@yiiunit/twig/views/simpleFilters2.twig');
$this->assertEquals($content, 'val42');
$content = $view->renderFile('@yiiunit/twig/views/simpleFilters3.twig');
$this->assertEquals($content, 'Gjvt');
$content = $view->renderFile('@yiiunit/twig/views/simpleFilters4.twig');
$this->assertEquals($content, 'val42');
$content = $view->renderFile('@yiiunit/twig/views/simpleFilters5.twig');
$this->assertEquals($content, 'Gjvt');
}
public function testSimpleFunctions()
{
$view = $this->mockView();
$content = $view->renderFile('@yiiunit/twig/views/simpleFunctions1.twig');
$this->assertEquals($content, 'Gjvt');
$content = $view->renderFile('@yiiunit/twig/views/simpleFunctions2.twig');
$this->assertEquals($content, 'val43');
$content = $view->renderFile('@yiiunit/twig/views/simpleFunctions3.twig');
$this->assertEquals($content, 'Gjvt');
$content = $view->renderFile('@yiiunit/twig/views/simpleFunctions4.twig');
$this->assertEquals($content, 'val43');
$content = $view->renderFile('@yiiunit/twig/views/simpleFunctions5.twig');
$this->assertEquals($content, '6');
}
public function testTranslation()
{
$view = $this->mockView();
$content = $view->renderFile('@yiiunit/twig/views/t.twig');
$this->assertContains('test<br>', $content);
}
public function testHtmlExtension()
{
$params = [
'options' => [
'class' => 'btn btn-default',
'style' => 'color:red; font-size: 24px'
]
];
$view = $this->mockView();
$content = $view->renderFile('@yiiunit/twig/views/html/add_class.twig', $params);
$this->assertEquals($content, "btn btn-default btn-primary");
$content = $view->renderFile('@yiiunit/twig/views/html/remove_class.twig', $params);
$this->assertEquals($content, "btn");
$content = $view->renderFile('@yiiunit/twig/views/html/add_style.twig', $params);
$this->assertEquals($content, "color: red; font-size: 24px; display: none;");
$content = $view->renderFile('@yiiunit/twig/views/html/remove_style.twig', $params);
$this->assertEquals($content, "color: red; font-size: 24px;/color: red; font-size: 24px;");
$content = $view->renderFile('@yiiunit/twig/views/html/anchor.twig');
$this->assertEquals($content, "<a class=\"btn\" href=\"/site/index\">Button</a>\n");
}
public function testRegisterAssetBundle()
{
$view = $this->mockView();
$content = $view->renderFile('@yiiunit/twig/views/register_asset_bundle.twig');
$this->assertEquals(Yii::getAlias('@bower/jquery/dist'), $content);
}
public function testPath()
{
$this->mockWebApplication([
'components' => [
'urlManager' => [
'cache' => false,
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
'GET mypath' => 'mycontroller/myaction',
'GET mypath2/<myparam>' => 'mycontroller2/myaction2'
],
]
]
]);
$view = $this->mockView();
$this->assertEquals('/mypath?myparam=123', $view->renderFile('@yiiunit/twig/views/path/pathWithParams.twig'));//bc
$this->assertEquals('/mypath2/123', $view->renderFile('@yiiunit/twig/views/path/path2WithParams.twig'));//bc
$this->assertEquals('/some/custom/path', $view->renderFile('@yiiunit/twig/views/path/pathCustom.twig'));
//to resolve url as a route first arg should be an array
$this->assertEquals('/mycontroller/myaction', $view->renderFile('@yiiunit/twig/views/path/pathWithoutParams.twig'));
$this->assertEquals('/mypath', $view->renderFile('@yiiunit/twig/views/path/pathWithoutParamsAsArray.twig'));
$this->assertEquals('/mypath?myparam=123', $view->renderFile('@yiiunit/twig/views/path/pathWithParamsAsArray.twig'));
$this->assertEquals('/mypath2/123', $view->renderFile('@yiiunit/twig/views/path/path2WithParamsAsArray.twig'));
}
public function testUrl()
{
$this->mockWebApplication([
'components' => [
'urlManager' => [
'cache' => false,
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
'GET mypath' => 'mycontroller/myaction',
'GET mypath2/<myparam>' => 'mycontroller2/myaction2'
],
]
]
]);
Yii::$app->request->setHostInfo('http://testurl.com');
$view = $this->mockView();
$this->assertEquals('http://testurl.com/mypath?myparam=123', $view->renderFile('@yiiunit/twig/views/url/urlWithParams.twig'));//bc
$this->assertEquals('http://testurl.com/mypath2/123', $view->renderFile('@yiiunit/twig/views/url/url2WithParams.twig'));//bc
$this->assertEquals('http://testurl.com/some/custom/path', $view->renderFile('@yiiunit/twig/views/url/urlCustom.twig'));
//to resolve url as a route first arg should be an array
$this->assertEquals('http://testurl.com/mycontroller/myaction', $view->renderFile('@yiiunit/twig/views/url/urlWithoutParams.twig'));
$this->assertEquals('http://testurl.com/mypath', $view->renderFile('@yiiunit/twig/views/url/urlWithoutParamsAsArray.twig'));
$this->assertEquals('http://testurl.com/mypath?myparam=123', $view->renderFile('@yiiunit/twig/views/url/urlWithParamsAsArray.twig'));
$this->assertEquals('http://testurl.com/mypath2/123', $view->renderFile('@yiiunit/twig/views/url/url2WithParamsAsArray.twig'));
}
public function testStaticAndConsts()
{
$view = $this->mockView();
$view->renderers['twig']['globals']['staticClass'] = ['class' => \yiiunit\twig\data\StaticAndConsts::class];
$content = $view->renderFile('@yiiunit/twig/views/staticAndConsts.twig');
$this->assertContains('I am a const!', $content);
$this->assertContains('I am a static var!', $content);
$this->assertContains('I am a static function with param pam-param!', $content);
}
public function testDate()
{
$view = $this->mockView();
$date = new \DateTime();
$content = $view->renderFile('@yiiunit/twig/views/date.twig', compact('date'));
$this->assertEquals($content, $date->format('Y-m-d'));
}
/**
* Mocks view instance
* @return View
*/
protected function mockView()
{
return new View([
'renderers' => [
'twig' => [
'class' => 'yii\twig\ViewRenderer',
'options' => [
'cache' => false,
],
'globals' => [
'pos_begin' => View::POS_BEGIN,
],
'functions' => [
't' => '\Yii::t',
'json_encode' => '\yii\helpers\Json::encode',
new \Twig\TwigFunction('rot13', 'str_rot13'),
new \Twig\TwigFunction('add_*', function ($symbols, $val) {
return $val . $symbols;
}, ['is_safe' => ['html']]),
'callable_rot13' => function($string) {
return str_rot13($string);
},
'callable_add_*' => function ($symbols, $val) {
return $val . $symbols;
},
'callable_sum' => function ($a, $b) {
return $a + $b;
}
],
'filters' => [
'string_rot13' => 'str_rot13',
new \Twig\TwigFilter('rot13', 'str_rot13'),
new \Twig\TwigFilter('add_*', function ($symbols, $val) {
return $val . $symbols;
}, ['is_safe' => ['html']]),
'callable_rot13' => function($string) {
return str_rot13($string);
},
'callable_add_*' => function ($symbols, $val) {
return $val . $symbols;
}
],
'lexerOptions' => [
'tag_comment' => [ '{*', '*}' ],
],
'extensions' => [
'\yii\twig\html\HtmlHelperExtension'
]
],
],
'assetManager' => $this->mockAssetManager(),
]);
}
/**
* Mocks asset manager
* @return AssetManager
*/
protected function mockAssetManager()
{
$assetDir = Yii::getAlias('@runtime/assets');
if (!is_dir($assetDir)) {
mkdir($assetDir, 0777, true);
}
return new AssetManager([
'basePath' => $assetDir,
'baseUrl' => '/assets',
]);
}
}
| php | BSD-3-Clause | 1bae7be1e52f5b120fcdcebc4ccd91cdd861a592 | 2026-01-05T05:08:39.408608Z | false |
yiisoft/yii2-twig | https://github.com/yiisoft/yii2-twig/blob/1bae7be1e52f5b120fcdcebc4ccd91cdd861a592/tests/bootstrap.php | tests/bootstrap.php | <?php
// ensure we get report on all possible php errors
error_reporting(-1);
define('YII_ENABLE_ERROR_HANDLER', false);
define('YII_DEBUG', true);
$_SERVER['SCRIPT_NAME'] = '/' . __DIR__;
$_SERVER['SCRIPT_FILENAME'] = __FILE__;
require_once(__DIR__ . '/../vendor/autoload.php');
require_once(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
Yii::setAlias('@yiiunit/twig', __DIR__);
require_once(__DIR__ . '/compatibility.php');
| php | BSD-3-Clause | 1bae7be1e52f5b120fcdcebc4ccd91cdd861a592 | 2026-01-05T05:08:39.408608Z | false |
yiisoft/yii2-twig | https://github.com/yiisoft/yii2-twig/blob/1bae7be1e52f5b120fcdcebc4ccd91cdd861a592/tests/compatibility.php | tests/compatibility.php | <?php
/*
* Ensures compatibility with PHPUnit < 6.x
*/
namespace PHPUnit\Framework\Constraint {
if (!class_exists('PHPUnit\Framework\Constraint\Constraint') && class_exists('PHPUnit_Framework_Constraint')) {
abstract class Constraint extends \PHPUnit_Framework_Constraint {}
}
}
namespace PHPUnit\Framework {
if (!class_exists('PHPUnit\Framework\TestCase') && class_exists('PHPUnit_Framework_TestCase')) {
abstract class TestCase extends \PHPUnit_Framework_TestCase {
/**
* @param string $exception
*/
public function expectException($exception)
{
$this->setExpectedException($exception);
}
/**
* @param string $message
*/
public function expectExceptionMessage($message)
{
$this->setExpectedException($this->getExpectedException(), $message);
}
}
}
}
| php | BSD-3-Clause | 1bae7be1e52f5b120fcdcebc4ccd91cdd861a592 | 2026-01-05T05:08:39.408608Z | false |
yiisoft/yii2-twig | https://github.com/yiisoft/yii2-twig/blob/1bae7be1e52f5b120fcdcebc4ccd91cdd861a592/tests/data/Order.php | tests/data/Order.php | <?php
namespace yiiunit\twig\data;
use yii\db\ActiveRecord;
use yii\db\Connection;
/**
* Class Order
*
* @property integer $id
* @property integer $customer_id
* @property integer $created_at
* @property string $total
*/
class Order extends ActiveRecord
{
public static $db;
public static function getDb()
{
if (static::$db === null) {
static::$db = new Connection(['dsn' => 'sqlite::memory:']);
}
return static::$db;
}
public static function setUp()
{
static::getDb()->createCommand(<<<SQL
CREATE TABLE "order" (
id INTEGER NOT NULL,
customer_id INTEGER NOT NULL,
created_at INTEGER NOT NULL,
total decimal(10,0) NOT NULL,
PRIMARY KEY (id)
);
SQL
)->execute();
}
public static function tableName()
{
return 'order';
}
public function getCustomer()
{
return $this->hasOne(Order::class, ['id' => 'customer_id']);
}
}
| php | BSD-3-Clause | 1bae7be1e52f5b120fcdcebc4ccd91cdd861a592 | 2026-01-05T05:08:39.408608Z | false |
yiisoft/yii2-twig | https://github.com/yiisoft/yii2-twig/blob/1bae7be1e52f5b120fcdcebc4ccd91cdd861a592/tests/data/StaticAndConsts.php | tests/data/StaticAndConsts.php | <?php
namespace yiiunit\twig\data;
class StaticAndConsts
{
const FIRST_CONST = 'I am a const!';
public static $staticVar = 'I am a static var!';
public static function sticFunction($var)
{
return "I am a static function with param {$var}!";
}
}
| php | BSD-3-Clause | 1bae7be1e52f5b120fcdcebc4ccd91cdd861a592 | 2026-01-05T05:08:39.408608Z | false |
yiisoft/yii2-twig | https://github.com/yiisoft/yii2-twig/blob/1bae7be1e52f5b120fcdcebc4ccd91cdd861a592/tests/data/Singer.php | tests/data/Singer.php | <?php
namespace yiiunit\twig\data;
use yii\base\Model;
/**
* Singer
*/
class Singer extends Model
{
public $firstName;
public $lastName;
public $test;
}
| php | BSD-3-Clause | 1bae7be1e52f5b120fcdcebc4ccd91cdd861a592 | 2026-01-05T05:08:39.408608Z | false |
bitpressio/blade-extensions | https://github.com/bitpressio/blade-extensions/blob/eeb4f3acb7253ee28302530c0bd25c5113248507/src/helpers.php | src/helpers.php | <?php
use BitPress\BladeExtension\Container\BladeRegistrar;
if (! function_exists('blade_extension')) {
/**
* @param string|array $abstract
* @param \Closure|string|null $concrete
*/
function blade_extension($service, $concrete = null)
{
BladeRegistrar::register($service, $concrete);
}
}
| php | MIT | eeb4f3acb7253ee28302530c0bd25c5113248507 | 2026-01-05T05:08:49.763946Z | false |
bitpressio/blade-extensions | https://github.com/bitpressio/blade-extensions/blob/eeb4f3acb7253ee28302530c0bd25c5113248507/src/BladeExtensionServiceProvider.php | src/BladeExtensionServiceProvider.php | <?php
namespace BitPress\BladeExtension;
use Illuminate\Support\ServiceProvider;
use BitPress\BladeExtension\Contracts\BladeExtension;
use BitPress\BladeExtension\Exceptions\InvalidBladeExtension;
class BladeExtensionServiceProvider extends ServiceProvider
{
/**
* Bootstrap package services
*
* @return void
*/
public function boot()
{
$this->defineBladeExtensions();
if ($this->app->runningInConsole()) {
$this->defineCommands();
}
}
/**
* Register package services
*
* @return void
*/
public function register()
{
}
/**
* Define package console commands
*/
protected function defineCommands()
{
$this->commands([
Console\Commands\BladeExtensionMakeCommand::class,
]);
}
/**
* Register Blade Extension directives and conditionals with the blade compiler
*
* @return void
*/
protected function defineBladeExtensions()
{
foreach ($this->app->tagged('blade.extension') as $extension) {
if (! $extension instanceof BladeExtension) {
throw new InvalidBladeExtension($extension);
}
foreach ($extension->getDirectives() as $name => $callable) {
$this->app['blade.compiler']->directive($name, $callable);
}
foreach ($extension->getConditionals() as $name => $callable) {
$this->app['blade.compiler']->if($name, $callable);
}
}
}
}
| php | MIT | eeb4f3acb7253ee28302530c0bd25c5113248507 | 2026-01-05T05:08:49.763946Z | false |
bitpressio/blade-extensions | https://github.com/bitpressio/blade-extensions/blob/eeb4f3acb7253ee28302530c0bd25c5113248507/src/Exceptions/BladeExtensionException.php | src/Exceptions/BladeExtensionException.php | <?php
namespace BitPress\BladeExtension\Exceptions;
class BladeExtensionException extends \Exception
{
}
| php | MIT | eeb4f3acb7253ee28302530c0bd25c5113248507 | 2026-01-05T05:08:49.763946Z | false |
bitpressio/blade-extensions | https://github.com/bitpressio/blade-extensions/blob/eeb4f3acb7253ee28302530c0bd25c5113248507/src/Exceptions/InvalidBladeExtension.php | src/Exceptions/InvalidBladeExtension.php | <?php
namespace BitPress\BladeExtension\Exceptions;
use BitPress\BladeExtension\Contracts\BladeExtension;
class InvalidBladeExtension extends BladeExtensionException
{
public function __construct($extension)
{
parent::__construct(sprintf(
"\"%s\" is an invalid Blade extension.\n\nBlade extensions must implement the \"%s\" contract.",
get_class($extension),
BladeExtension::class
));
}
}
| php | MIT | eeb4f3acb7253ee28302530c0bd25c5113248507 | 2026-01-05T05:08:49.763946Z | false |
bitpressio/blade-extensions | https://github.com/bitpressio/blade-extensions/blob/eeb4f3acb7253ee28302530c0bd25c5113248507/src/Container/BladeRegistrar.php | src/Container/BladeRegistrar.php | <?php
namespace BitPress\BladeExtension\Container;
class BladeRegistrar
{
/**
* Register and tag a blade service in the container
*
* @param string|array $abstract
* @param \Closure|string|null $concrete
*/
public static function register($extension, $concrete = null)
{
app()->singleton($extension, $concrete);
app()->tag($extension, 'blade.extension');
}
}
| php | MIT | eeb4f3acb7253ee28302530c0bd25c5113248507 | 2026-01-05T05:08:49.763946Z | false |
bitpressio/blade-extensions | https://github.com/bitpressio/blade-extensions/blob/eeb4f3acb7253ee28302530c0bd25c5113248507/src/Contracts/BladeExtension.php | src/Contracts/BladeExtension.php | <?php
namespace BitPress\BladeExtension\Contracts;
interface BladeExtension
{
/**
* Register directives
*
* ```php
* return [
* 'truncate' => [$this, 'truncate']
* ];
* ```
*
* @return array
*/
public function getDirectives();
/**
* Register conditional directives
*
* ```php
* return [
* 'prod' => [$this, 'isProd']
* ];
* ```
*
* @return array
*/
public function getConditionals();
}
| php | MIT | eeb4f3acb7253ee28302530c0bd25c5113248507 | 2026-01-05T05:08:49.763946Z | false |
bitpressio/blade-extensions | https://github.com/bitpressio/blade-extensions/blob/eeb4f3acb7253ee28302530c0bd25c5113248507/src/Console/Commands/BladeExtensionMakeCommand.php | src/Console/Commands/BladeExtensionMakeCommand.php | <?php
namespace BitPress\BladeExtension\Console\Commands;
use Illuminate\Support\Str;
use Illuminate\Console\GeneratorCommand;
class BladeExtensionMakeCommand extends GeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'make:blade';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a custom blade extension class';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Blade Extension';
/**
* Get the stub file for the generator.
*
* @return string
*/
protected function getStub()
{
return __DIR__ . '/stubs/blade-extension.stub';
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace . '\Blade';
}
/**
* Get the desired class name from the input.
*
* @return string
*/
protected function getNameInput()
{
$name = trim($this->argument('name'));
if (Str::endsWith($name, 'Extension')) {
return $name;
}
return sprintf('%sExtension', $name);
}
}
| php | MIT | eeb4f3acb7253ee28302530c0bd25c5113248507 | 2026-01-05T05:08:49.763946Z | false |
crazybooot/base64-validation | https://github.com/crazybooot/base64-validation/blob/6e5290c20e99735f0228fcde7e81d2597191b9d5/src/Validators/Base64Validator.php | src/Validators/Base64Validator.php | <?php
declare(strict_types = 1);
namespace Crazybooot\Base64Validation\Validators;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Validation\Concerns\ValidatesAttributes;
use Symfony\Component\HttpFoundation\File\File;
use function base64_decode;
use function explode;
use function file_put_contents;
use function stream_get_meta_data;
use function strpos;
use function tmpfile;
use const true;
/**
* Class Base64Validator
*
* @package Crazybooot\Base64Validation\Validators
*/
class Base64Validator
{
use ValidatesAttributes;
private $tmpFileDescriptor;
/**
* @param string $attribute
* @param mixed $value
* @param array $parameters
* @param Validator $validator
*
* @return bool
*/
public function validateBase64Max(string $attribute, $value, array $parameters, Validator $validator): bool
{
return !empty($value)
? $validator->validateMax($attribute, $this->convertToFile($value), $parameters)
: true;
}
/**
* @param string $attribute
* @param mixed $value
* @param array $parameters
* @param Validator $validator
*
* @return bool
*/
public function validateBase64Min(string $attribute, $value, array $parameters, Validator $validator): bool
{
return !empty($value)
? $validator->validateMin($attribute, $this->convertToFile($value), $parameters)
: true;
}
/**
* @param string $attribute
* @param mixed $value
* @param array $parameters
* @param Validator $validator
*
* @return bool
*/
public function validateBase64Dimensions(string $attribute, $value, array $parameters, Validator $validator): bool
{
return !empty($value)
? $this->validateDimensions($attribute, $this->convertToFile($value), $parameters)
: true;
}
/**
* @param string $attribute
* @param mixed $value
* @param array $parameters
* @param Validator $validator
*
* @return bool
*/
public function validateBase64File(string $attribute, $value, array $parameters, Validator $validator): bool
{
return !empty($value)
? $validator->validateFile($attribute, $this->convertToFile($value))
: true;
}
/**
* @param string $attribute
* @param mixed $value
* @param array $parameters
* @param Validator $validator
*
* @return bool
*/
public function validateBase64Image(string $attribute, $value, array $parameters, Validator $validator): bool
{
return !empty($value)
? $validator->validateImage($attribute, $this->convertToFile($value))
: true;
}
/**
* @param string $attribute
* @param mixed $value
* @param array $parameters
* @param Validator $validator
*
* @return bool
*/
public function validateBase64Mimetypes(string $attribute, $value, array $parameters, Validator $validator): bool
{
return !empty($value)
? $validator->validateMimetypes($attribute, $this->convertToFile($value), $parameters)
: true;
}
/**
* @param string $attribute
* @param mixed $value
* @param array $parameters
* @param Validator $validator
*
* @return bool
*/
public function validateBase64Mimes(string $attribute, $value, array $parameters, Validator $validator): bool
{
return !empty($value)
? $validator->validateMimes($attribute, $this->convertToFile($value), $parameters)
: true;
}
/**
* @param string $attribute
* @param mixed $value
* @param array $parameters
* @param Validator $validator
*
* @return bool
*/
public function validateBase64Between(string $attribute, $value, array $parameters, Validator $validator): bool
{
return !empty($value)
? $validator->validateBetween($attribute, $this->convertToFile($value), $parameters)
: true;
}
/**
* @param string $attribute
* @param mixed $value
* @param array $parameters
* @param Validator $validator
*
* @return bool
*/
public function validateBase64Size(string $attribute, $value, array $parameters, Validator $validator): bool
{
return !empty($value)
? $validator->validateSize($attribute, $this->convertToFile($value), $parameters)
: true;
}
/**
* @param string $value
*
* @return File
*/
protected function convertToFile(string $value): File
{
if (strpos($value, ';base64') !== false) {
[, $value] = explode(';', $value);
[, $value] = explode(',', $value);
}
$binaryData = base64_decode($value);
$tmpFile = tmpfile();
$this->tmpFileDescriptor = $tmpFile;
$tmpFilePath = stream_get_meta_data($tmpFile)['uri'];
file_put_contents($tmpFilePath, $binaryData);
return new File($tmpFilePath);
}
/**
* @param $attribute
* @param $value
* @param $parameters
*
* @return bool
*/
public function validateDimensions($attribute, $value, $parameters)
{
if ($this->isValidFileInstance($value) && $value->getMimeType() === 'image/svg+xml') {
return true;
}
if (! $this->isValidFileInstance($value) || ! $sizeDetails = @getimagesize($value->getRealPath())) {
return false;
}
$this->requireParameterCount(1, $parameters, 'dimensions');
[$width, $height] = $sizeDetails;
$parameters = $this->parseNamedParameters($parameters);
if ($this->failsBasicDimensionChecks($parameters, $width, $height) ||
$this->failsRatioCheck($parameters, $width, $height)) {
return false;
}
return true;
}
} | php | MIT | 6e5290c20e99735f0228fcde7e81d2597191b9d5 | 2026-01-05T05:09:03.351722Z | false |
crazybooot/base64-validation | https://github.com/crazybooot/base64-validation/blob/6e5290c20e99735f0228fcde7e81d2597191b9d5/src/Providers/ServiceProvider.php | src/Providers/ServiceProvider.php | <?php
declare(strict_types = 1);
namespace Crazybooot\Base64Validation\Providers;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\ServiceProvider as BaseServiceProvider;
use function config;
use function config_path;
use function implode;
use function trans;
/**
* Class QueueStatsServiceProvider
*
* @package Crazybooot\QueueStats\Providers
*/
class ServiceProvider extends BaseServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot(): void
{
Validator::extend(
'base64max',
'Crazybooot\Base64Validation\Validators\Base64Validator@validateBase64Max'
);
Validator::extend(
'base64min',
'Crazybooot\Base64Validation\Validators\Base64Validator@validateBase64Min'
);
Validator::extend(
'base64dimensions',
'Crazybooot\Base64Validation\Validators\Base64Validator@validateBase64Dimensions'
);
Validator::extend(
'base64file',
'Crazybooot\Base64Validation\Validators\Base64Validator@validateBase64File'
);
Validator::extend(
'base64image',
'Crazybooot\Base64Validation\Validators\Base64Validator@validateBase64Image'
);
Validator::extend(
'base64mimetypes',
'Crazybooot\Base64Validation\Validators\Base64Validator@validateBase64Mimetypes'
);
Validator::extend(
'base64mimes',
'Crazybooot\Base64Validation\Validators\Base64Validator@validateBase64Mimes'
);
Validator::extend(
'base64between',
'Crazybooot\Base64Validation\Validators\Base64Validator@validateBase64Between'
);
Validator::extend(
'base64size',
'Crazybooot\Base64Validation\Validators\Base64Validator@validateBase64Size'
);
if (config('base64validation.replace_validation_messages')) {
Validator::replacer('base64max', function ($message, $attribute, $rule, $parameters, $validator) {
return trans('validation.max.file', ['attribute' => $validator->getDisplayableAttribute($attribute), 'max' => $parameters[0]]);
});
Validator::replacer('base64min', function ($message, $attribute, $rule, $parameters, $validator) {
return trans('validation.min.file', ['attribute' => $validator->getDisplayableAttribute($attribute), 'min' => $parameters[0]]);
});
Validator::replacer('base64dimensions', function ($message, $attribute, $rule, $parameters, $validator) {
return trans('validation.dimensions', ['attribute' => $validator->getDisplayableAttribute($attribute)]);
});
Validator::replacer('base64file', function ($message, $attribute, $rule, $parameters, $validator) {
return trans('validation.file', ['attribute' => $validator->getDisplayableAttribute($attribute)]);
});
Validator::replacer('base64image', function ($message, $attribute, $rule, $parameters, $validator) {
return trans('validation.image', ['attribute' => $validator->getDisplayableAttribute($attribute)]);
});
Validator::replacer('base64mimetypes', function ($message, $attribute, $rule, $parameters, $validator) {
return trans('validation.mimetypes', [
'attribute' => $validator->getDisplayableAttribute($attribute),
'values' => implode(',', $parameters)
]);
});
Validator::replacer('base64mimes', function ($message, $attribute, $rule, $parameters, $validator) {
return trans('validation.mimes', [
'attribute' => $validator->getDisplayableAttribute($attribute),
'values' => implode(',', $parameters),
]);
});
Validator::replacer('base64between', function ($message, $attribute, $rule, $parameters, $validator) {
return trans('validation.between.file', [
'attribute' => $validator->getDisplayableAttribute($attribute),
'min' => $parameters[0],
'max' => $parameters[1]
]);
});
Validator::replacer('base64size', function ($message, $attribute, $rule, $parameters, $validator) {
return trans('validation.size.file', [
'attribute' => $validator->getDisplayableAttribute($attribute),
'size' => $parameters[0],
]);
});
}
$this->publishes([
__DIR__.'/../../config/base64validation.php' => config_path('base64validation.php'),
], 'config');
}
/**
* @return void
*/
public function register(): void
{
$this->mergeConfigFrom(
__DIR__.'/../../config/base64validation.php', 'base64validation'
);
}
} | php | MIT | 6e5290c20e99735f0228fcde7e81d2597191b9d5 | 2026-01-05T05:09:03.351722Z | false |
crazybooot/base64-validation | https://github.com/crazybooot/base64-validation/blob/6e5290c20e99735f0228fcde7e81d2597191b9d5/config/base64validation.php | config/base64validation.php | <?php
declare(strict_types = 1);
return [
/*
|--------------------------------------------------------------------------
| Replace rule validation message
|--------------------------------------------------------------------------
|
| If set true will be used validation messages for standard
| file validation rules (for base64min - validation.min.file message, etc)
| for using own messages set this property to false and define message
| replacement for each rule you use in afforded by framework way
|
*/
'replace_validation_messages' => true,
];
| php | MIT | 6e5290c20e99735f0228fcde7e81d2597191b9d5 | 2026-01-05T05:09:03.351722Z | false |
ferranfg/midjourney-discord-api-php | https://github.com/ferranfg/midjourney-discord-api-php/blob/65ec41a7cced09be0ae1e2264ec9f85c19087bf7/demo.php | demo.php | <?php
include 'vendor/autoload.php';
use Ferranfg\MidjourneyPhp\Midjourney;
$discord_channel_id = '';
$discord_user_token = '';
$midjourney = new Midjourney($discord_channel_id, $discord_user_token);
// It takes about 1 minue to generate and upscale an image
$message = $midjourney->generate('A cat riding a horse --v 5');
echo $message->upscaled_photo_url; | php | MIT | 65ec41a7cced09be0ae1e2264ec9f85c19087bf7 | 2026-01-05T05:09:09.240988Z | false |
ferranfg/midjourney-discord-api-php | https://github.com/ferranfg/midjourney-discord-api-php/blob/65ec41a7cced09be0ae1e2264ec9f85c19087bf7/src/Midjourney.php | src/Midjourney.php | <?php
namespace Ferranfg\MidjourneyPhp;
use Exception;
use GuzzleHttp\Client;
class Midjourney {
private const API_URL = 'https://discord.com/api/v9';
protected const APPLICATION_ID = '936929561302675456';
protected const DATA_ID = '938956540159881230';
protected const DATA_VERSION = '1166847114203123795';
protected const SESSION_ID = '2fb980f65e5c9a77c96ca01f2c242cf6';
private static $client;
private static $channel_id;
private static $oauth_token;
private static $guild_id;
private static $user_id;
public function __construct($channel_id, $oauth_token)
{
self::$channel_id = $channel_id;
self::$oauth_token = $oauth_token;
self::$client = new Client([
'base_uri' => self::API_URL,
'headers' => [
'Authorization' => self::$oauth_token
]
]);
$request = self::$client->get('channels/' . self::$channel_id);
$response = json_decode((string) $request->getBody());
self::$guild_id = $response->guild_id;
$request = self::$client->get('users/@me');
$response = json_decode((string) $request->getBody());
self::$user_id = $response->id;
}
private static function firstWhere($array, $key, $value = null)
{
foreach ($array as $item)
{
if (
(is_callable($key) and $key($item)) or
(is_string($key) and str_starts_with($item->{$key}, $value))
)
{
return $item;
}
}
return null;
}
public function imagine(string $prompt)
{
$params = [
'type' => 2,
'application_id' => self::APPLICATION_ID,
'guild_id' => self::$guild_id,
'channel_id' => self::$channel_id,
'session_id' => self::SESSION_ID,
'data' => [
'version' => self::DATA_VERSION,
'id' => self::DATA_ID,
'name' => 'imagine',
'type' => 1,
'options' => [[
'type' => 3,
'name' => 'prompt',
'value' => $prompt
]],
'application_command' => [
'id' => self::DATA_ID,
'application_id' => self::APPLICATION_ID,
'version' => self::DATA_VERSION,
'default_member_permissions' => null,
'type' => 1,
'nsfw' => false,
'name' => 'imagine',
'description' => 'Create images with Midjourney',
'dm_permission' => true,
'options' => [[
'type' => 3,
'name' => 'prompt',
'description' => 'The prompt to imagine',
'required' => true
]]
],
'attachments' => []
]
];
self::$client->post('interactions', [
'json' => $params
]);
sleep(8);
$imagine_message = null;
while (is_null($imagine_message))
{
$imagine_message = $this->getImagine($prompt);
if (is_null($imagine_message)) sleep(8);
}
return $imagine_message;
}
public function getImagine(string $prompt)
{
$response = self::$client->get('channels/' . self::$channel_id . '/messages');
$response = json_decode((string) $response->getBody());
$raw_message = self::firstWhere($response, function ($item) use ($prompt)
{
return (
str_starts_with($item->content, "**{$prompt}** - <@" . self::$user_id . '>') and
! str_contains($item->content, '%') and
str_ends_with($item->content, '(fast)')
);
});
if (is_null($raw_message)) return null;
return (object) [
'id' => $raw_message->id,
'prompt' => $prompt,
'raw_message' => $raw_message
];
}
public function upscale($message, int $upscale_index = 0)
{
if ( ! property_exists($message, 'raw_message'))
{
throw new Exception('Upscale requires a message object obtained from the imagine/getImagine methods.');
}
if ($upscale_index < 0 or $upscale_index > 3)
{
throw new Exception('Upscale index must be between 0 and 3.');
}
$upscale_hash = null;
$raw_message = $message->raw_message;
if (property_exists($raw_message, 'components') and is_array($raw_message->components))
{
$upscales = $raw_message->components[0]->components;
$upscale_hash = $upscales[$upscale_index]->custom_id;
}
$params = [
'type' => 3,
'guild_id' => self::$guild_id,
'channel_id' => self::$channel_id,
'message_flags' => 0,
'message_id' => $message->id,
'application_id' => self::APPLICATION_ID,
'session_id' => self::SESSION_ID,
'data' => [
'component_type' => 2,
'custom_id' => $upscale_hash
]
];
self::$client->post('interactions', [
'json' => $params
]);
$upscaled_photo_url = null;
while (is_null($upscaled_photo_url))
{
$upscaled_photo_url = $this->getUpscale($message, $upscale_index);
if (is_null($upscaled_photo_url)) sleep(3);
}
return $upscaled_photo_url;
}
public function getUpscale($message, $upscale_index = 0)
{
if ( ! property_exists($message, 'raw_message'))
{
throw new Exception('Upscale requires a message object obtained from the imagine/getImagine methods.');
}
if ($upscale_index < 0 or $upscale_index > 3)
{
throw new Exception('Upscale index must be between 0 and 3.');
}
$prompt = $message->prompt;
$response = self::$client->get('channels/' . self::$channel_id . '/messages');
$response = json_decode((string) $response->getBody());
$message_index = $upscale_index + 1;
$message = self::firstWhere($response, 'content', "**{$prompt}** - Image #{$message_index} <@" . self::$user_id . '>');
if (is_null($message))
{
$message = self::firstWhere($response, 'content', "**{$prompt}** - Upscaled by <@" . self::$user_id . '> (fast)');
}
if (is_null($message)) return null;
if (property_exists($message, 'attachments') and is_array($message->attachments))
{
$attachment = $message->attachments[0];
return $attachment->url;
}
return null;
}
public function generate($prompt, $upscale_index = 0)
{
$imagine = $this->imagine($prompt);
$upscaled_photo_url = $this->upscale($imagine, $upscale_index);
return (object) [
'imagine_message_id' => $imagine->id,
'upscaled_photo_url' => $upscaled_photo_url
];
}
}
| php | MIT | 65ec41a7cced09be0ae1e2264ec9f85c19087bf7 | 2026-01-05T05:09:09.240988Z | false |
Rct567/DomQuery | https://github.com/Rct567/DomQuery/blob/4bc72c3da2e82eb7c08fa30582f71e91843423df/src/Rct567/DomQuery/DomQueryNodes.php | src/Rct567/DomQuery/DomQueryNodes.php | <?php
namespace Rct567\DomQuery;
/**
* Class DomQueryNodes
*
* @property string $tagName
* @property string $nodeName
* @property string $nodeValue
* @property string $outerHTML
*
* @method string getAttribute(string $name)
*
* @package Rct567\DomQuery
*/
class DomQueryNodes implements \Countable, \IteratorAggregate, \ArrayAccess
{
/**
* Instance of DOMDocument
*
* @var \DOMDocument|null
*/
protected $document;
/**
* All nodes as instances of DOMNode
*
* @var \DOMNode[]
*/
protected $nodes = array();
/**
* Instance of DOMXPath class
*
* @var \DOMXPath|null
*/
protected $dom_xpath;
/**
* Number of nodes
*
* @var integer
*/
public $length = 0;
/**
* Load and return as xml
*
* @var bool
*/
public $xml_mode;
/**
* Return xml with pi node (xml declaration) if in xml mode
*
* @var bool
*/
public $xml_print_pi = false;
/**
* Preserve no newlines (prevent creating newlines in html result)
*
* @var bool
*/
public $preserve_no_newlines;
/**
* LibXMl options used to load html for DOMDocument
*
* @var mixed
*/
public $libxml_options =
LIBXML_HTML_NOIMPLIED // turns off the automatic adding of implied html/body
| LIBXML_HTML_NODEFDTD; // prevents a default doctype being added when one is not found
/**
* Previous instance of the chain
*
* @var static|null
*/
protected $prev_instance;
/**
* Root instance who began the chain
*
* @var static|null
*/
protected $root_instance;
/**
* Xpath expression used to create the result of this instance
*
* @var string|null
*/
private $xpath_query;
/**
* Css selector given to create result of this instance
*
* @var string|null
*/
private $css_query;
/**
* Jquery style property; css selector given to create result of this instance
*
* @var string|null
*/
public $selector;
/**
* Constructor
*
* @throws \InvalidArgumentException
*/
final public function __construct()
{
if (\func_num_args() === 2 && \is_string(\func_get_arg(0)) && strpos(func_get_arg(0), '<') === false) {
$result = self::create(func_get_arg(1))->find(func_get_arg(0));
$this->addNodes($result->nodes);
return;
}
foreach (\func_get_args() as $arg) {
if ($arg instanceof \DOMDocument) {
$this->setDomDocument($arg);
} elseif ($arg instanceof \DOMNodeList) {
$this->loadDomNodeList($arg);
} elseif ($arg instanceof \DOMNode) {
$this->addDomNode($arg);
} elseif (\is_array($arg) && $arg[0] instanceof \DOMNode) {
$this->addNodes($arg);
} elseif ($arg instanceof \DOMXPath) {
$this->dom_xpath = $arg;
} elseif (\is_string($arg) && strpos($arg, '<') !== false) {
$this->loadContent($arg);
} elseif (\is_object($arg)) {
throw new \InvalidArgumentException('Unknown object '. \get_class($arg).' given as argument');
} else {
throw new \InvalidArgumentException('Unknown argument '. \gettype($arg));
}
}
}
/**
* Create new instance of self with some properties of its parents.
*
* @return static
*/
protected function createChildInstance()
{
$instance = new static(...\func_get_args());
if (isset($this->document)) {
$instance->setDomDocument($this->document);
}
// This should not be set the first time it is created.
if (isset($this->root_instance)) {
$instance->prev_instance = $this;
}
if (isset($this->root_instance)) {
$instance->root_instance = $this->root_instance;
} else {
$instance->root_instance = $this;
}
if (\is_bool($this->xml_mode)) {
$instance->xml_mode = $this->xml_mode;
}
if (isset($this->document) && $this->dom_xpath instanceof \DOMXPath) {
$instance->dom_xpath = $this->dom_xpath;
}
return $instance;
}
/**
* Make xpath query relative by adding a dot, while keeping
* in mind there might be a union, so:
* '//div|//p', should become '(.//div|.//p)'.
*
* @param string $xpath
*
* @return string
*/
private static function xpathMakeQueryRelative(string $xpath)
{
$matching_slash_to_add_dot = '/(?<=[(]|^)(?![^\[]*])\//';
if (strpos($xpath, '|') === false) { // no union
return preg_replace($matching_slash_to_add_dot, './', $xpath, 1); // add dot before the forward slash
}
$expressions = preg_split('/\|(?![^\[]*\])/', $xpath); // split on union operators not inside brackets
$expressions = array_map(function ($expr) use ($matching_slash_to_add_dot) {
return preg_replace($matching_slash_to_add_dot, './', trim($expr), 1); // add dot before the forward slash
}, $expressions);
$new_xpath = implode('|', $expressions);
return count($expressions) > 1 ? '(' . $new_xpath . ')' : $new_xpath;
}
/**
* Use xpath and return new DomQuery with resulting nodes.
*
* @param string $xpath_query
*
* @return static
*/
public function xpath(string $xpath_query)
{
$result = $this->createChildInstance();
if (isset($this->document)) {
$result->xpath_query = $xpath_query;
if (isset($this->root_instance) || isset($this->xpath_query)) { // all nodes as context
$xpath_query_relative = self::xpathMakeQueryRelative($xpath_query);
foreach ($this->nodes as $node) {
if ($result_node_list = $this->xpathQuery($xpath_query_relative, $node)) {
$result->loadDomNodeList($result_node_list);
}
}
} else { // whole document
if ($result_node_list = $this->xpathQuery($xpath_query)) {
$result->loadDomNodeList($result_node_list);
}
}
}
return $result;
}
/**
* Retrieve last created XPath query.
*
* @return \DOMXPath|null
*/
public function getDomXpath()
{
if (!$this->dom_xpath) {
$this->dom_xpath = $this->createDomXpath();
}
return $this->dom_xpath;
}
/**
* Retrieve last created XPath query.
*
* @return string|null
*/
public function getXpathQuery()
{
return $this->xpath_query;
}
/**
* Create new instance.
*
* @return static
* @throws \InvalidArgumentException
*/
public static function create()
{
if (func_get_arg(0) instanceof static) {
return func_get_arg(0);
}
return new static(...\func_get_args());
}
/**
* Set dom document.
*
* @param \DOMDocument $document
*
* @return void
* @throws \Exception if other document is already set
*/
public function setDomDocument(\DOMDocument $document)
{
if (isset($this->document) && $this->document !== $document) {
throw new \Exception('Other DOMDocument already set!');
}
$this->document = $document;
}
/**
* Add nodes from dom node list to result set.
*
* @param \DOMNodeList $dom_node_list
*
* @return void
* @throws \Exception if no document is set and list is empty
*/
public function loadDomNodeList(\DOMNodeList $dom_node_list, $prepend=false)
{
if (!isset($this->document) && $dom_node_list->length === 0) {
throw new \Exception('DOMDocument is missing!');
}
if ($dom_node_list->length > 0) {
$this->setDomDocument($dom_node_list->item(0)->ownerDocument);
}
foreach ($dom_node_list as $node) {
$this->addDomNode($node, $prepend);
}
}
/**
* Add an array of nodes to the result set.
*
* @param \DOMNode[] $dom_nodes
*
* @return void
*/
public function addDomNodes(array $dom_nodes)
{
if (!isset($dom_nodes[0])) {
return;
}
foreach ($dom_nodes as $dom_node) {
$this->nodes[] = $dom_node;
}
$this->length = \count($this->nodes);
if ($dom_nodes[0] instanceof \DOMDocument) {
$this->setDomDocument($dom_nodes[0]);
} else {
$this->setDomDocument($dom_nodes[0]->ownerDocument);
}
}
/**
* Add a single node to the result set.
*
* @param \DOMNode $dom_node
* @param bool $prepend
*
* @return void
*/
public function addDomNode(\DOMNode $dom_node, $prepend=false)
{
if ($prepend) {
\array_unshift($this->nodes, $dom_node);
} else {
$this->nodes[] = $dom_node;
}
$this->length = \count($this->nodes);
if ($dom_node instanceof \DOMDocument) {
$this->setDomDocument($dom_node);
} else {
$this->setDomDocument($dom_node->ownerDocument);
}
}
/**
* Load html or xml content.
*
* @param string $content
* @param string $encoding
*
* @return void
*/
public function loadContent(string $content, $encoding='UTF-8')
{
$this->preserve_no_newlines = (strpos($content, '<') !== false && strpos($content, "\n") === false);
$content_has_leading_pi = stripos($content, '<?xml') === 0;
if (!\is_bool($this->xml_mode)) {
$this->xml_mode = $content_has_leading_pi;
}
$this->xml_print_pi = $content_has_leading_pi;
$xml_pi_node_added = false;
if (!$this->xml_mode && $encoding && !$content_has_leading_pi) {
$content = '<?xml encoding="'.$encoding.'">'.$content; // add pi node to make libxml use the correct encoding
$xml_pi_node_added = true;
}
if (\PHP_VERSION_ID < 80000) {
libxml_disable_entity_loader(true);
}
libxml_use_internal_errors(true);
$dom_document = new \DOMDocument('1.0', $encoding);
$dom_document->strictErrorChecking = false;
$dom_document->validateOnParse = false;
$dom_document->recover = true;
if ($this->xml_mode) {
$dom_document->loadXML($content, $this->libxml_options);
} else {
$dom_document->loadHTML($content, $this->libxml_options);
}
$this->setDomDocument($dom_document);
if ($xml_pi_node_added) { // pi node added, now remove it
foreach ($dom_document->childNodes as $node) {
if ($node->nodeType === XML_PI_NODE) {
$dom_document->removeChild($node);
break;
}
}
}
foreach ($dom_document->childNodes as $node) {
$this->nodes[] = $node;
}
$this->length = \count($this->nodes);
}
/**
* Grants access to the DOM nodes of this instance.
*
* @param int $index
*
* @return \DOMNode|null
*/
public function get($index)
{
$result = \array_slice($this->nodes, $index, 1); // note: index can be negative
if (\count($result) > 0) {
return $result[0];
}
return null; // return null if no result for key
}
/**
* Get the descendants of each element in the current set of matched elements, filtered by a selector.
*
* @param string|static|\DOMNodeList|\DOMNode $selector A string containing a selector expression,
* or DomQuery|DOMNodeList|DOMNode instance to match against.
*
* @return static
*/
public function find($selector)
{
if (\is_string($selector)) {
$css_expression = $selector;
} else {
$selector_tag_names = array();
$selector_result = self::create($selector);
foreach ($selector_result as $node) {
$selector_tag_names[] = $node->tagName;
}
$css_expression = implode(',', $selector_tag_names);
}
$xpath_expression = CssToXpath::transform($css_expression);
$result = $this->xpath($xpath_expression);
if (\is_string($selector)) {
$result->css_query = $css_expression;
$result->selector = $css_expression; // jquery style
}
if (isset($selector_result)) {
$new_result_nodes = array();
foreach ($result->nodes as $result_node) {
foreach ($selector_result->nodes as $selector_result_node) {
if ($result_node->isSameNode($selector_result_node)) {
$new_result_nodes[] = $result_node;
}
}
}
$result->nodes = $new_result_nodes;
}
return $result;
}
/**
* Get next element from node.
*
* @param \DOMNode $node
*
* @return \DOMElement|void
*/
protected static function getNextElement(\DOMNode $node)
{
while ($node = $node->nextSibling) {
if ($node instanceof \DOMElement) {
return $node;
}
}
}
/**
* Get previous element from node.
*
* @param \DOMNode $node
*
* @return \DOMElement|void
*/
protected static function getPreviousElement(\DOMNode $node)
{
while ($node = $node->previousSibling) {
if ($node instanceof \DOMElement) {
return $node;
}
}
}
/**
* Retrieve last used CSS Query.
*
* @return string|null
*/
public function getCssQuery()
{
return $this->css_query;
}
/**
* Get the descendants of each element in the current set of matched elements, filtered by a selector.
* If no results are found an exception is thrown.
*
* @param string|static|\DOMNodeList|\DOMNode $selector A string containing a selector expression,
* or DomQuery|DOMNodeList|DOMNode instance to match against.
*
* @return static
* @throws \Exception if no results are found
*/
public function findOrFail($selector)
{
$result = $this->find($selector);
if ($result->length === 0) {
if (\is_string($selector)) {
throw new \Exception('Find with selector "'.$selector.'" failed!');
}
throw new \Exception('Find with node (collection) as selector failed!');
}
return $result;
}
/**
* Iterate over result set and executing a callback for each node.
*
* @param callable $callback
*
* @return $this
*/
public function each(callable $callback)
{
foreach ($this->nodes as $index => $node) {
$return_value = \call_user_func($callback, $node, $index);
if ($return_value === false) {
break;
}
}
return $this;
}
/**
* Pass each element in the current matched set through a function,
* producing an array containing the return values.
*
* @param callable $callback
*
* @return array
*/
public function map(callable $callback)
{
$result = array();
foreach ($this->nodes as $index => $node) {
$return_value = \call_user_func($callback, $node, $index);
if ($return_value === null) {
continue;
} elseif (\is_array($return_value)) {
$result = \array_merge($result, $return_value);
} else {
$result[] = $return_value;
}
}
return $result;
}
/**
* Returns dom elements.
*
* @return \Generator
*/
protected function getElements()
{
foreach ($this->nodes as $node) {
if ($node instanceof \DOMElement) {
yield $node;
}
}
}
/**
* Return array with nodes.
*
* @return \DOMNode[]
*/
protected function getNodes()
{
return $this->nodes;
}
/**
* Return array with cloned nodes.
*
* @return \DOMNode[]
*/
protected function getClonedNodes()
{
$cloned_nodes = array();
foreach ($this->nodes as $node) {
$cloned_node = $node->cloneNode(true);
if ($cloned_node instanceof \DOMElement && $cloned_node->hasAttribute('dqn_tmp_id')) {
$cloned_node->removeAttribute('dqn_tmp_id');
}
$cloned_nodes[] = $cloned_node;
}
return $cloned_nodes;
}
/**
* Return array with nodes.
*
* @return \DOMNode[]
*/
public function toArray()
{
return $this->nodes;
}
/**
* Add nodes to result set.
*
* @param \DOMNode[] $node_list
* @param bool $prepend
*
* @return void
*/
public function addNodes(array $node_list, $prepend=false)
{
foreach ($node_list as $node) {
$this->addDomNode($node, $prepend);
}
}
/**
* Return first DOMElement.
*
* @return \DOMElement|void
*/
protected function getFirstElmNode()
{
foreach ($this->nodes as $node) {
if ($node instanceof \DOMElement) {
return $node;
}
}
}
/**
* Access xpath or ... DOMNode properties (nodeName, parentNode etc) or get attribute value of first node.
*
* @param string $name
*
* @return \DOMXPath|\DOMNode|string|null
*/
public function __get($name)
{
if ($name === 'outerHTML') {
return $this->getOuterHtml();
}
if ($node = $this->getFirstElmNode()) {
if (isset($node->$name)) {
return $node->{$name};
}
if ($node instanceof \DOMElement && $node->hasAttribute($name)) {
return $node->getAttribute($name);
}
}
return null;
}
/**
* Call method on first DOMElement.
*
* @param string $name
* @param mixed[] $arguments
*
* @return mixed
* @throws \Exception
*/
public function __call($name, array $arguments)
{
if (method_exists($this->getFirstElmNode(), $name)) {
return \call_user_func_array(array($this->getFirstElmNode(), $name), $arguments);
}
throw new \Exception('Unknown call '.$name);
}
/**
* Perform query via xpath expression (using DOMXPath::query).
*
* @param string $expression
* @param \DOMNode|null $context_node
*
* @return \DOMNodeList|false
* @throws \Exception
*/
public function xpathQuery(string $expression, ?\DOMNode $context_node=null)
{
if ($dom_xpath = $this->getDomXpath()) {
$node_list = $dom_xpath->query($expression, $context_node);
if ($node_list instanceof \DOMNodeList) {
return $node_list;
} elseif ($node_list === false && $context_node) {
throw new \Exception('Expression '.$expression.' is malformed or contextnode is invalid.');
} elseif ($node_list === false) {
throw new \Exception('Expression '.$expression.' is malformed.');
}
}
return false;
}
/**
* Create dom xpath instance.
*
* @return \DOMXPath|null
*/
private function createDomXpath()
{
if (!$this->document) {
return null;
}
$xpath = new \DOMXPath($this->document);
if ($this->xml_mode) { // register all name spaces
foreach ($xpath->query('namespace::*') as $node) {
if ($node->prefix !== 'xml') {
$xpath->registerNamespace($node->prefix, $node->namespaceURI);
}
}
}
return $xpath;
}
/**
* Countable: get count
*
* @return int
*/
public function count(): int
{
return count($this->nodes);
}
/**
* Retrieve DOMDocument
*
* @return \DOMDocument|null
*/
public function getDocument()
{
return $this->document;
}
/**
* Return html of all nodes (HTML fragment describing all the elements, including their descendants).
*
* @return string
*/
public function getOuterHtml()
{
$outer_html = '';
if ($this->xml_mode && $this->xml_print_pi) {
$outer_html .= '<?xml version="'.$this->document->xmlVersion.'" encoding="'.$this->document->xmlEncoding.'"?>';
$outer_html .= "\n\n";
}
foreach ($this->nodes as $node) {
if (isset($this->document)) {
if ($this->xml_mode) {
$outer_html .= $this->document->saveXML($node);
} else {
$outer_html .= $this->document->saveHTML($node);
}
}
}
$outer_html = $this->handleHtmlResult($outer_html);
return $outer_html;
}
/**
* Get id for node.
*
* @param \DOMElement $node
*
* @return string $node_id
*/
public static function getElementId(\DOMElement $node)
{
if ($node->hasAttribute('dqn_tmp_id')) {
return $node->getAttribute('dqn_tmp_id');
}
$node_id = md5(mt_rand());
$node->setAttribute('dqn_tmp_id', $node_id);
return $node_id;
}
/**
* Handle html when resulting html is requested.
*
* @param string $html
*
* @return string
*/
private function handleHtmlResult($html)
{
if ($this->preserve_no_newlines) {
$html = str_replace("\n", '', $html);
}
if (stripos($html, 'dqn_tmp_id=') !== false) {
$html = preg_replace('/ dqn_tmp_id="([a-z0-9]+)"/', '', $html);
}
return $html;
}
/**
* Get the HTML contents of the first element in the set of matched elements.
*
* @return string
*/
public function getInnerHtml()
{
$html = '';
if ($content_node = $this->getFirstElmNode()) {
$document = $content_node->ownerDocument;
foreach ($content_node->childNodes as $node) {
if ($this->xml_mode) {
$html .= $document->saveXML($node);
} else {
$html .= $document->saveHTML($node);
}
}
$html = $this->handleHtmlResult($html);
}
return $html;
}
/**
* Return html of all nodes.
*
* @return string
*/
public function __toString()
{
return $this->getOuterHtml();
}
/**
* IteratorAggregate (note: using Iterator conflicts with next method in jquery).
*
* @return \ArrayIterator containing nodes as instances of DomQuery
*/
public function getIterator(): \ArrayIterator
{
$iteration_result = array();
if (\is_array($this->nodes)) {
foreach ($this->nodes as $node) {
$iteration_result[] = $this->createChildInstance($node);
}
}
return new \ArrayIterator($iteration_result);
}
/**
* ArrayAccess: offset exists
*
* @param mixed $key
*
* @return bool
*/
public function offsetExists($key): bool
{
return isset($this->nodes[$key]);
}
/**
* ArrayAccess: get offset
*
* @param mixed $key
*
* @return static
*/
public function offsetGet($key): self
{
if (!\is_int($key)) {
throw new \BadMethodCallException('Attempting to access node list with non-integer');
}
if (isset($this->nodes[$key])) {
return $this->createChildInstance($this->nodes[$key]);
}
return $this->createChildInstance();
}
/**
* ArrayAccess: set offset
*
* @param mixed $key
* @param mixed $value
*
* @throws \BadMethodCallException when attempting to write to a read-only item
*/
public function offsetSet($key, $value): void
{
throw new \BadMethodCallException('Attempting to write to a read-only node list');
}
/**
* ArrayAccess: unset offset
*
* @param mixed $key
*
* @throws \BadMethodCallException when attempting to unset a read-only item
*/
public function offsetUnset($key): void
{
throw new \BadMethodCallException('Attempting to unset on a read-only node list');
}
}
| php | MIT | 4bc72c3da2e82eb7c08fa30582f71e91843423df | 2026-01-05T05:09:18.310463Z | false |
Rct567/DomQuery | https://github.com/Rct567/DomQuery/blob/4bc72c3da2e82eb7c08fa30582f71e91843423df/src/Rct567/DomQuery/DomQuery.php | src/Rct567/DomQuery/DomQuery.php | <?php
namespace Rct567\DomQuery;
/**
* Class DomQuery
*
* @package Rct567\DomQuery
*/
class DomQuery extends DomQueryNodes
{
/**
* Node data
*
* @var array[]
*/
private static $node_data = array();
/**
* Get the combined text contents of each element in the set of matched elements, including their descendants,
* or set the text contents of the matched elements.
*
* @param string|null $val
*
* @return $this|string|void
*/
public function text($val=null)
{
if ($val !== null) { // set node value for all nodes
foreach ($this->nodes as $node) {
$node->nodeValue = $val;
}
return $this;
}
if ($node = $this->getFirstElmNode()) { // get value for first node
return $node->nodeValue;
}
}
/**
* Get the HTML contents of the first element in the set of matched elements
*
* @param string|null $html_string
*
* @return $this|string
*/
public function html($html_string=null)
{
if ($html_string !== null) { // set html for all nodes
foreach ($this as $node) {
$node->get(0)->nodeValue = '';
$node->append($html_string);
}
return $this;
}
// get html for first node
return $this->getInnerHtml();
}
/**
* Get the value of an attribute for the first element in the set of matched elements
* or set one or more attributes for every matched element.
*
* @param string $name
* @param string $val
*
* @return $this|string|void
*/
public function attr(string $name, $val=null)
{
if ($val !== null) { // set attribute for all nodes
foreach ($this->getElements() as $node) {
$node->setAttribute($name, $val);
}
return $this;
}
if ($node = $this->getFirstElmNode()) { // get attribute value for first element
return $node->getAttribute($name);
}
}
/**
* Store arbitrary data associated with the matched elements or return the value at
* the named data store for the first element in the set of matched elements.
*
* @param string $key
* @param mixed $val
*
* @return $this|string|object|void
*/
public function data(?string $key=null, $val=null)
{
$doc_hash = spl_object_hash($this->document);
if ($val !== null) { // set data for all nodes
if (!isset(self::$node_data[$doc_hash])) {
self::$node_data[$doc_hash] = array();
}
foreach ($this->getElements() as $node) {
if (!isset(self::$node_data[$doc_hash][self::getElementId($node)])) {
self::$node_data[$doc_hash][self::getElementId($node)] = (object) array();
}
self::$node_data[$doc_hash][self::getElementId($node)]->$key = $val;
}
return $this;
}
if ($node = $this->getFirstElmNode()) { // get data for first element
if (isset(self::$node_data[$doc_hash]) && isset(self::$node_data[$doc_hash][self::getElementId($node)])) {
if ($key === null) {
return self::$node_data[$doc_hash][self::getElementId($node)];
} elseif (isset(self::$node_data[$doc_hash][self::getElementId($node)]->$key)) {
return self::$node_data[$doc_hash][self::getElementId($node)]->$key;
}
}
if ($key === null) { // object with all data
$data = array();
foreach ($node->attributes as $attr) {
if (strpos($attr->nodeName, 'data-') === 0) {
$val = $attr->nodeValue[0] === '{' ? json_decode($attr->nodeValue) : $attr->nodeValue;
$data[substr($attr->nodeName, 5)] = $val;
}
}
return (object) $data;
}
if ($data = $node->getAttribute('data-'.$key)) {
$val = $data[0] === '{' ? json_decode($data) : $data;
return $val;
}
}
}
/**
* Remove a previously-stored piece of data.
*
* @param string|string[] $name
*
* @return void
*/
public function removeData($name=null)
{
$remove_names = \is_array($name) || \is_null($name) ? $name : explode(' ', $name);
$doc_hash = spl_object_hash($this->document);
if (!isset(self::$node_data[$doc_hash])) {
return;
}
foreach ($this->getElements() as $node) {
if (!$node->hasAttribute('dqn_tmp_id')) {
continue;
}
$node_id = self::getElementId($node);
if (isset(self::$node_data[$doc_hash][$node_id])) {
if ($name === null) {
self::$node_data[$doc_hash][$node_id] = null;
} else {
foreach ($remove_names as $remove_name) {
if (isset(self::$node_data[$doc_hash][$node_id]->$remove_name)) {
self::$node_data[$doc_hash][$node_id]->$remove_name = null;
}
}
}
}
}
}
/**
* Convert css string to array.
*
* @param string $css_str containing style properties
*
* @return array<string, string> with key-value as style properties
*/
private static function parseStyle(string $css_str)
{
$statements = explode(';', preg_replace('/\s+/s', ' ', $css_str));
$styles = array();
foreach ($statements as $statement) {
if ($p = strpos($statement, ':')) {
$key = trim(substr($statement, 0, $p));
$value = trim(substr($statement, $p + 1));
$styles[$key] = $value;
}
}
return $styles;
}
/**
* Convert css name-value array to string.
*
* @param array<string, string> $css_array with style properties
*
* @return string containing style properties
*/
private static function getStyle(array $css_array)
{
$styles = '';
foreach ($css_array as $key => $value) {
$styles .= $key.': '.$value.';';
}
return $styles;
}
/**
* Get the value of a computed style property for the first element in the set of matched elements
* or set one or more CSS properties for every matched element.
*
* @param string $name
* @param string $val
*
* @return $this|string|void
*/
public function css(string $name, $val=null)
{
if ($val !== null) { // set css for all nodes
foreach ($this->getElements() as $node) {
$style = self::parseStyle($node->getAttribute('style'));
$style[$name] = $val;
$node->setAttribute('style', self::getStyle($style));
}
return $this;
}
if ($node = $this->getFirstElmNode()) { // get css value for first element
$style = self::parseStyle($node->getAttribute('style'));
if (isset($style[$name])) {
return $style[$name];
}
}
}
/**
* Remove an attribute from each element in the set of matched elements.
* Name can be a space-separated list of attributes.
*
* @param string|string[] $name
*
* @return $this
*/
public function removeAttr($name)
{
$remove_names = \is_array($name) ? $name : explode(' ', $name);
foreach ($this->getElements() as $node) {
foreach ($remove_names as $remove_name) {
$node->removeAttribute($remove_name);
}
}
return $this;
}
/**
* Adds the specified class(es) to each element in the set of matched elements.
*
* @param string|string[] $class_name class name(s)
*
* @return $this
*/
public function addClass($class_name)
{
$add_names = \is_array($class_name) ? $class_name : explode(' ', $class_name);
foreach ($this->getElements() as $node) {
$node_classes = array();
if ($node_class_attr = $node->getAttribute('class')) {
$node_classes = explode(' ', $node_class_attr);
}
foreach ($add_names as $add_name) {
if (!\in_array($add_name, $node_classes, true)) {
$node_classes[] = $add_name;
}
}
if (\count($node_classes) > 0) {
$node->setAttribute('class', implode(' ', $node_classes));
}
}
return $this;
}
/**
* Determine whether any of the matched elements are assigned the given class.
*
* @param string $class_name
*
* @return bool
*/
public function hasClass($class_name)
{
foreach ($this->nodes as $node) {
if ($node instanceof \DOMElement && $node_class_attr = $node->getAttribute('class')) {
$node_classes = explode(' ', $node_class_attr);
if (\in_array($class_name, $node_classes, true)) {
return true;
}
}
}
return false;
}
/**
* Remove a single class, multiple classes, or all classes from each element in the set of matched elements.
*
* @param string|string[] $class_name
*
* @return $this
*/
public function removeClass($class_name='')
{
$remove_names = \is_array($class_name) ? $class_name : explode(' ', $class_name);
foreach ($this->nodes as $node) {
if ($node instanceof \DOMElement && $node->hasAttribute('class')) {
$node_classes = preg_split('#\s+#s', $node->getAttribute('class'));
$class_removed = false;
if ($class_name === '') { // remove all
$node_classes = array();
$class_removed = true;
} else {
foreach ($remove_names as $remove_name) {
$key = array_search($remove_name, $node_classes, true);
if ($key !== false) {
unset($node_classes[$key]);
$class_removed = true;
}
}
}
if ($class_removed) {
$node->setAttribute('class', implode(' ', $node_classes));
}
}
}
return $this;
}
/**
* Remove a single class, multiple classes, or all classes from each element in the set of matched elements.
*
* @param string|string[] $class_name
*
* @return $this
*/
public function toggleClass($class_name='')
{
$toggle_names = \is_array($class_name) ? $class_name : explode(' ', $class_name);
foreach ($this as $node) {
foreach ($toggle_names as $toggle_class) {
if (!$node->hasClass($toggle_class)) {
$node->addClass($toggle_class);
} else {
$node->removeClass($toggle_class);
}
}
}
return $this;
}
/**
* Get the value of a property for the first element in the set of matched elements
* or set one or more properties for every matched element.
*
* @param string $name
* @param string $val
*
* @return $this|mixed|null
*/
public function prop(string $name, $val=null)
{
if ($val !== null) { // set attribute for all nodes
foreach ($this->nodes as $node) {
$node->$name = $val;
}
return $this;
}
// get property value for first element
if ($name === 'outerHTML') {
return $this->getOuterHtml();
}
if ($node = $this->getFirstElmNode()) {
if (isset($node->$name)) {
return $node->$name;
}
}
}
/**
* Get the children of each element in the set of matched elements, including text and comment nodes.
*
* @return self
*/
public function contents()
{
return $this->children(false);
}
/**
* Get the children of each element in the set of matched elements, optionally filtered by a selector.
*
* @param string|self|callable|\DOMNodeList|\DOMNode|false|null $selector expression that filters the set of matched elements
*
* @return self
*/
public function children($selector=null)
{
$result = $this->createChildInstance();
if (isset($this->document) && $this->length > 0) {
$all_nodes_children_of_root = true;
foreach ($this->nodes as $node) {
if (!($node->parentNode instanceof \DOMDocument)) {
$all_nodes_children_of_root = false;
}
}
if (!isset($this->root_instance) && $all_nodes_children_of_root) { // first instance direct access to children
$result->loadDomNodeList($this->document->childNodes);
} else {
foreach ($this->nodes as $node) {
if ($node->hasChildNodes()) {
$result->loadDomNodeList($node->childNodes);
}
}
}
if ($selector !== false) { // filter out text nodes
$filtered_elements = array();
foreach ($result->getElements() as $result_elm) {
$filtered_elements[] = $result_elm;
}
$result->nodes = $filtered_elements;
$result->length = \count($result->nodes);
}
if ($selector) {
$result = $result->filter($selector);
}
}
return $result;
}
/**
* Get the siblings of each element in the set of matched elements, optionally filtered by a selector.
*
* @param string|self|callable|\DOMNodeList|\DOMNode|null $selector expression that filters the set of matched elements
*
* @return self
*/
public function siblings($selector=null)
{
$result = $this->createChildInstance();
if (isset($this->document) && $this->length > 0) {
foreach ($this->nodes as $node) {
if ($node->parentNode) {
foreach ($node->parentNode->childNodes as $sibling) {
if ($sibling instanceof \DOMElement && !$sibling->isSameNode($node)) {
$result->addDomNode($sibling);
}
}
}
}
if ($selector) {
$result = $result->filter($selector);
}
}
return $result;
}
/**
* Get the parent of each element in the current set of matched elements, optionally filtered by a selector.
*
* @param string|self|callable|\DOMNodeList|\DOMNode|null $selector expression that filters the set of matched elements
*
* @return self
*/
public function parent($selector=null)
{
$result = $this->createChildInstance();
if (isset($this->document) && $this->length > 0) {
foreach ($this->nodes as $node) {
if ($node->parentNode) {
$result->addDomNode($node->parentNode);
}
}
if ($selector) {
$result = $result->filter($selector);
}
}
return $result;
}
/**
* For each element in the set, get the first element that matches the selector
* by testing the element itself and traversing up through its ancestors in the DOM tree.
*
* @param string|self|callable|\DOMNodeList|\DOMNode $selector selector expression to match elements against
*
* @return self
*/
public function closest($selector)
{
$result = $this->createChildInstance();
if (isset($this->document) && $this->length > 0) {
foreach ($this->nodes as $node) {
$current = $node;
while ($current instanceof \DOMElement) {
if (self::create($current)->is($selector)) {
$result->addDomNode($current);
break;
}
$current = $current->parentNode;
}
}
}
return $result;
}
/**
* Remove elements from the set of matched elements.
*
* @param string|self|callable|\DOMNodeList|\DOMNode $selector
*
* @return self
*/
public function not($selector)
{
$result = $this->createChildInstance();
if ($this->length > 0) {
if (!\is_string($selector) && \is_callable($selector)) {
foreach ($this->nodes as $index => $node) {
if (!$selector($node, $index)) {
$result->addDomNode($node);
}
}
} elseif ($selector === null) {
$result->addDomNodes($this->nodes);
} else {
$selection = self::create($this->document)->find($selector);
if ($selection->length > 0) {
foreach ($this->nodes as $node) {
$matched = false;
foreach ($selection as $result_node) {
if ($result_node->isSameNode($node)) {
$matched = true;
break 1;
}
}
if (!$matched) {
$result->addDomNode($node);
}
}
} else {
$result->addNodes($this->nodes);
}
}
}
return $result;
}
/**
* Added elements that match the selector.
*
* @param string|self|\DOMNodeList|\DOMNode $selector
* @param string|self|\DOMNodeList|\DOMNode|\DOMDocument $context
*
* @return self
*/
public function add($selector, $context=null)
{
$result = $this->createChildInstance();
$result->addDomNodes($this->nodes);
$selection = $this->getTargetResult($selector, $context);
foreach ($selection as $selection_node) {
if (!$result->is($selection_node)) {
if ($result->document === $selection_node->document) {
$new_node = $selection_node->get(0);
} else {
$new_node = $this->document->importNode($selection_node->get(0), true);
}
$result->addDomNode($new_node);
}
}
return $result;
}
/**
* Reduce the set of matched elements to those that match the selector.
*
* @param string|self|callable|\DOMNodeList|\DOMNode $selector
*
* @return self
*/
public function filter($selector)
{
$result = $this->createChildInstance();
if ($this->length > 0) {
if (!\is_string($selector) && \is_callable($selector)) {
foreach ($this->nodes as $index => $node) {
if ($selector($node, $index)) {
$result->addDomNode($node);
}
}
} elseif ($selector === null) {
$result->addDomNodes($this->nodes);
} else {
$selection = self::create($this->document)->find($selector);
foreach ($selection as $result_node) {
foreach ($this->nodes as $node) {
if ($result_node->isSameNode($node)) {
$result->addDomNode($node);
break 1;
}
}
}
}
}
return $result;
}
/**
* Create a deep copy of the set of matched elements (does not clone attached data).
*
* @return self
*/
public function clone()
{
$new_instance = self::create($this->getClonedNodes());
if (\is_bool($this->xml_mode)) {
$new_instance->xml_mode = $this->xml_mode;
}
if (isset($this->document) && $this->dom_xpath instanceof \DOMXPath) {
$new_instance->dom_xpath = $this->dom_xpath;
}
return $new_instance;
}
/**
* Get the position of the first element within the DOM, relative to its sibling elements.
* Or get the position of the first node in the result that matches the selector.
*
* @param string|self|callable|\DOMNodeList|\DOMNode $selector
*
* @return int $position
*/
public function index($selector=null)
{
if ($selector === null) {
if ($node = $this->getFirstElmNode()) {
$position = 0;
while ($node && ($node = $node->previousSibling)) {
if ($node instanceof \DOMElement) {
$position++;
} else {
break;
}
}
return $position;
}
} else {
foreach ($this as $key => $node) {
if ($node->is($selector)) {
return $key;
}
}
}
return -1;
}
/**
* Check if any node matches the selector.
*
* @param string|self|callable|\DOMNodeList|\DOMNode $selector
*
* @return bool
*/
public function is($selector)
{
if ($this->length > 0) {
if (!\is_string($selector) && \is_callable($selector)) {
foreach ($this->nodes as $index => $node) {
if ($selector($node, $index)) {
return true;
}
}
} else {
$selection = self::create($this->document)->find($selector);
foreach ($selection->nodes as $result_node) {
foreach ($this->nodes as $node) {
if ($result_node->isSameNode($node)) {
return true;
}
}
}
}
}
return false;
}
/**
* Reduce the set of matched elements to those that have a descendant that matches the selector.
*
* @param string|self|\DOMNodeList|\DOMNode $selector
*
* @return self
*/
public function has($selector)
{
$result = $this->createChildInstance();
if ($this->length > 0 && $selector !== null) {
foreach ($this as $node) {
if ($node->find($selector)->length > 0) {
$result->addDomNode($node->get(0));
}
}
}
return $result;
}
/**
* Reduce the set of matched elements to a subset specified by the offset and length (php like).
*
* @param integer $offset
* @param integer $length
*
* @return self
*/
public function slice($offset=0, $length=null)
{
$result = $this->createChildInstance();
$result->nodes = \array_slice($this->nodes, $offset, $length);
$result->length = \count($result->nodes);
return $result;
}
/**
* Reduce the set of matched elements to the one at the specified index.
*
* @param integer $index
*
* @return self
*/
public function eq($index)
{
return $this->slice($index, 1);
}
/**
* Returns DomQuery with first node.
*
* @param string|self|callable|\DOMNodeList|\DOMNode|null $selector expression that filters the set of matched elements
*
* @return self
*/
public function first($selector=null)
{
$result = $this[0];
if ($selector) {
$result = $result->filter($selector);
}
return $result;
}
/**
* Returns DomQuery with last node.
*
* @param string|self|callable|\DOMNodeList|\DOMNode|null $selector expression that filters the set of matched elements
*
* @return self
*/
public function last($selector=null)
{
$result = $this[$this->length-1];
if ($selector) {
$result = $result->filter($selector);
}
return $result;
}
/**
* Returns DomQuery with immediately following sibling of all nodes.
*
* @param string|self|callable|\DOMNodeList|\DOMNode|null $selector expression that filters the set of matched elements
*
* @return self
*/
public function next($selector=null)
{
$result = $this->createChildInstance();
if (isset($this->document) && $this->length > 0) {
foreach ($this->nodes as $node) {
if ($next = self::getNextElement($node)) {
$result->addDomNode($next);
}
}
if ($selector) {
$result = $result->filter($selector);
}
}
return $result;
}
/**
* Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.
*
* @param string|self|callable|\DOMNodeList|\DOMNode|null $selector expression that filters the set of matched elements
*
* @return self
*/
public function nextAll($selector=null)
{
$result = $this->createChildInstance();
if (isset($this->document) && $this->length > 0) {
foreach ($this->nodes as $node) {
$current = $node;
while ($next = self::getNextElement($current)) {
$result->addDomNode($next);
$current = $next;
}
}
if ($selector) {
$result = $result->filter($selector);
}
}
return $result;
}
/**
* Get all following siblings up to but not including the element which matched by the selector.
*
* @param string|self|callable|\DOMNodeList|\DOMNode|null $selector expression that filters the set of matched elements
*
* @return self
*/
public function nextUntil($selector=null)
{
$result = $this->createChildInstance();
if (isset($this->document) && $this->length > 0) {
foreach ($this->nodes as $node) {
$current = $node;
while ($next = self::getNextElement($current)) {
if ($selector) {
$current_result = $this->createChildInstance();
$current_result->addDomNode($next);
if ($current_result->is($selector)) {
break 2;
}
}
$result->addDomNode($next);
$current = $next;
}
}
}
return $result;
}
/**
* Returns DomQuery with immediately preceding sibling of all nodes.
*
* @param string|self|callable|\DOMNodeList|\DOMNode|null $selector expression that filters the set of matched elements
*
* @return self
*/
public function prev($selector=null)
{
$result = $this->createChildInstance();
if (isset($this->document) && $this->length > 0) {
foreach ($this->nodes as $node) { // get all previous sibling of all nodes
if ($prev = self::getPreviousElement($node)) {
$result->addDomNode($prev);
}
}
if ($selector) {
$result = $result->filter($selector);
}
}
return $result;
}
/**
* Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector.
*
* @param string|self|callable|\DOMNodeList|\DOMNode|null $selector expression that filters the set of matched elements
*
* @return self
*/
public function prevAll($selector=null)
{
$result = $this->createChildInstance();
if (isset($this->document) && $this->length > 0) {
foreach ($this->nodes as $node) {
$current = $node;
while ($prev = self::getPreviousElement($current)) {
$result->addDomNode($prev, true);
$current = $prev;
}
}
if ($selector) {
$result = $result->filter($selector);
}
}
return $result;
}
/**
* Get all previous siblings up to but not including the element is matched by the selector.
*
* @param string|self|callable|\DOMNodeList|\DOMNode|null $selector expression that filters the set of matched elements
*
* @return self
*/
public function prevUntil($selector=null)
{
$result = $this->createChildInstance();
if (isset($this->document) && $this->length > 0) {
foreach ($this->nodes as $node) {
$current = $node;
while ($prev = self::getPreviousElement($current)) {
if ($selector) {
$current_result = $this->createChildInstance();
$current_result->addDomNode($prev);
if ($current_result->is($selector)) {
break 2;
}
}
$result->addDomNode($prev);
$current = $prev;
}
}
}
return $result;
}
/**
* Remove the set of matched elements.
*
* @param string|self|callable|\DOMNodeList|\DOMNode|null $selector expression that
* filters the set of matched elements to be removed
*
* @return self
*/
public function remove($selector=null)
{
$result = $this;
if ($selector) {
$result = $result->filter($selector);
}
foreach ($result->nodes as $node) {
if ($node->parentNode) {
$node->parentNode->removeChild($node);
}
}
$result->nodes = array();
$result->length = 0;
return $result;
}
/**
* Import nodes from content and call import function to insert or append them.
*
* @param string|self|array $content
* @param callable $import_function
* @param bool $use_last_content_node if true then not clone, but directly use last content node if from same doc
*
* @return \DOMNode[] $imported_nodes
*/
private function importNodes($content, callable $import_function, bool $use_last_content_node=true)
{
$imported_nodes = [];
if (\is_array($content)) {
foreach ($content as $item) {
$imported_nodes = array_merge($imported_nodes, $this->importNodes($item, $import_function, $use_last_content_node));
}
return $imported_nodes;
}
if (\is_string($content) && strpos($content, "\n") !== false) {
$this->preserve_no_newlines = false;
if (isset($this->root_instance)) {
$this->root_instance->preserve_no_newlines = false;
}
}
if (!($content instanceof self)) {
$content = new self($content);
}
foreach ($this->nodes as $node_key => $node) {
foreach ($content->getNodes() as $content_node) {
$imported_node = null;
if ($content_node->ownerDocument === $node->ownerDocument) {
if ($use_last_content_node && ($node_key+1) === count($this->nodes)) {
$imported_node = $content_node;
} else {
$imported_node = $content_node->cloneNode(true);
}
} else {
$imported_node = $this->document->importNode($content_node, true);
| php | MIT | 4bc72c3da2e82eb7c08fa30582f71e91843423df | 2026-01-05T05:09:18.310463Z | true |
Rct567/DomQuery | https://github.com/Rct567/DomQuery/blob/4bc72c3da2e82eb7c08fa30582f71e91843423df/src/Rct567/DomQuery/CssToXpath.php | src/Rct567/DomQuery/CssToXpath.php | <?php
namespace Rct567\DomQuery;
/**
* Class CssToXpath
*/
class CssToXpath
{
/**
* Css selector to xpath cache
*
* @var array<string, string>
*/
private static $xpath_cache = array();
/**
* Transform CSS selector expression to XPath
*
* @param string $path css selector expression
*
* @return string xpath expression
*/
public static function transform(string $path)
{
if (isset(self::$xpath_cache[$path])) {
return self::$xpath_cache[$path];
}
// handle css grouping query (multiple queries combined with a comma)
$paths = preg_split('/\,(?![^\[]*]|[^()]*\))/', $path);
if (count($paths) > 1) {
$expressions = array();
foreach ($paths as $single_path) {
$xpath = self::transform(trim($single_path));
$expressions[] = $xpath;
}
return implode('|', $expressions);
}
// create tokens and analyze to create segments
$tokens = preg_split('/\s+(?![^\[]*]|[^()]*\))/', $path);
$segments = array();
foreach ($tokens as $key => $token) {
if ($segment = self::getSegmentFromToken($token, $key, $tokens)) {
$segments[] = $segment;
}
}
// use segments to create array with transformed tokens
$new_path_tokens = self::transformCssSegments($segments);
// result tokens to xpath
$xpath_result = implode('', $new_path_tokens);
self::$xpath_cache[$path] = $xpath_result;
return $xpath_result;
}
/**
* Get segment data from token (css selector delimited by space and commas)
*
* @param string $token
* @param integer $key
* @param string[] $tokens
*
* @return object|false $segment
*/
private static function getSegmentFromToken($token, $key, array $tokens)
{
$relation_tokens = array('>', '~', '+');
if (\in_array($token, $relation_tokens, true)) { // not a segment
return false;
}
$segment = (object) array(
'selector' => '',
'relation_token' => false,
'attribute_filters' => array(),
'pseudo_filters' => array()
);
if (isset($tokens[$key-1]) && \in_array($tokens[$key-1], $relation_tokens, true)) { // get relationship token
$segment->relation_token = $tokens[$key-1];
}
if (ctype_alpha($token)) { // simple element selector
$segment->selector = $token;
return $segment;
}
$char_tmp_replaced = false;
if (strpos($token, '\\') !== false) {
$token = preg_replace_callback( // temporary replace escaped characters
'#(\\\\)(.{1})#',
function ($matches) {
return 'ESCAPED'. \ord($matches[2]);
},
$token
);
$char_tmp_replaced = true;
}
$segment->selector = $token;
while (preg_match('/(.*)\:(not|contains|has|nth\-child)\((.+)\)$/i', $segment->selector, $matches)) { // pseudo selector
$segment->selector = $matches[1];
$segment->pseudo_filters[] = $matches[2].'('.$matches[3].')';
}
while (preg_match('/(.*)\:([a-z][a-z\-]+)$/i', $segment->selector, $matches)) { // pseudo selector
$segment->selector = $matches[1];
$segment->pseudo_filters[] = $matches[2];
}
while (preg_match('/(.*)\[([^]]+)\]$/', $segment->selector, $matches)) { // attribute selector
$segment->selector = $matches[1];
$segment->attribute_filters[] = $matches[2];
}
while (preg_match('/(.*)\.([^\.\#]+)$/i', $segment->selector, $matches)) { // class selector
$segment->selector = $matches[1];
$segment->attribute_filters[] = 'class~="'.$matches[2].'"';
}
while (preg_match('/(.*)\#([^\.\#]+)$/i', $segment->selector, $matches)) { // id selector
$segment->selector = $matches[1];
$segment->attribute_filters[] = 'id="'.$matches[2].'"';
}
if ($char_tmp_replaced) { // restore temporary replaced characters
$set_escape_back = function (string $str) {
return preg_replace_callback(
'#(ESCAPED)([0-9]{1,3})#',
function ($matches) {
return \chr(intval($matches[2]));
},
$str
);
};
$segment->selector = $set_escape_back($segment->selector);
$segment->attribute_filters = array_map($set_escape_back, $segment->attribute_filters);
}
return $segment;
}
/**
* Transform css segments to xpath
*
* @param array<int, object> $segments
*
* @return string[] $new_path_tokens
*/
private static function transformCssSegments(array $segments)
{
$new_path_tokens = array();
foreach ($segments as $num => $segment) {
if ($segment->relation_token === '>') {
$new_path_tokens[] = '/';
} elseif ($segment->relation_token === '~' || $segment->relation_token === '+') {
$new_path_tokens[] = '/following-sibling::';
} else {
$new_path_tokens[] = '//';
}
if ($segment->selector !== '') {
$new_path_tokens[] = $segment->selector; // specific tagname
} else {
$new_path_tokens[] = '*'; // any tagname
}
if ($segment->relation_token === '+' && isset($segments[$num-1])) { // add adjacent filter
$prev_selector = implode('', self::transformCssSegments([$segments[$num-1]]));
$new_path_tokens[] = '[preceding-sibling::*[1][self::'.ltrim($prev_selector, '/').']]';
}
foreach (array_reverse($segment->attribute_filters) as $attr) {
$new_path_tokens[] = self::transformAttrSelector($attr);
}
foreach (array_reverse($segment->pseudo_filters) as $attr) {
$new_path_tokens[] = self::transformCssPseudoSelector($attr, $new_path_tokens);
}
}
return $new_path_tokens;
}
/**
* Transform 'css pseudo selector' expression to xpath expression
*
* @param string $expression
* @param string[] $new_path_tokens
*
* @return string transformed expression (xpath)
* @throws \Exception
*/
private static function transformCssPseudoSelector($expression, array &$new_path_tokens)
{
if (preg_match('|not\((.+)\)|i', $expression, $matches)) {
$parts = explode(',', $matches[1]);
foreach ($parts as &$part) {
$part = trim($part);
$part = 'self::'.ltrim(self::transform($part), '/');
}
$not_selector = implode(' or ', $parts);
return '[not('.$not_selector.')]';
} elseif (preg_match('|nth\-child\((.+)\)|i', $expression, $matches)) {
return '[position()='.$matches[1].']';
} elseif (preg_match('|contains\((.+)\)|i', $expression, $matches)) {
return '[text()[contains(.,\''.$matches[1].'\')]]'; // contain the specified text
} elseif (preg_match('|has\((.+)\)|i', $expression, $matches)) {
if (strpos($matches[1], '> ') === 0) {
return '[child::' . ltrim(self::transform($matches[1]), '/') .']';
} else {
return '[descendant::' . ltrim(self::transform($matches[1]), '/') .']';
}
} elseif ($expression === 'first' || $expression === 'last') { // new path inside selection
array_unshift($new_path_tokens, '(');
$new_path_tokens[] = ')';
}
// static replacement
$pseudo_class_selectors = array(
'disabled' => '[@disabled]',
'first-child' => '[not(preceding-sibling::*)]',
'last-child' => '[not(following-sibling::*)]',
'only-child' => '[not(preceding-sibling::*) and not(following-sibling::*)]',
'empty' => '[count(*) = 0 and string-length() = 0]',
'not-empty' => '[count(*) > 0 or string-length() > 0]',
'parent' => '[count(*) > 0]',
'header' => '[self::h1 or self::h2 or self::h3 or self::h5 or self::h5 or self::h6]',
'odd' => '[position() mod 2 = 0]',
'even' => '[position() mod 2 = 1]',
'first' => '[1]',
'last' => '[last()]',
'root' => '[not(parent::*)]'
);
if (!isset($pseudo_class_selectors[$expression])) {
throw new \Exception('Pseudo class '.$expression.' unknown');
}
return $pseudo_class_selectors[$expression];
}
/**
* Transform 'css attribute selector' expression to xpath expression
*
* @param string $expression
*
* @return string transformed expression (xpath)
*/
private static function transformAttrSelector($expression)
{
if (preg_match('|^([a-z0-9_]{1}[a-z0-9_-]*)(([\!\*\^\$\~\|]{0,1})=)?'.
'(?:[\'"]*)?([^\'"]+)?(?:[\'"]*)?$|i', $expression, $matches)) {
if (!isset($matches[3])) { // attribute without value
return "[@" . $matches[1] . "]";
} elseif ($matches[3] === '') { // arbitrary attribute strict value equality
return '[@' . strtolower($matches[1]) . "='" . $matches[4] . "']";
} elseif ($matches[3] === '!') { // arbitrary attribute negation strict value
return '[@' . strtolower($matches[1]) . "!='" . $matches[4] . "']";
} elseif ($matches[3] === '~') { // arbitrary attribute value contains full word
return "[contains(concat(' ', normalize-space(@" . strtolower($matches[1]) . "), ' '), ' ". $matches[4] . " ')]";
} elseif ($matches[3] === '*') { // arbitrary attribute value contains specified content
return "[contains(@" . strtolower($matches[1]) . ", '" . $matches[4] . "')]";
} elseif ($matches[3] === '^') { // attribute value starts with specified content
return "[starts-with(@" . strtolower($matches[1]) . ", '" . $matches[4] . "')]";
} elseif ($matches[3] === '$') { // attribute value ends with specified content
return "[@".$matches[1]." and substring(@".$matches[1].", string-length(@".$matches[1].")-".
(\strlen($matches[4])-1).") = '".$matches[4]."']";
} elseif ($matches[3] === '|') { // attribute has prefix selector
return '[@' . strtolower($matches[1]) . "='" . $matches[4] . "' or starts-with(@".
strtolower($matches[1]) . ", '" . $matches[4].'-' . "')]";
}
}
throw new \Exception('Attribute selector is malformed or contains unsupported characters.');
}
}
| php | MIT | 4bc72c3da2e82eb7c08fa30582f71e91843423df | 2026-01-05T05:09:18.310463Z | false |
Rct567/DomQuery | https://github.com/Rct567/DomQuery/blob/4bc72c3da2e82eb7c08fa30582f71e91843423df/tests/Rct567/DomQuery/Tests/DomQueryManipulationTest.php | tests/Rct567/DomQuery/Tests/DomQueryManipulationTest.php | <?php
namespace Rct567\DomQuery\Tests;
use Rct567\DomQuery\DomQuery;
class DomQueryManipulationTest extends \PHPUnit\Framework\TestCase
{
/*
* Test wrap all
*/
public function testWrapAll()
{
$dom = DomQuery::create('<html><div class="container">'.
'<div class="inner">Hello</div> <div class="inner">Goodbye</div>'.
'</div></html>');
$dom->find('.inner')->wrapAll('<div class="new" />');
$this->assertEquals('<html><div class="container">'.
'<div class="new"><div class="inner">Hello</div><div class="inner">Goodbye</div></div>'.
' </div></html>', (string) $dom);
}
/*
* Test wrap all with non wrapping sibling
*/
public function testWrapAllWithNonWrappingSibling()
{
$dom = DomQuery::create('<html><div class="container">'.
'<div class="inner">Hello</div> <div class="nope">Goodbye</div>'.
'</div></html>');
$dom->find('.inner')->wrapAll('<div class="new" />');
$this->assertEquals('<html><div class="container">'.
'<div class="new"><div class="inner">Hello</div></div> <div class="nope">Goodbye</div>'.
'</div></html>', (string) $dom);
}
/*
* Test wrap all with multiple elements wrapper
*/
public function testWrapAllWithMultipleElementsWrapper()
{
$dom = DomQuery::create('<html><div class="container">'.
'<div class="inner">Hello</div> <div class="inner">Goodbye</div>'.
'</div></html>');
$dom->find('.inner')->wrapAll('<div class="new"><x></x></div>');
$this->assertEquals('<html><div class="container">'.
'<div class="new"><x><div class="inner">Hello</div><div class="inner">Goodbye</div></x></div>'.
' </div></html>', (string) $dom);
}
/*
* Test wrap inner
*/
public function testInnerWrap()
{
$dom = DomQuery::create('<p><a>Hello</a></p>');
$dom->find('a')->wrapInner('<div></div>');
$this->assertEquals("<p><a><div>Hello</div></a></p>", (string) $dom);
}
/*
* Test wrap
*/
public function testWrap()
{
$dom = DomQuery::create('<p><a>Hello</a></p>');
$dom->find('a')->wrap('<div></div>');
$this->assertEquals("<p><div><a>Hello</a></div></p>", (string) $dom);
}
/*
* Test wrap on element with sibling
*/
public function testWrapOnElementWithSibling()
{
$dom = DomQuery::create('<p> <span>Hi</span> <a>Hello</a> </p>');
$dom->find('a')->wrap('<x></x>');
$this->assertEquals("<p> <span>Hi</span> <x><a>Hello</a></x> </p>", (string) $dom);
}
/*
* Test wrap on multiple elements
*/
public function testWrapOnMultipleElements()
{
$dom = DomQuery::create('<p> <span>Hi</span> <a>Hello</a> </p>');
$dom->find('a, span')->wrap('<x></x>');
$this->assertEquals("<p> <x><span>Hi</span></x> <x><a>Hello</a></x> </p>", (string) $dom);
}
/*
* Test wrap where wrapper has multiple elements
*/
public function testWrapWithMultipleElementsWrapper()
{
$dom = DomQuery::create('<p><a>Hello</a></p>');
$dom->find('a')->wrap('<div><x></x></div>');
$this->assertEquals("<p><div><x><a>Hello</a></x></div></p>", (string) $dom);
}
/*
* Test remove
*/
public function testRemove()
{
$dom = DomQuery::create('<div><a title="hello">Some text</a><a>B</a><span>C</span></div>');
$dom->find('a')->remove();
$this->assertEquals("<div><span>C</span></div>", (string) $dom);
}
/*
* Test remove with selector filter
*/
public function testRemoveWithSelectorFilter()
{
$dom = DomQuery::create('<div><a title="hello">Some text</a><a>B</a><span>C</span></div>');
$dom->find('a')->remove('[title]');
$this->assertEquals("<div><a>B</a><span>C</span></div>", (string) $dom);
}
/*
* Test change text
*/
public function testMultipleNodesTextChange()
{
$dom = DomQuery::create('<div><a title="hello">Some text</a><a>B</a><span>C</span></div>');
$dom->find('a')->text('Changed text');
$this->assertEquals("<div><a title=\"hello\">Changed text</a><a>Changed text</a><span>C</span></div>", (string) $dom);
}
/*
* Test append html string
*/
public function testAppend()
{
$dom = new DomQuery('<p id="target">1</p> <p></p> <b></b> <a>2</a>');
$dom->find('p#target')->append('<span></span>');
$this->assertEquals('<p id="target">1<span></span></p><p></p><b></b><a>2</a>', (string) $dom);
}
/*
* Test append multiple content
*/
public function testAppendMulti()
{
$dom = new DomQuery('<p id="target"><a></a></p>');
$dom->find('p#target')->append('<b></b> ', '<c></c>');
$this->assertEquals('<p id="target"><a></a><b></b><c></c></p>', (string) $dom);
}
/*
* Test append DomQuery instance with multiple targets
*/
public function testAppendDomQueryInstance()
{
$dom = new DomQuery('<p class="target"></p><p></p><p class="target"></p>');
$dom->find('p.target')->append(DomQuery::create('<i>X</i>'));
$this->assertEquals('<p class="target"><i>X</i></p><p></p><p class="target"><i>X</i></p>', (string) $dom);
$this->assertEquals('X', $dom->find('i')->text());
}
/*
* Test append, content getting moved
*/
public function testAppendClone()
{
$dom = new DomQuery('<div> <p id="target"></p><p><b id="content">XX</b></p> </div>');
$dom->find('p#target')->append($dom->find('b#content'));
$this->assertEquals('<div> <p id="target"><b id="content">XX</b></p><p></p> </div>', (string) $dom);
}
/*
* Test append with multiple targets, first content should be cloned, second/last should move it
*/
public function testAppendCloneMultipleTargets()
{
$dom = new DomQuery('<div> <p class="target"></p><p class="target"></p><p><b id="content">XX</b></p> </div>');
$dom->find('p.target')->append($dom->find('b#content'));
$this->assertEquals('<div> <p class="target"><b id="content">XX</b></p><p class="target"><b id="content">XX</b></p><p></p> </div>', (string) $dom);
}
/*
* Test append to
*/
public function testAppendTo()
{
$dom = new DomQuery('<div> <span>A</span><span>B</span> <p id="target"></p> </div>');
$dom->find('span')->appendTo('p#target');
$this->assertEquals('<div> <p id="target"><span>A</span><span>B</span></p> </div>', (string) $dom);
}
/*
* Test append to (other DomQuery)
*/
public function testAppendToOther()
{
$dom = DomQuery::create('<div>P</div>');
DomQuery::create('<span>Hello</span>')->appendTo($dom);
$this->assertEquals('<div>P<span>Hello</span></div>', (string) $dom);
}
/*
* Test append to moves content,
*/
public function testAppendToMoved()
{
$dom = new DomQuery('<div> <span>X</span> <p id="target"></p> </div>');
$dom->find('span')->appendTo('p#target');
$this->assertEquals('<div> <p id="target"><span>X</span></p> </div>', (string) $dom);
}
/*
* Test append to with clones
*/
public function testAppendToCloned()
{
$dom = new DomQuery('<div> <span>X</span> <p id="target"></p> </div>');
$dom->find('span')->clone()->appendTo('p#target');
$this->assertEquals('<div> <span>X</span> <p id="target"><span>X</span></p> </div>', (string) $dom);
}
/*
* Test return value of appendTo by using it again
*/
public function testAppendToReturnValue()
{
$dom = new DomQuery('<div class="container"></div>');
$span = DomQuery::create('<span id="el1">')->appendTo($dom);
$this->assertEquals('<span id="el1"></span>', (string) $span);
DomQuery::create('<a></a>')->appendTo($span);
$this->assertEquals('<div class="container"><span id="el1"><a></a></span></div>', (string) $dom);
}
/*
* Test return value of prependTo by using it again
*/
public function testPrependToReturnValue()
{
$dom = new DomQuery('<div class="container"></div>');
$span = DomQuery::create('<span id="el1">')->prependTo($dom);
$this->assertEquals('<span id="el1"></span>', (string) $span);
DomQuery::create('<a></a>')->prependTo($span);
$this->assertEquals('<div class="container"><span id="el1"><a></a></span></div>', (string) $dom);
}
/*
* Test prepend html
*/
public function testPrepend()
{
$dom = new DomQuery('<a>X</a>');
$dom->find('a')->prepend('<span></span>', '<i></i>');
$this->assertEquals('<a><i></i><span></span>X</a>', (string) $dom);
$this->assertEquals(1, $dom->find('span')->length);
}
/*
* Test prepend multiple content
*/
public function testPrependMulti()
{
$dom = new DomQuery('<p><c></c></p>');
$dom->find('p:last')->prepend('<b></b>', '<a></a>');
$this->assertEquals('<p><a></a><b></b><c></c></p>', (string) $dom);
}
/*
* Test prepend to
*/
public function testPrependTo()
{
$dom = new DomQuery('<div> <span>X</span> <div id="target"></div> </div>');
$dom->find('span')->prependTo('#target');
$this->assertEquals('<div> <div id="target"><span>X</span></div> </div>', (string) $dom);
}
/*
* Test prepend to (other DomQuery)
*/
public function testPrependToOther()
{
$dom = DomQuery::create('<div>P</div>');
DomQuery::create('<span>Hello</span>')->prependTo($dom);
$this->assertEquals('<div><span>Hello</span>P</div>', (string) $dom);
}
/*
* Test insert before
*/
public function testBefore()
{
$dom = new DomQuery('<div> <a>X</a> </div>');
$dom->find('a')->before('<span></span>');
$this->assertEquals('<div> <span></span><a>X</a> </div>', (string) $dom);
$this->assertEquals(1, $dom->find('span')->length);
}
/*
* Test insert after
*/
public function testAfter()
{
$dom = new DomQuery('<div> <a>X</a> </div>');
$dom->find('a')->after('<span></span>');
$this->assertEquals('<div> <a>X</a><span></span> </div>', (string) $dom);
$this->assertEquals(1, $dom->find('span')->length);
}
/*
* Test insert after with nl
* @note nl is detected in child instance and set back to root
*/
public function testAfterWithWhiteSpaces()
{
$dom = new DomQuery("<div> <a>X</a> </div>");
$dom->find('div')->find('a')->after("<span>\n</span>");
$this->assertEquals("<div> <a>X</a><span>\n</span> </div>", (string) $dom);
$this->assertFalse($dom->preserve_no_newlines);
}
/*
* Test get html
*/
public function testGetHtml()
{
$dom = new DomQuery('<p> <a>M<i selected>A</i></a> <span></span></p>');
$this->assertEquals('M<i selected>A</i>', $dom->find('a')->html()); // inner
$this->assertEquals('<a>M<i selected>A</i></a>', $dom->find('a')->prop('outerHTML')); // outer
$this->assertEquals('<a>M<i selected>A</i></a>', $dom->find('a')->outerHTML); // outer
$this->assertEquals('A', $dom->find('a i')->html());
}
/*
* Test get html in xml mode
*/
public function testGetHtmlInXmlMode()
{
$dom = new DomQuery('<p> <a>M<i selected>A</i></a> <span></span> </p>');
$dom->xml_mode = true;
$this->assertEquals('M<i selected="selected">A</i>', $dom->find('a')->html()); // inner
$this->assertEquals('<a>M<i selected="selected">A</i></a>', $dom->find('a')->prop('outerHTML')); // outer
$this->assertEquals('<a>M<i selected="selected">A</i></a>', $dom->find('a')->outerHTML); // outer
$this->assertEquals('A', $dom->find('a i')->html());
}
/*
* Test set html
*/
public function testSetHtml()
{
$dom = new DomQuery('<p> <a>M<i>A</i></a> <span></span> </p>');
$dom->find('a')->html('<i>x</i>');
$this->assertEquals('<p> <a><i>x</i></a> <span></span> </p>', (string) $dom);
}
/*
* Test set html with new line content
*/
public function testSetHtmlWithNewline()
{
$dom = new DomQuery('<p> <a>M<i>A</i></a> <span></span> </p>');
$dom->find('a')->html("<i>x\n</i>");
$this->assertEquals("<p> <a><i>x\n</i></a> <span></span> </p>", (string) $dom);
}
/*
* Test get css
*/
public function testGetCss()
{
$dom = new DomQuery('<p><a style="color: green;"></a></p>');
$this->assertEquals('green', $dom->find('a')->css('color'));
$this->assertEquals(null, $dom->find('a')->css('margin-top'));
}
/*
* Test get css from element with multiple css values
*/
public function testGetCssFromMulti()
{
$dom = new DomQuery('<p><a style="color: green;margin-top:2px"></a></p>');
$this->assertEquals('green', $dom->find('a')->css('color'));
$this->assertEquals('2px', $dom->find('a')->css('margin-top'));
$this->assertEquals(null, $dom->find('p')->css('margin-top'));
}
/*
* Test test css
*/
public function testSetNewCss()
{
$dom = new DomQuery('<p><a></a></p>');
$dom->find('a')->css('color', 'green');
$this->assertEquals('<p><a style="color: green;"></a></p>', (string) $dom);
}
/*
* Test add css to existing inline css
*/
public function testSetExistingCss()
{
$dom = new DomQuery('<p><a style="margin-top: 5px;"></a></p>');
$dom->find('a')->css('color', 'green');
$this->assertEquals('<p><a style="margin-top: 5px;color: green;"></a></p>', (string) $dom);
}
/*
* Test overwrite existing inline css property
*/
public function testOverwriteCss()
{
$dom = new DomQuery('<p><a style="color: red;"></a></p>');
$dom->find('a')->css('color', 'green');
$this->assertEquals('<p><a style="color: green;"></a></p>', (string) $dom);
}
/*
* Test replace with
*/
public function testReplaceWith()
{
$dom = new DomQuery('<div> <a class="a"></a> <a class="b"></a> <a class="c"></a> </div>');
$removed = $dom->find('.b')->replaceWith('<h2>Hello</h2>');
$this->assertEquals('<a class="b"></a>', (string) $removed);
$this->assertEquals('<div> <a class="a"></a> <h2>Hello</h2> <a class="c"></a> </div>', (string) $dom);
}
/*
* Test replace with, using DomQuery as new content
*/
public function testReplaceWithSelection()
{
$dom = new DomQuery('<div> <a class="a"></a> <a class="b"></a> <a class="c"></a> </div>');
$removed = $dom->find('.c')->replaceWith($dom->find('.a'));
$this->assertEquals('<a class="c"></a>', (string) $removed);
$this->assertEquals('<div> <a class="b"></a> <a class="a"></a> </div>', (string) $dom); // moved, not cloned
}
}
| php | MIT | 4bc72c3da2e82eb7c08fa30582f71e91843423df | 2026-01-05T05:09:18.310463Z | false |
Rct567/DomQuery | https://github.com/Rct567/DomQuery/blob/4bc72c3da2e82eb7c08fa30582f71e91843423df/tests/Rct567/DomQuery/Tests/DomQueryTraversingMiscellaneousTest.php | tests/Rct567/DomQuery/Tests/DomQueryTraversingMiscellaneousTest.php | <?php
namespace Rct567\DomQuery\Tests;
use Rct567\DomQuery\DomQuery;
class DomQueryTraversingMiscellaneousTest extends \PHPUnit\Framework\TestCase
{
/*
* Test add using selector
*/
public function testAddWithSelector()
{
$dom = new DomQuery('<a>1</a><span>2</span>');
$dom->find('a')->add('span')->addClass('yep');
$this->assertEquals('<a class="yep">1</a><span class="yep">2</span>', (string) $dom);
}
/*
* Test add using html fragment
*/
public function testAddWithHtml()
{
$dom = new DomQuery('<a>1</a>');
$new_dom = $dom->find('a')->add('<span>2</span>');
$this->assertEquals('<a>1</a>', (string) $dom);
$this->assertEquals('<a>1</a><span>2</span>', (string) $new_dom);
}
/*
* Test add using selector with html fragment as context
*/
public function testAddWithHtmlContext()
{
$dom = new DomQuery('<a>1</a><p>nope</p>');
$new_dom = $dom->find('a')->add('span', '<span>2</span><p>nope</p>');
$this->assertEquals('<a>1</a><p>nope</p>', (string) $dom);
$this->assertEquals('<a>1</a><span>2</span>', (string) $new_dom);
}
/*
* Test addBack().
*/
public function testAddBack()
{
$dom = new DomQuery('
<div>
<span id="first">1</span>
<span>2</span>
<span>3</span>
</div>');
$result = $dom->find('#first')->next();
$this->assertEquals('<span>2</span>', (string) $result); // only next to the first
$this->assertEquals('<span id="first">1</span><span>2</span>', (string) $result->addBack()); // prepend the first with addBack()
}
}
| php | MIT | 4bc72c3da2e82eb7c08fa30582f71e91843423df | 2026-01-05T05:09:18.310463Z | false |
Rct567/DomQuery | https://github.com/Rct567/DomQuery/blob/4bc72c3da2e82eb7c08fa30582f71e91843423df/tests/Rct567/DomQuery/Tests/DomQuerySelectorsTest.php | tests/Rct567/DomQuery/Tests/DomQuerySelectorsTest.php | <?php
namespace Rct567\DomQuery\Tests;
use Rct567\DomQuery\DomQuery;
use Rct567\DomQuery\CssToXpath;
class DomQuerySelectorsTest extends \PHPUnit\Framework\TestCase
{
/*
* Test css to xpath conversion
*/
public function testCssToXpath()
{
$css_to_xpath = array(
'a' => '//a',
'*' => '//*',
'* > a' => '//*/a',
'#someid' => '//*[@id=\'someid\']',
'p#someid' => '//p[@id=\'someid\']',
'#some\\.id' => '//*[@id=\'some.id\']',
'#someid.s-class' => '//*[@id=\'someid\'][contains(concat(\' \', normalize-space(@class), \' \'), \' s-class \')]',
'#id[_]' => '//*[@id=\'id\'][@_]',
'p a' => '//p//a',
'div, span' => '//div|//span',
'a[href]' => '//a[@href]',
'a[href][rel]' => '//a[@href][@rel]',
'a[href="html"]' => '//a[@href=\'html\']',
'a[href!="html"]' => '//a[@href!=\'html\']',
'a[href*=\'html\']' => '//a[contains(@href, \'html\')]',
'[href*=\'html\']' => '//*[contains(@href, \'html\')]',
'[href^=\'html\']' => '//*[starts-with(@href, \'html\')]',
'meta[http-equiv^="Content"]' => '//meta[starts-with(@http-equiv, \'Content\')]',
'meta[http-equiv^=Content]' => '//meta[starts-with(@http-equiv, \'Content\')]',
'[href$=\'html\']' => '//*[@href and substring(@href, string-length(@href)-3) = \'html\']',
'[href~=\'html\']' => '//*[contains(concat(\' \', normalize-space(@href), \' \'), \' html \')]',
'[href|=\'html\']' => '//*[@href=\'html\' or starts-with(@href, \'html-\')]',
'[data-id="e1eaziw "]' => '//*[@data-id=\'e1eaziw \']',
'> a' => '/a',
'p > a' => '//p/a',
'p > a[href]' => '//p/a[@href]',
'p a[href]' => '//p//a[@href]',
':disabled' => '//*[@disabled]',
'div :header' => '//div//*[self::h1 or self::h2 or self::h3 or self::h5 or self::h5 or self::h6]',
':odd' => '//*[position() mod 2 = 0]',
'.h' => '//*[contains(concat(\' \', normalize-space(@class), \' \'), \' h \')]',
'.a, .b' => '//*[contains(concat(\' \', normalize-space(@class), \' \'), \' a \')]|//*[contains(concat(\' \', normalize-space(@class), \' \'), \' b \')]',
'.πΎ-_πΎ' => '//*[contains(concat(\' \', normalize-space(@class), \' \'), \' πΎ-_πΎ \')]',
'.hidden' => '//*[contains(concat(\' \', normalize-space(@class), \' \'), \' hidden \')]',
'.hidden-something' => '//*[contains(concat(\' \', normalize-space(@class), \' \'), \' hidden-something \')]',
'a.hidden[href]' => '//a[contains(concat(\' \', normalize-space(@class), \' \'), \' hidden \')][@href]',
'a[href] > .hidden' => '//a[@href]/*[contains(concat(\' \', normalize-space(@class), \' \'), \' hidden \')]',
'a:not(b[co-ol])' => '//a[not(self::b[@co-ol])]',
'a:not(b,c)' => '//a[not(self::b or self::c)]',
'a:not(.cool)' => '//a[not(self::*[contains(concat(\' \', normalize-space(@class), \' \'), \' cool \')])]',
'a:contains(txt)' => '//a[text()[contains(.,\'txt\')]]',
'h1 ~ ul' => '//h1/following-sibling::ul',
'h1 + ul' => '//h1/following-sibling::ul[preceding-sibling::*[1][self::h1]]',
'h1 ~ #id' => '//h1/following-sibling::*[@id=\'id\']',
'p > a:has(> a)' => '//p/a[child::a]',
'p > a:has(b > a)' => '//p/a[descendant::b/a]',
'p > a:has(a)' => '//p/a[descendant::a]',
'a:has(b)' => '//a[descendant::b]',
'a:first-child:first' => '(//a[not(preceding-sibling::*)])[1]',
'ul > li:nth-child(2)' => '//ul/li[position()=2]',
'div > a:first' => '(//div/a)[1]',
':first' => '(//*)[1]'
);
foreach ($css_to_xpath as $css => $expected_xpath) {
$this->assertEquals($expected_xpath, CssToXpath::transform($css), $css);
}
}
/*
* Test select by tagname selector
*/
public function testElementTagnameSelector()
{
$dom = new DomQuery('<a>1</a><b>2</b><i>3</i>');
$this->assertEquals('2', $dom->find('b')->text());
}
/*
* Test select by tagname selector with xml
*/
public function testElementTagnameSelectorWithXml()
{
$dom = new DomQuery('<?xml version="1.0" encoding="UTF-8"?><root>'
.'<link>Hi</link><b:link>Hi2</b:link></root>');
$this->assertEquals('Hi', $dom->find('link')->text());
$this->assertEquals(1, $dom->find('link')->length);
}
/*
* Test select by tagname selector with xml name space
*/
public function testElementTagnameSelectorWithXmlNameSpace()
{
$dom = new DomQuery('<?xml version="1.0" encoding="UTF-8"?>'
.'<root xmlns:h="http://www.w3.org/TR/html4/" xmlns:f="https://www.w3schools.com/furniture">'
.'<f:link>Hi</f:link><b:link>Hi2</b:link><h:link>Hi3</h:link></root>');
$this->assertEquals('Hi', $dom->find('f\\:link')->text());
$this->assertEquals(1, $dom->find('f\\:link')->length);
$this->assertEquals('Hi3', $dom->find('h\\:link')->text());
}
/*
* Test wildcard / all selector
*/
public function testWildcardSelector()
{
$dom = new DomQuery('<a>1</a><b>2</b>');
$this->assertEquals(2, $dom->find('*')->length);
}
/*
* Test children selector
*/
public function testSelectChildrenSelector()
{
$dom = new DomQuery('<div><a>1</a><b>2</b></div><a>3</a>');
$this->assertEquals('1', $dom->find('div > a')->text());
$this->assertEquals(1, $dom->find('div > a')->length);
}
/*
* Test id selector
*/
public function testIdSelector()
{
$dom = new DomQuery('<div><a>1</a><b>2</b></div><a id="here">3</a>');
$this->assertEquals('3', $dom->find('#here')->text());
$this->assertEquals(1, $dom->find('#here')->length);
}
/*
* Test emoji as id selector
*/
public function testEmojiIdSelector()
{
$dom = new DomQuery('<div><a>1</a><b id="π">2</b></div><a >3</a>');
$this->assertEquals('2', $dom->find('#π')->text());
$this->assertEquals(1, $dom->find('#π')->length);
}
/*
* Test id selector with meta character
*/
public function testIdSelectorWithMetaCharacter()
{
$dom = new DomQuery('<div><a>1</a><b>2</b></div><a id="here.here">3</a>');
$this->assertEquals('3', $dom->find('#here\\.here')->text());
}
/*
* Test descendant selector
*/
public function testDescendantSelector()
{
$dom = new DomQuery('<div><a>1</a><b>2</b></div><a id="here">3</a><p><a>4</a></p>');
$this->assertEquals('2', $dom->find('div > b')->text());
$this->assertEquals(1, $dom->find('div > b')->length);
$this->assertEquals(0, $dom->find('a > b')->length);
$this->assertEquals(1, $dom->find('> a')->length);
$this->assertEquals(2, $dom->find('* > a')->length);
}
/*
* Test next adjacent selector
*/
public function testNextAdjacentSelector()
{
$dom = new DomQuery('<a>x</a><b>a</b><a>1</a><a>2</a><a>3</a>');
$this->assertEquals(1, $dom->find('b + a')->length);
$this->assertEquals('1', $dom->find('b + a')->text());
$this->assertEquals(1, $dom->find('a + b')->length);
$this->assertEquals('2', $dom->find('a + a')->text());
$this->assertEquals(2, $dom->find('a + a')->length);
}
/*
* Test next adjacent selector using class
*/
public function testNextAdjacentSelectorUsingClass()
{
$dom = new DomQuery('<a class="app">x</a><b>a</b><a class="app">1</a><a class="app">2</a><a class="app">3</a>');
$this->assertEquals('2', $dom->find('.app + a.app')->text());
$this->assertEquals('2', $dom->find('a + .app')->text());
$this->assertEquals('3', $dom->find('a + .app')->last()->text());
$this->assertEquals(2, $dom->find('.app + .app')->length);
$this->assertEquals(2, $dom->find('a.app + a.app')->length);
}
/*
* Test next siblings selector
*/
public function testNextSiblingsSelector()
{
$dom = new DomQuery('<b>a</b><a>1</a><a>2</a><a>3</a>');
$this->assertEquals(3, $dom->find('b ~ a')->length);
$this->assertEquals('3', $dom->find('b ~ a')->last()->text());
$this->assertEquals(0, $dom->find('a ~ b')->length);
$this->assertEquals(2, $dom->find('a ~ a')->length);
}
/*
* Test multiple selectors
*/
public function testMultipleSelectors()
{
$dom = new DomQuery('<div><a>1</a><b>2</b></div><a id="here">3</a><p><a>4</a></p>');
$this->assertEquals(2, $dom->find('#here, div > b')->length);
}
/*
* Test class selector
*/
public function testClassSelector()
{
$dom = new DomQuery('<div><a class="monkey moon">1</a><b>2</b></div><a class="monkey">3</a>');
$this->assertEquals(2, $dom->find('a.monkey')->length);
$this->assertEquals(1, $dom->find('.moon')->length);
$this->assertEquals(1, $dom->find('a.moon')->length);
}
/*
* Test class selector with uppercase
*/
public function testClassSelectorWithUppercase()
{
$dom = new DomQuery('<div><a class="monkey">1</a><b>2</b></div><a class="Monkey">3</a>');
$this->assertEquals('3', $dom->find('.Monkey')->text());
$this->assertEquals(1, $dom->find('.Monkey')->length);
$this->assertEquals(1, $dom->find('a.Monkey')->length);
}
/*
* Test class selector with underscore
*/
public function testClassSelectorWithUnderscore()
{
$dom = new DomQuery('<div><a class="monkey_moon">1</a><b>2</b></div><a class="monkey-moon">3</a>');
$this->assertEquals('1', $dom->find('.monkey_moon')->text());
$this->assertEquals('3', $dom->find('.monkey-moon')->text());
}
/*
* Test emoji as class selector
*/
public function testEmojiClassSelector()
{
$dom = new DomQuery('<div><a>1</a><b class="π">2</b></div><a>3</a>');
$this->assertEquals('2', $dom->find('.π')->text());
$this->assertEquals(1, $dom->find('b.π')->length);
}
/*
* Test not filter selector
*/
public function testNotFilterSelector()
{
$dom = new DomQuery('<a>1</a><a class="monkey">2</a><a id="some-monkey">3</a>');
$this->assertEquals(2, $dom->find('a:not(.monkey)')->length);
$this->assertEquals(2, $dom->find('a:not([id])')->length);
$this->assertEquals(1, $dom->find('a:not([id],[class])')->length);
$this->assertEquals(2, $dom->find('a:not(#some-monkey)')->length);
$this->assertEquals(1, $dom->find('a:not(#some-monkey, .monkey)')->length);
$this->assertEquals(1, $dom->find('a:not(.monkey,#some-monkey)')->length);
$this->assertEquals(3, $dom->find('a:not(b)')->length);
}
/*
* Test has filter selector
*/
public function testHasFilterSelector()
{
$dom = new DomQuery('<ul>
<li id="item2">list item 1<a></a></li>
<li id="item2">list item 2</li>
<li id="item3"><b></b>list item 3</li>
<li >list item 4</li>
<li class="item-item"><span id="anx">x</span></li>
<li class="item item6">list item 6</li>
</ul>');
$this->assertEquals('item2', $dom->find('li:has(a)')->id);
$this->assertEquals(1, $dom->find('li:has(b)')->length);
$this->assertEquals('item-item', $dom->find('li:has(span#anx)')->class);
$this->assertEquals('item-item', $dom->find('li:has(*#anx)')->class);
$this->assertEquals(1, $dom->find('ul:has(li.item)')->length);
$this->assertEquals(1, $dom->find('ul:has(span)')->length);
$this->assertEquals(1, $dom->find('ul:has(li span)')->length);
$this->assertEquals(0, $dom->find('ul:has(> span)')->length);
}
/*
* Test contains selector
*/
public function testContainsSelector()
{
$dom = new DomQuery('<a>no</a><a id="ok">yes it is!</a><a>no</a>');
$this->assertEquals('ok', $dom->find('a:contains(yes)')->attr('id'));
}
/*
* Test attribute selector
*/
public function testAttributeSelector()
{
$dom = new DomQuery('<ul>
<li>list item 1</li>
<li id="item2">list item 2</li>
<li id="item3" _="x" i- i2-="">list item 3</li>
<li>list item 4</li>
<li class="item-item">list item 5</li>
<li class="item item6" rel="x">list item 6</li>
<li class="item"></li>
<meta http-equiv="Content-Type" content="text/html">
</ul>');
$this->assertEquals(2, $dom->find('li[id]')->length);
$this->assertEquals(0, $dom->find('li[id ]')->length);
$this->assertEquals(1, $dom->find('li[_]')->length);
$this->assertEquals(1, $dom->find('li[_=x]')->length);
$this->assertEquals(1, $dom->find('li[i-]')->length);
$this->assertEquals(1, $dom->find('li[i2-]')->length);
$this->assertEquals(2, $dom->find('li[id^=\'item\']')->length);
$this->assertEquals(2, $dom->find('li[id*=\'tem\']')->length);
$this->assertEquals('list item 3', $dom->find('li[id$=\'tem3\']')->text());
$this->assertEquals(0, $dom->find('li[id$=\'item\']')->length);
$this->assertEquals(0, $dom->find('li[id|=\'item\']')->length);
$this->assertEquals('list item 3', $dom->find('li[id=\'item3\']')->text());
$this->assertEquals('list item 6', $dom->find('li[class~=\'item6\']')->text());
$this->assertEquals('list item 6', $dom->find('li[class][rel]')->text());
$this->assertEquals(2, $dom->find('li[class~=\'item\']')->length);
$this->assertEquals(1, $dom->find('li[class~=\'item\'][class~=\'item6\']')->length);
$this->assertEquals(0, $dom->find('li[class~=\'item\'][id~=\'item\']')->length);
$this->assertEquals(3, $dom->find('li[class*=\'item\']')->length);
$this->assertEquals(2, $dom->find('li[class|=\'item\']')->length);
$this->assertEquals('text/html', (string) $dom->find('meta[http-equiv^="Content"]')->attr('content'));
}
/*
* Test malformed attribute selector
*/
public function testMalformedAttributeSelector()
{
$this->expectException(\Exception::class);
$dom = new DomQuery('<div></div>');
$dom->find('#id[-]');
}
/*
* Test odd even pseudo selector
* @note :even and :odd use 0-based indexing, so even (0, 2, 4) becomes item (1, 3, 5)
*/
public function testOddEvenPseudoSelector()
{
$dom = new DomQuery('<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
<li>list item 6</li>
</ul>');
$this->assertEquals(3, $dom->find('li')->filter(':even')->length); // 1 3 5
$this->assertEquals('list item 5', $dom->find('li')->filter(':even')->last()->text());
$this->assertEquals(3, $dom->find('li')->filter(':odd')->length); // 2 4 6
$this->assertEquals('list item 6', $dom->find('li')->filter(':odd')->last()->text());
}
/*
* Test first child pseudo selector
*/
public function testFirstChildPseudoSelector()
{
$dom = new DomQuery('<div>
<div id="list-a">
<span>a</span>
<li>nope</li>
</div>
<ul id="list-b">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul></div>');
$this->assertEquals(0, $dom->find('ul:first-child')->length);
$this->assertEquals(1, $dom->find('div > div:first-child')->length);
$this->assertEquals('item 1', $dom->find('li:first-child')->text());
}
/*
* Test last child pseudo selector
*/
public function testLastChildPseudoSelector()
{
$dom = new DomQuery('<section>
<div id="list-a">
<li>nope</li>
<span>a</span>
</div>
<ul id="list-b">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul></section>');
$this->assertEquals(0, $dom->find('div:last-child')->length);
$this->assertEquals('item 3', $dom->find('li:last-child')->text());
$this->assertTrue($dom->find('ul')->is(':last-child'));
}
/*
* Test first child pseudo selector
*/
public function testNthChildPseudoSelector()
{
$dom = new DomQuery('<div>
<div id="list-a">
<span>a</span>
<li>nope</li>
</div>
<ul id="list-b">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul></div>');
$this->assertEquals(0, $dom->find('ul:nth-child(2)')->length);
$this->assertEquals('item 2', $dom->find('li:nth-child(2)')->text());
}
/*
* Test only child pseudo selector
*/
public function testOnlyChildPseudoSelector()
{
$dom = new DomQuery('<section>
<ul id="list-b">
<li>nope</li>
<span>nope</span>
</ul>
<ul id="list-b">
<li>yep</li>
</ul></section>');
$this->assertEquals(0, $dom->find('span:only-child')->length);
$this->assertEquals(0, $dom->find('ul:only-child')->length);
$this->assertTrue($dom->is(':only-child'));
$this->assertEquals('yep', $dom->find('li:only-child')->text());
}
/*
* Test parent pseudo selector
*/
public function testParentPseudoSelector()
{
$dom = new DomQuery('<section>
<ul id="list-b">
<li>nope</li>
<li><span>yep</span></li>
<li>nope</li>
</ul></section>');
$this->assertEquals('yep', $dom->find('li:parent')->text());
$this->assertEquals(1, $dom->find('li:parent')->length);
$this->assertEquals(2, $dom->find('li:not(:parent)')->length);
}
/*
* Test empty pseudo selector
*/
public function testEmptyPseudoSelector()
{
$dom = new DomQuery('<ul id="list-b">
<li id="nope">nope</li>
<li id="yep"></li>
<li id="nope"><span></span></li>
</ul>');
$this->assertEquals('yep', $dom->find('li:empty')->attr('id'));
$this->assertEquals(1, $dom->find('li:empty')->length);
}
/*
* Test empty pseudo selector
*/
public function testNotEmptyPseudoSelector()
{
$dom = new DomQuery('<ul id="list-b">
<li id="nope"></li>
<li id="yep">hi</li>
<li id="yep2"><span></span></li>
</ul>');
$this->assertEquals('yep', $dom->find('li:not-empty')->attr('id'));
$this->assertEquals('yep2', $dom->find('li:not-empty')->last()->attr('id'));
$this->assertEquals(2, $dom->find('li:not-empty')->length);
}
/*
* Test header pseudo selector
*/
public function testHeaderPseudoSelector()
{
$dom = new DomQuery('<div>
<span>nope</span>
<h1>yep</h1>
<h6>yep2</h6>
</div>');
$this->assertEquals('yep', $dom->find(':header')->text());
$this->assertEquals('yep2', $dom->find(':header')->last()->text());
$this->assertEquals('nope', $dom->find('div > *:not(:header)')->text());
}
/*
* Test first and last pseudo selector
*/
public function testFirstAndLastPseudoSelector()
{
$dom = new DomQuery('<div>
<span>yep</span>
<h1>nope</h1>
<h6>yep2</h6>
</div>');
$this->assertEquals('yep', $dom->find('div > *:first')->text());
$this->assertEquals('yep2', $dom->find('div > *:last')->text());
$result = $dom->find('div > *:first, div > *:last');
$this->assertEquals('yep', $result->first()->text());
$this->assertEquals('yep2', $result->last()->text());
}
/*
* Test root pseudo selector
*/
public function testRootPseudoSelector()
{
$dom = new DomQuery('<div id="yep">
<span>nope</span>
<h1>nope</h1>
<h6>nope</h6>
</div>');
$this->assertEquals('yep', $dom->find(':root')->attr('id'));
$this->assertEquals(1, $dom->find(':root')->length);
}
/*
* Test invalid xpath expression
*/
public function testInvalidPseudoSelector()
{
$this->expectException(\Exception::class);
CssToXpath::transform('a:not-a-selector');
}
}
| php | MIT | 4bc72c3da2e82eb7c08fa30582f71e91843423df | 2026-01-05T05:09:18.310463Z | false |
Rct567/DomQuery | https://github.com/Rct567/DomQuery/blob/4bc72c3da2e82eb7c08fa30582f71e91843423df/tests/Rct567/DomQuery/Tests/DomQueryTraversingFilterTest.php | tests/Rct567/DomQuery/Tests/DomQueryTraversingFilterTest.php | <?php
namespace Rct567\DomQuery\Tests;
use Rct567\DomQuery\DomQuery;
class DomQueryTraversingFilterTest extends \PHPUnit\Framework\TestCase
{
/*
* Test is
*/
public function testIs()
{
$dom = new DomQuery('<a>hai</a> <a></a> <a id="mmm"></a> <a class="x"></a> <a class="xpp"></a> <header></header>');
$this->assertTrue($dom[2]->is('#mmm'));
$this->assertTrue($dom[2]->next()->is('.x'));
$this->assertTrue($dom[0]->is($dom->xpathQuery('//a[position()=1]')));
$this->assertTrue($dom[0]->is($dom[0]));
$this->assertTrue($dom[0]->is(function ($node) {
return $node->tagName == 'a';
}));
$this->assertFalse($dom[0]->is($dom[1]));
$this->assertFalse($dom[0]->is($dom->find('a:last-child')));
$this->assertTrue($dom->find(':last-child')->is('header'));
$this->assertTrue($dom->find(':last-child')->is($dom->find(':last-child')->get(0))); // check by DOMNode
}
/*
*
*/
public function testHas()
{
$dom = new DomQuery('<a>hai</a> <a></a> <a id="mmm"></a> <a class="x"><span id="here"><u></u></span></a> <a class="xpp"><u></u></a>');
$this->assertEquals('<a class="x"><span id="here"><u></u></span></a>', (string) $dom->find('a')->has('#here'));
$this->assertEquals('<a class="x"><span id="here"><u></u></span></a>', (string) $dom->find('a')->has('span > u'));
$this->assertEquals('<a class="x"><span id="here"><u></u></span></a>', (string) $dom->find('a')->has($dom->find('#here')));
$this->assertEquals('<a class="x"><span id="here"><u></u></span></a>', (string) $dom->find('a')->has($dom->find('#here')->get(0))); # by DOMNode
$this->assertEquals(0, (string) $dom->find('a')->has(null)->length);
}
/*
* Test filter on selection result
*/
public function testFilter()
{
$dom = new DomQuery('<a>hai</a> <a></a> <a id="mmm"></a> <a class="x"></a> <a class="xpp"></a> <header>2</header>');
$selection = $dom->find('a');
$this->assertEquals(5, $selection->length);
$this->assertEquals(5, $selection->filter('a')->length);
$this->assertEquals(5, $selection->filter(function ($node) {
return $node->tagName == 'a';
})->length);
$this->assertEquals(1, $selection->filter('#mmm')->length);
$this->assertEquals(1, $selection->filter($dom->getDocument()->getElementById('mmm'))->length);
$this->assertEquals(1, $selection->filter('a')->filter('.xpp')->length);
$this->assertEquals('<a id="mmm"></a><a class="x"></a><a class="xpp"></a>', (string) $selection->filter('a[class], #mmm'));
$this->assertEquals('<a class="xpp"></a>', (string) $selection->filter($dom->find('a.xpp')));
$this->assertEquals('<a class="x"></a>', (string) $selection->filter($dom->find('a')->get(-2))); // filter by DOMNode
$this->assertEquals('<header>2</header>', (string) $dom->find('*')->filter('header'));
$this->assertEquals(2, $dom->find('a[class]')->filter(null)->length);
$this->assertEquals('<a class="x"></a><a class="xpp"></a>', (string) $dom->find('a[class]')->filter(null));
}
/*
* Test not filter on selection result
*/
public function testNot()
{
$dom = new DomQuery('<a>hai</a> <a></a> <a id="mmm"></a> <a class="x"></a> <a class="xpp"></a> <header>2</header>');
$selection = $dom->find('a');
$this->assertEquals(5, $selection->length);
$this->assertEquals(5, $selection->not('p')->length);
$this->assertEquals((string) $selection, (string) $selection->not(null));
$this->assertEquals(0, $selection->not('a')->length);
$this->assertEquals(4, $selection->not('#mmm')->length);
$this->assertEquals(3, $selection->not('#mmm')->not('.xpp')->length);
$this->assertEquals(2, $selection->not('a[class], #mmm')->length);
$this->assertEquals(2, $selection->not(':even')->length);
$this->assertEquals(2, $selection->not(function ($node) {
return $node->hasAttributes();
})->length);
$this->assertEquals(4, $selection->not($dom->getDocument()->getElementById('mmm'))->length);
$inner = (string) $selection->not($dom->find('a:first-child, a:last'));
$this->assertEquals('<a></a><a id="mmm"></a><a class="x"></a>', $inner);
$this->assertEquals('<a>hai</a><a></a><a id="mmm"></a>', (string) $dom->find('*')->not('header')->not('[class]'));
$this->assertEquals('<a class="xpp"></a>', (string) $dom->find('a[class]')->not($dom->find('.x')->get(0))); // filter by DOMNode
}
/*
* Test first last, with and without filter selector
*/
public function testFirstLast()
{
$dom = new DomQuery('<a>1</a> <a>2</a> <a>3</a>');
$links = $dom->children('a');
$this->assertEquals(3, $links->length);
$this->assertEquals(null, $links->first()->next('p')->text());
$this->assertEquals(null, $links->last()->prev('p')->text());
$this->assertEquals('2', $links->first()->next('a')->text());
$this->assertEquals('2', $links->last()->prev('a')->text());
$this->assertEquals(0, $links->first('p')->length);
$this->assertEquals(0, $links->last('p')->length);
$this->assertEquals(1, $links->first('a')->length);
$this->assertEquals(1, $links->last('a')->length);
}
/*
* Test slice
*/
public function testSlice()
{
$dom = new DomQuery('<a>1</a><a>2</a><a>3</a><a>4</a><a>5</a><a>6</a>');
$this->assertEquals('<a>1</a><a>2</a>', (string) $dom->find('a')->slice(0, 2));
$this->assertEquals('<a>3</a><a>4</a><a>5</a><a>6</a>', (string) $dom->find('a')->slice(2));
$this->assertEquals('<a>6</a>', (string) $dom->find('a')->slice(-1));
$this->assertEquals('<a>5</a>', (string) $dom->find('a')->slice(-2, -1));
}
/*
* Test eq
*/
public function testEq()
{
$dom = new DomQuery('<a>1</a><a>2</a><a>3</a><a>4</a><a>5</a><a>6</a>');
$this->assertEquals('<a>1</a>', (string) $dom->find('a')->eq(0));
$this->assertEquals('<a>2</a>', (string) $dom->find('a')->eq(1));
$this->assertEquals('<a>6</a>', (string) $dom->find('a')->eq(-1));
$this->assertEquals('<a>5</a>', (string) $dom->find('a')->eq(-2));
}
/*
* Test map (with returning string and array)
*/
public function testMap()
{
$dom = new DomQuery('<p> <a>1</a> <a>2,3</a> <a>4</a> <span></span> </p>');
$map = $dom->find('p > *')->map(function ($elm) {
if ($elm->textContent !== '') {
if (strpos($elm->textContent, ',') !== false) {
return explode(',', $elm->textContent);
} else {
return $elm->textContent;
}
}
});
$this->assertEquals(['1', '2', '3', '4'], $map);
}
}
| php | MIT | 4bc72c3da2e82eb7c08fa30582f71e91843423df | 2026-01-05T05:09:18.310463Z | false |
Rct567/DomQuery | https://github.com/Rct567/DomQuery/blob/4bc72c3da2e82eb7c08fa30582f71e91843423df/tests/Rct567/DomQuery/Tests/DomQueryTraversingTreeTest.php | tests/Rct567/DomQuery/Tests/DomQueryTraversingTreeTest.php | <?php
namespace Rct567\DomQuery\Tests;
use Rct567\DomQuery\DomQuery;
class DomQueryTraversingTreeTest extends \PHPUnit\Framework\TestCase
{
/*
* Test find
*/
public function testFindWithSelection()
{
$dom = new DomQuery('<a>1</a><a>2</a><a id="last">3</a>');
$this->assertEquals('<a>1</a><a>2</a><a id="last">3</a>', (string) $dom->find($dom->find('a')));
$this->assertEquals('<a id="last">3</a>', (string) $dom->find($dom->getDocument()->getElementById('last')));
$this->assertEquals('<a id="last">3</a>', (string) $dom->find($dom->find('a:contains(3)')));
}
/*
* Test find on context
*/
public function testFindOnContext()
{
$dom = new DomQuery('
<div class="test"><p class="bob">111</p></div>
<div class="test"><p class="bob">222</p></div>
');
// second .bob should not be affected
$dom->find('.test')->first()->find('.someotherclass,.bob')->addClass('affected');
$this->assertEquals('<div class="test"><p class="bob affected">111</p></div><div class="test"><p class="bob">222</p></div>', (string) $dom);
}
/*
* Test findOrFail
*/
public function testFindOrFailSuccess()
{
$dom = new DomQuery('<a>1</a><a>2</a><a id="last">3</a>');
$this->assertEquals(1, $dom->findOrFail('a#last')->length);
}
/*
* Test findOrFail exception
*/
public function testFindOrFailException()
{
$this->expectException(\Exception::class);
$dom = new DomQuery('<a>1</a><a>2</a><a id="last">3</a>');
$dom->findOrFail('span');
}
/*
* Test findOrFail exception using collection
*/
public function testFindOrFailExceptionUsingCollection()
{
$this->expectException(\Exception::class);
$dom = new DomQuery('<a>1</a><a>2</a><a id="last">3</a>');
$dom->find('#last')->findOrFail($dom->find('a:first-child'));
}
/*
* Test next
*/
public function testNext()
{
$dom = new DomQuery('<ul> <li id="a">1</li> nope <li id="b">2</li> </ul>');
$this->assertEquals('<li id="b">2</li>', (string) $dom->find('#a')->next());
$this->assertEquals('', (string) $dom->find('#b')->next());
}
/*
* Test next all
*/
public function testNextAll()
{
$dom = new DomQuery('<ul> <li id="a">1</li> nope <li id="b">2</li> <li id="c">3</li> </ul>');
$this->assertEquals('<li id="b">2</li><li id="c">3</li>', (string) $dom->find('#a')->nextAll());
$this->assertEquals('<li id="c">3</li>', (string) $dom->find('#b')->nextAll());
$this->assertEquals('', (string) $dom->find('#c')->nextAll());
}
/*
* Test next until
*/
public function testNextUntil()
{
$dom = new DomQuery('<div>
<span id="first">1</span>
<span>2</span>
<span>3</span>
<span class="stop-but-not-selected">4</span>
<span>5</span>
</div>');
$result = $dom->find('#first')->nextUntil('.stop-but-not-selected');
$this->assertEquals('<span>2</span><span>3</span>', (string) $result);
$result = $dom->find('#first')->nextUntil(function ($elm) {
return DomQuery::create($elm)->is('.stop-but-not-selected');
});
$this->assertEquals('<span>2</span><span>3</span>', (string) $result);
}
/*
* Test previous
*/
public function testPrev()
{
$dom = new DomQuery('<ul> <li id="a">1</li> nope <li id="b">2</li> </ul>');
$this->assertEquals('<li id="a">1</li>', (string) $dom->find('#b')->prev());
$this->assertEquals('', (string) $dom->find('#a')->prev());
}
/*
* Test previous all
*/
public function testPrevAll()
{
$dom = new DomQuery('<ul> <li id="a">1</li> nope <li id="b">2</li> <li id="c">3</li> </ul>');
$this->assertEquals('<li id="a">1</li><li id="b">2</li>', (string) $dom->find('#c')->prevAll());
$this->assertEquals('<li id="a">1</li>', (string) $dom->find('#b')->prevAll());
$this->assertEquals('', (string) $dom->find('#a')->prevAll());
}
/*
* Test prev until
*/
public function testPrevUntil()
{
$dom = new DomQuery('<div>
<span>1</span>
<span class="stop-but-not-selected">2</span>
<span>3</span>
<span>4</span>
<span id="last">5</span>
</div>');
$result = $dom->find('#last')->prevUntil('.stop-but-not-selected');
$this->assertEquals('<span>4</span><span>3</span>', (string) $result);
$result = $dom->find('#last')->prevUntil(function ($elm) {
return DomQuery::create($elm)->is('.stop-but-not-selected');
});
$this->assertEquals('<span>4</span><span>3</span>', (string) $result);
}
/*
* Test first last, with and without filter selector
*/
public function testSiblings()
{
$dom = new DomQuery('<div><a>1</a> <a id="target">2</a> <a>3</a></div>');
$siblings = $dom->find('#target')->siblings();
$this->assertEquals(2, $siblings->length);
$this->assertEquals('1', $siblings->first()->text());
$this->assertEquals('3', $siblings->last()->text());
}
/*
* Test children (spaces should be ignored by default)
*/
public function testChildren()
{
$dom = new DomQuery('<div><a>1</a> <a>2</a> <a>3</a></div>');
$children = $dom->find('div')->children();
$this->assertEquals(3, $children->length);
$this->assertEquals('<a>1</a>', (string) $children->first());
$this->assertEquals('<a>3</a>', (string) $children->last());
}
/*
* Test children from new instance
*/
public function testChildrenFromNewInstance()
{
$dom = new DomQuery('<div><p><span>x</span></p></div>');
$result = array();
$dom->find('p')->each(function ($node) use (&$result) {
$result[] = (string) (new DomQuery($node))->children();
$result[] = (string) DomQuery::create($node)->children();
});
$this->assertEquals('<span>x</span>|<span>x</span>', implode('|', $result));
}
/*
* Test contents (children including text nodes)
*/
public function testContents()
{
$dom = new DomQuery('<div> <a>1</a> <a>2</a> <a>3</a> </div>');
$children = $dom->find('div')->contents();
$this->assertEquals(7, $children->length); // 3 elements plus 4 spaces
$this->assertEquals(' ', (string) $children[0]);
$this->assertEquals('<a>1</a>', (string) $children[1]);
}
/*
* Test get parent
*/
public function testParent()
{
$dom = new DomQuery('<a></a><a></a><a class="link">
<b><span></span></b>
</a>');
$this->assertEquals('b', $dom->find('span')->parent()->tagName);
$this->assertEquals('link', $dom->find('span')->parent('b')->parent('a')->class);
$this->assertEquals(0, $dom->find('span')->parent('div')->length);
}
/*
* Test parent method to get root
*/
public function testParentToGetRoot()
{
$dom = new DomQuery('<a><b><span></span></b></a>');
$this->assertInstanceOf('DOMDocument', $dom->find('b')->parent()->parent()->get(0));
$this->assertEquals('<a><b><span></span></b></a>', (string) $dom->parent()->children());
}
/*
* Test get closest
*/
public function testClosest()
{
$dom = new DomQuery('<a></a><a></a><a class="link">
<b><span></span></b>
</a>');
$this->assertEquals('a', $dom->find('span')->closest('.link')->tagName);
$this->assertEquals('<b><span></span></b>', (string) $dom->find('span')->closest('b'));
$this->assertEquals(0, $dom->find('span')->closest('nope')->length);
}
/*
* Test traversing nodes from readme
*/
public function testTraversingNodesReadmeExamples()
{
$dom = new DomQuery('<a>1</a> <a>2</a> <a>3</a>');
$links = $dom->children('a');
$result = '';
foreach ($links as $elm) {
$result .= $elm->text();
}
$this->assertEquals('123', $result);
$this->assertEquals('1', $links[0]->text());
$this->assertEquals('3', $links->last()->text());
$this->assertEquals('2', $links->first()->next()->text());
$this->assertEquals('2', $links->last()->prev()->text());
$this->assertEquals('1', $links->get(0)->textContent);
$this->assertEquals('3', $links->get(-1)->textContent);
}
/*
* Make selection and sub selection
*/
public function testSubSelection()
{
$html = '<div id="main" class="root">
<div class="level-a"></div>
<div class="level-a">
<p>Hai</p>
<div class="level-b"></div>
<div class="level-b"></div>
<div class="level-b">
<div class="level-c"></div>
</div>
</div>
<div class="level-a"></div>
</div>';
$dom = new DomQuery($html);
$this->assertEquals('main', $dom->id);
$this->assertEquals('root', $dom->class);
$this->assertTrue($dom->is($dom->getDocument()->getElementById('main')));
// main selection
$main_selection = $dom->find('.level-a');
$this->assertCount(3, $main_selection);
$this->assertTrue($main_selection->is($dom->getDocument()->getElementsByTagName('div')));
$this->assertFalse($main_selection->is($dom->getDocument()->getElementById('main')));
// make sub selection
$sub_selection = $main_selection->find('> div'); // child divs from main selection
$this->assertCount(3, $sub_selection);
$this->assertEquals('level-b', $sub_selection->class);
// check what it is
$this->assertTrue($sub_selection->is('.level-b'));
$this->assertTrue($sub_selection->is('.root .level-b'));
$this->assertTrue($sub_selection->is('div:not-empty')); // last has child (div with class level-c)
$this->assertTrue($sub_selection->is('div:has(.level-c)')); // last has child (div with class level-c)
$this->assertFalse($sub_selection->is('div.level-a'));
$this->assertFalse($sub_selection->is('div.level-c'));
$this->assertFalse($sub_selection->is('p'));
$this->assertFalse($sub_selection->is('#main'));
// same thing again
$sub_selection = $main_selection->children('div, span');
$this->assertCount(3, $sub_selection);
$this->assertEquals('level-b', $sub_selection->class);
// dual selection
$dual_selection = $dom->find('p:first-child, div.level-b:last-child');
$this->assertCount(2, $dual_selection);
$this->assertTrue($dual_selection[0]->is('p'));
$this->assertTrue($dual_selection[0]->is(':first-child'));
$this->assertFalse($dual_selection[0]->is(':last-child'));
$this->assertTrue($dual_selection[1]->is('div'));
$this->assertTrue($dual_selection[1]->is(':last-child'));
$this->assertFalse($dual_selection[1]->is(':first-child'));
}
}
| php | MIT | 4bc72c3da2e82eb7c08fa30582f71e91843423df | 2026-01-05T05:09:18.310463Z | false |
Rct567/DomQuery | https://github.com/Rct567/DomQuery/blob/4bc72c3da2e82eb7c08fa30582f71e91843423df/tests/Rct567/DomQuery/Tests/DomQueryAttributesTest.php | tests/Rct567/DomQuery/Tests/DomQueryAttributesTest.php | <?php
namespace Rct567\DomQuery\Tests;
use Rct567\DomQuery\DomQuery;
class DomQueryAttributesTest extends \PHPUnit\Framework\TestCase
{
/*
* Test get attribute value
*/
public function testGetAttributeValue()
{
$this->assertEquals('hello', DomQuery::create('<a title="hello"></a>')->attr('title'));
}
/*
* Test get attribute value on non existing element
*/
public function testGetAttributeValueOnNonElements()
{
$this->assertNull(DomQuery::create('<a title="hello"></a>')->find('nope')->attr('title'));
}
/*
* Test change attribute
*/
public function testSetAttributeValue()
{
$this->assertEquals('<a title="oke"></a>', (string) DomQuery::create('<a title="hello"></a>')->attr('title', 'oke'));
}
/*
* Test remove attribute
*/
public function testRemoveAttribute()
{
$dom = DomQuery::create('<a title="hello">Some text</a>');
$dom->removeAttr('title');
$this->assertEquals('<a>Some text</a>', (string) $dom);
}
/*
* Test remove multiple attribute
*/
public function testRemoveMultipleAttribute()
{
$dom = DomQuery::create('<a title="hello" alt="x">Some text</a>');
$dom->removeAttr('title alt');
$this->assertEquals('<a>Some text</a>', (string) $dom);
}
/*
* Test remove multiple attribute using array
*/
public function testRemoveMultipleAttributeArray()
{
$dom = DomQuery::create('<a title="hello" alt="x">Some text</a>');
$dom->removeAttr(['title', 'alt']);
$this->assertEquals('<a>Some text</a>', (string) $dom);
}
/*
* Test add class name
*/
public function testAddClass()
{
$dom = DomQuery::create('<a></a><a href="hello" class=""></a><a class="before"></a>');
$dom->find('a')->addClass('after');
$this->assertEquals('<a class="after"></a><a href="hello" class="after"></a><a class="before after"></a>', (string) $dom);
}
/*
* Test add multiple class names
*/
public function testAddMultipleClasses()
{
$dom = DomQuery::create('<a href="hello" class=""></a><a class="before"></a>');
$dom->find('a')->addClass('after after2');
$this->assertEquals('<a href="hello" class="after after2"></a><a class="before after after2"></a>', (string) $dom);
}
/*
* Test add multiple class names using array
*/
public function testAddMultipleClassesArray()
{
$dom = DomQuery::create('<a href="hello" class=""></a><a class="before"></a>');
$dom->find('a')->addClass(['after', 'after2']);
$this->assertEquals('<a href="hello" class="after after2"></a><a class="before after after2"></a>', (string) $dom);
}
/*
* Test has class
*/
public function testHasClass()
{
$dom = DomQuery::create('<a href="hello" class=""></a><a class="before"></a>');
$this->assertFalse($dom->find('a')->first()->hasClass('before'));
$this->assertTrue($dom->find('a')->last()->hasClass('before'));
}
/*
* Test remove class name
*/
public function testRemoveClass()
{
$dom = DomQuery::create('<a class=""></a><a class="before"></a><a class="before stay"></a>');
$dom->find('a')->removeClass('before');
$this->assertEquals('<a class=""></a><a class=""></a><a class="stay"></a>', (string) $dom);
}
/*
* Test remove multiple class names
*/
public function testRemoveMultipleClass()
{
$dom = DomQuery::create('<a class="before go stay"></a><a class="go before"></a>');
$dom->find('a')->removeClass('before go');
$this->assertEquals('<a class="stay"></a><a class=""></a>', (string) $dom);
}
/*
* Test remove multiple class names using array
*/
public function testRemoveMultipleClassArray()
{
$dom = DomQuery::create('<a class="before go stay"></a><a class="go before"></a>');
$dom->find('a')->removeClass(['before', 'go']);
$this->assertEquals('<a class="stay"></a><a class=""></a>', (string) $dom);
}
/*
* Test remove all class names
*/
public function testRemoveAllClass()
{
$dom = DomQuery::create('<a class="before go stay"></a><a class="go before"></a>');
$dom->find('a')->removeClass();
$this->assertEquals('<a class=""></a><a class=""></a>', (string) $dom);
}
/*
* Test toggle class name
*/
public function testToggleClass()
{
$dom = DomQuery::create('<a></a><a class="b"></a>');
$dom->find('a')->toggleClass('b');
$this->assertEquals('<a class="b"></a><a class=""></a>', (string) $dom);
}
/*
* Test toggle multiple class names
*/
public function testToggleMultipleClassArray()
{
$dom = DomQuery::create('<a></a><a class="b"></a><a class="a b"></a>');
$dom->find('a')->toggleClass(['a', 'b']);
$this->assertEquals('<a class="a b"></a><a class="a"></a><a class=""></a>', (string) $dom);
}
/*
* Test set text
*/
public function testSetText()
{
$dom = DomQuery::create('<a></a>')->text('HI');
$this->assertEquals('<a>HI</a>', (string) $dom);
}
/*
* Test change text
*/
public function testTextChange()
{
$dom = DomQuery::create('<a>Some text</a>');
$dom->text('Changed text');
$this->assertEquals('<a>Changed text</a>', (string) $dom);
$this->assertEquals('Changed text', $dom->text());
}
}
| php | MIT | 4bc72c3da2e82eb7c08fa30582f71e91843423df | 2026-01-05T05:09:18.310463Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.