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
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/Routing/ResourceRoutingRepositoryTest.php
tests/Routing/ResourceRoutingRepositoryTest.php
<?php namespace StatamicRadPack\Runway\Tests\Routing; use PHPUnit\Framework\Attributes\Test; use Statamic\Facades\Data; use StatamicRadPack\Runway\Routing\RoutingModel; use StatamicRadPack\Runway\Tests\Fixtures\Models\Post; use StatamicRadPack\Runway\Tests\TestCase; class ResourceRoutingRepositoryTest extends TestCase { #[Test] public function can_find_by_uri() { $post = Post::factory()->create(); $runwayUri = $post->fresh()->runwayUri; $this->assertEquals($runwayUri->uri, "/posts/{$post->slug}"); $findByUri = Data::findByUri("/posts/{$post->slug}"); $this->assertEquals($post->fresh()->id, $findByUri->id); $this->assertTrue($findByUri instanceof RoutingModel); } #[Test] public function can_find_by_uri_where_multiple_matches_are_found() { $posts = Post::factory()->count(5)->create(['slug' => 'chicken-fried-rice']); $findByUri = Data::findByUri("/posts/{$posts[0]->slug}"); $this->assertEquals($posts[0]->id, $findByUri->id); $this->assertTrue($findByUri instanceof RoutingModel); } #[Test] public function cant_find_by_uri_if_no_matching_uri() { $findByUri = Data::findByUri('/posts/some-absolute-jibber-jabber'); $this->assertNull($findByUri); } #[Test] public function cant_find_by_uri_if_a_similar_uri_exists() { $post = Post::factory()->create(); $runwayUri = $post->fresh()->runwayUri; $this->assertEquals($runwayUri->uri, "/posts/{$post->slug}"); $findByUri = Data::findByUri("/posts/{$post->slug}-smth"); $this->assertNull($findByUri); } #[Test] public function cant_find_by_uri_when_model_is_unpublished() { $post = Post::factory()->unpublished()->create(); $runwayUri = $post->fresh()->runwayUri; $this->assertEquals($runwayUri->uri, "/posts/{$post->slug}"); $findByUri = Data::findByUri("/posts/{$post->slug}"); $this->assertNull($findByUri); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/Tags/RunwayTagTest.php
tests/Tags/RunwayTagTest.php
<?php namespace StatamicRadPack\Runway\Tests\Tags; use Illuminate\Support\Facades\Config; use PHPUnit\Framework\Attributes\Test; use Statamic\Facades\Antlers; use Statamic\Facades\Blueprint; use Statamic\Fields\Value; use StatamicRadPack\Runway\Runway; use StatamicRadPack\Runway\Tags\RunwayTag; use StatamicRadPack\Runway\Tests\Fixtures\Models\Author; use StatamicRadPack\Runway\Tests\Fixtures\Models\Post; use StatamicRadPack\Runway\Tests\TestCase; class RunwayTagTest extends TestCase { public $tag; protected function setUp(): void { parent::setUp(); $this->tag = resolve(RunwayTag::class) ->setParser(Antlers::parser()) ->setContext([]); } #[Test] public function has_been_registered() { $this->assertTrue(isset(app()['statamic.tags']['runway'])); } #[Test] public function can_get_models_with_no_parameters() { $posts = Post::factory()->count(5)->create(); $this->tag->setParameters([]); $usage = $this->tag->wildcard('post'); $this->assertEquals(5, count($usage)); $this->assertEquals((string) $usage[0]['title'], $posts[0]->title); $this->assertEquals((string) $usage[1]['title'], $posts[1]->title); $this->assertEquals((string) $usage[2]['title'], $posts[2]->title); $this->assertEquals((string) $usage[3]['title'], $posts[3]->title); $this->assertEquals((string) $usage[4]['title'], $posts[4]->title); } #[Test] public function can_get_models_with_select_parameter() { $posts = Post::factory()->count(5)->create(); $this->tag->setParameters([ 'select' => 'id,title,slug', ]); $usage = $this->tag->wildcard('post'); $this->assertEquals(5, count($usage)); $this->assertEquals((string) $usage[0]['title']->value(), $posts[0]->title); $this->assertEquals((string) $usage[0]['slug']->value(), $posts[0]->slug); $this->assertEmpty((string) $usage[0]['body']->value()); $this->assertEquals((string) $usage[1]['title']->value(), $posts[1]->title); $this->assertEquals((string) $usage[1]['slug']->value(), $posts[1]->slug); $this->assertEmpty((string) $usage[1]['body']->value()); $this->assertEquals((string) $usage[2]['title']->value(), $posts[2]->title); $this->assertEquals((string) $usage[2]['slug']->value(), $posts[2]->slug); $this->assertEmpty((string) $usage[2]['body']->value()); $this->assertEquals((string) $usage[3]['title']->value(), $posts[3]->title); $this->assertEquals((string) $usage[3]['slug']->value(), $posts[3]->slug); $this->assertEmpty((string) $usage[3]['body']->value()); $this->assertEquals((string) $usage[4]['title']->value(), $posts[4]->title); $this->assertEquals((string) $usage[4]['slug']->value(), $posts[4]->slug); $this->assertEmpty((string) $usage[4]['body']->value()); } #[Test] public function can_get_models_with_scope_parameter() { $posts = Post::factory()->count(5)->create(); $posts[0]->update(['title' => 'Pasta']); $posts[2]->update(['title' => 'Apple']); $posts[4]->update(['title' => 'Burger']); $this->tag->setParameters([ 'scope' => 'food', ]); $usage = $this->tag->wildcard('post'); $this->assertEquals(3, count($usage)); $this->assertEquals((string) $usage[0]['title']->value(), 'Pasta'); $this->assertEquals((string) $usage[1]['title']->value(), 'Apple'); $this->assertEquals((string) $usage[2]['title']->value(), 'Burger'); } #[Test] public function can_get_models_with_scope_parameter_and_scope_arguments() { $posts = Post::factory()->count(5)->create(); $posts[0]->update(['title' => 'Pasta']); $posts[2]->update(['title' => 'Apple']); $posts[4]->update(['title' => 'Burger']); $this->tag->setContext([ 'fab' => 'idoo', ]); $this->tag->setParameters([ 'scope' => 'fruit:fab', ]); $usage = $this->tag->wildcard('post'); $this->assertEquals(1, count($usage)); $this->assertEquals((string) $usage[0]['title']->value(), 'Apple'); } #[Test] public function can_get_models_with_scope_parameter_and_scope_arguments_and_multiple_scopes() { $posts = Post::factory()->count(5)->create(); $posts[0]->update(['title' => 'Pasta']); $posts[2]->update(['title' => 'Apple']); $posts[4]->update(['title' => 'Burger']); $this->tag->setContext([ 'fab' => 'idoo', ]); $this->tag->setParameters([ 'scope' => 'food|fruit:fab', ]); $usage = $this->tag->wildcard('post'); $this->assertEquals(1, count($usage)); $this->assertEquals((string) $usage[0]['title']->value(), 'Apple'); } #[Test] public function can_get_models_with_where_parameter() { $posts = Post::factory()->count(5)->create(); $posts[0]->update(['title' => 'penguin']); $this->tag->setParameters([ 'where' => 'title:penguin', ]); $usage = $this->tag->wildcard('post'); $this->assertEquals(1, count($usage)); $this->assertEquals((string) $usage[0]['title']->value(), 'penguin'); } #[Test] public function can_get_models_with_where_parameter_when_condition_is_on_relationship_field() { $posts = Post::factory()->count(5)->create(); $author = Author::factory()->create(); $posts[0]->update(['author_id' => $author->id]); $posts[2]->update(['author_id' => $author->id]); $posts[3]->update(['author_id' => $author->id]); $this->tag->setParameters([ 'where' => 'author_id:'.$author->id, ]); $usage = $this->tag->wildcard('post'); $this->assertEquals(3, count($usage)); $this->assertEquals((string) $usage[0]['title']->value(), $posts[0]->title); $this->assertEquals((string) $usage[1]['title']->value(), $posts[2]->title); $this->assertEquals((string) $usage[2]['title']->value(), $posts[3]->title); } #[Test] public function can_get_models_with_where_parameter_when_condition_is_on_nested_field() { $posts = Post::factory()->count(5)->create(); $posts[0]->update(['values' => ['alt_title' => 'penguin']]); $this->tag->setParameters([ 'where' => 'values_alt_title:penguin', ]); $usage = $this->tag->wildcard('post'); $this->assertEquals(1, count($usage)); $this->assertEquals((string) $usage[0]['values_alt_title']->value(), 'penguin'); } #[Test] public function can_get_models_with_where_in_parameter() { $posts = Post::factory()->count(5)->create(); $posts[0]->update(['slug' => 'foo']); $posts[2]->update(['slug' => 'bar']); $this->tag->setParameters([ 'where_in' => 'slug:foo,bar', ]); $usage = $this->tag->wildcard('post'); $this->assertEquals(2, count($usage)); $this->assertEquals((string) $usage[0]['slug']->value(), 'foo'); $this->assertEquals((string) $usage[1]['slug']->value(), 'bar'); } #[Test] public function can_get_models_with_where_in_parameter_when_condition_is_on_nested_field() { $posts = Post::factory()->count(5)->create(); $posts[0]->update(['values' => ['alt_title' => 'foo']]); $posts[2]->update(['values' => ['alt_title' => 'bar']]); $this->tag->setParameters([ 'where_in' => 'values_alt_title:foo,bar', ]); $usage = $this->tag->wildcard('post'); $this->assertEquals(2, count($usage)); $this->assertEquals((string) $usage[0]['values_alt_title']->value(), 'foo'); $this->assertEquals((string) $usage[1]['values_alt_title']->value(), 'bar'); } #[Test] public function can_get_models_with_with_parameter() { $posts = Post::factory()->count(5)->create(); $posts[0]->update(['title' => 'tiger']); $this->tag->setParameters([ 'with' => 'author', ]); $usage = $this->tag->wildcard('post'); $this->assertEquals(5, count($usage)); $this->assertEquals((string) $usage[0]['title'], 'tiger'); $this->assertInstanceOf(Value::class, $usage[0]['author']); $this->assertEquals($usage[0]['author']->value()['name']->value(), $posts[0]->author->name); } #[Test] public function can_get_models_with_sort_parameter() { $posts = Post::factory()->count(2)->create(); $posts[0]->update(['title' => 'abc']); $posts[1]->update(['title' => 'def']); $this->tag->setParameters([ 'sort' => 'title:desc', ]); $usage = $this->tag->wildcard('post'); $this->assertEquals(2, count($usage)); $this->assertEquals((string) $usage[0]['title'], 'def'); $this->assertEquals((string) $usage[1]['title'], 'abc'); } #[Test] public function can_get_models_with_sort_parameter_on_nested_field() { $posts = Post::factory()->count(2)->create(); $posts[0]->update(['values' => ['alt_title' => 'abc']]); $posts[1]->update(['values' => ['alt_title' => 'def']]); $this->tag->setParameters([ 'sort' => 'values_alt_title:desc', ]); $usage = $this->tag->wildcard('post'); $this->assertEquals(2, count($usage)); $this->assertEquals((string) $usage[0]['values_alt_title'], 'def'); $this->assertEquals((string) $usage[1]['values_alt_title'], 'abc'); } #[Test] public function can_get_models_with_scoping() { $posts = Post::factory()->count(2)->create(); $posts[0]->update(['title' => 'abc']); $posts[1]->update(['title' => 'def']); $this->tag->setParameters([ 'as' => 'items', ]); $usage = $this->tag->wildcard('post'); $this->assertEquals(2, count($usage['items'])); $this->assertEquals((string) $usage['items'][0]['title'], 'abc'); $this->assertEquals((string) $usage['items'][1]['title'], 'def'); } #[Test] public function can_get_models_with_limit_parameter() { $posts = Post::factory()->count(5)->create(); $this->tag->setParameters([ 'limit' => 2, ]); $usage = $this->tag->wildcard('post'); $this->assertEquals(2, count($usage)); $this->assertEquals((string) $usage[0]['title'], $posts[0]['title']); $this->assertEquals((string) $usage[1]['title'], $posts[1]['title']); $this->assertFalse(isset($usage[2])); } #[Test] public function can_get_models_with_scoping_and_pagination() { $posts = Post::factory()->count(5)->create(); $this->tag->setParameters([ 'limit' => 2, 'as' => 'items', ]); $usage = $this->tag->wildcard('post'); $this->assertEquals(2, count($usage['items'])); $this->assertEquals((string) $usage['items'][0]['title'], $posts[0]['title']); $this->assertEquals((string) $usage['items'][1]['title'], $posts[1]['title']); $this->assertFalse(isset($usage['items'][2])); $this->assertArrayHasKey('paginate', $usage); $this->assertArrayHasKey('no_results', $usage); } #[Test] public function can_get_models_and_non_blueprint_columns_are_returned() { $posts = Post::factory()->count(2)->create(); $this->tag->setParameters([]); $usage = $this->tag->wildcard('post'); $this->assertEquals(2, count($usage)); $this->assertEquals($usage[0]['id']->value(), $posts[0]['id']); $this->assertEquals($usage[1]['id']->value(), $posts[1]['id']); $this->assertEquals((string) $usage[0]['title']->value(), $posts[0]['title']); $this->assertEquals((string) $usage[1]['title']->value(), $posts[1]['title']); } #[Test] public function can_get_models_with_studly_case_resource_handle() { $postBlueprint = Blueprint::find('runway::post'); Blueprint::shouldReceive('find')->with('runway::BlogPosts')->andReturn($postBlueprint); Config::set('runway.resources.'.Post::class.'.handle', 'BlogPosts'); Runway::discoverResources(); $posts = Post::factory()->count(5)->create(); $this->tag->setParameters([]); $usage = $this->tag->wildcard('blog_posts'); $this->assertEquals(5, count($usage)); $this->assertEquals((string) $usage[0]['title'], $posts[0]->title); $this->assertEquals((string) $usage[1]['title'], $posts[1]->title); $this->assertEquals((string) $usage[2]['title'], $posts[2]->title); $this->assertEquals((string) $usage[3]['title'], $posts[3]->title); $this->assertEquals((string) $usage[4]['title'], $posts[4]->title); } #[Test] public function it_fires_an_augmented_hook() { $postBlueprint = Blueprint::find('runway::post'); Blueprint::shouldReceive('find')->with('runway::BlogPosts')->andReturn($postBlueprint); Config::set('runway.resources.'.Post::class.'.handle', 'BlogPosts'); Runway::discoverResources(); $post = Post::factory()->create(); $augmentedCount = 0; $post::hook('augmented', function ($payload, $next) use (&$augmentedCount) { $augmentedCount++; return $next($payload); }); $this->tag->setParameters([]); $this->tag->wildcard('blog_posts'); $this->assertEquals(1, $augmentedCount); } #[Test] public function it_can_count_models() { Post::factory()->count(3)->create(); Post::factory()->count(2)->create(['title' => 'Foo Bar']); $count = $this->tag ->setParameters([ 'from' => 'post', 'where' => 'title:Foo Bar', ]) ->count(); $this->assertEquals(2, $count); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/Http/Controllers/ApiControllerTest.php
tests/Http/Controllers/ApiControllerTest.php
<?php namespace StatamicRadPack\Runway\Tests\Http\Controllers; use PHPUnit\Framework\Attributes\Test; use Statamic\Facades\Config; use StatamicRadPack\Runway\Tests\Fixtures\Models\Post; use StatamicRadPack\Runway\Tests\TestCase; class ApiControllerTest extends TestCase { protected function setUp(): void { parent::setUp(); Config::set('statamic.api.resources.runway', [ 'posts' => ['allowed_filters' => ['title']], ]); } #[Test] public function gets_a_resource_that_exists() { $posts = Post::factory()->count(2)->create(); $this ->get(route('statamic.api.runway.index', ['resourceHandle' => 'posts'])) ->assertOk() ->assertJsonStructure(['data', 'meta']) ->assertJsonPath('data.0.id', $posts[0]->id) ->assertJsonPath('data.1.id', $posts[1]->id); } #[Test] public function returns_not_found_on_a_resource_that_doesnt_exist() { Post::factory()->count(2)->create(); $this ->get(route('statamic.api.runway.index', ['resourceHandle' => 'posts2'])) ->assertNotFound(); } #[Test] public function it_filters_out_unpublished_models() { $posts = Post::factory()->count(2)->create(); Post::factory()->count(2)->unpublished()->create(); $this ->get(route('statamic.api.runway.index', ['resourceHandle' => 'posts'])) ->assertOk() ->assertJsonStructure(['data', 'meta']) ->assertJsonCount(2, 'data') ->assertJsonPath('data.0.id', $posts[0]->id) ->assertJsonPath('data.1.id', $posts[1]->id); } #[Test] public function paginates_a_resource_list() { Post::factory()->count(10)->create(); $this ->get(route('statamic.api.runway.index', ['resourceHandle' => 'posts', 'limit' => 5])) ->assertOk() ->assertJsonStructure(['data', 'meta']) ->assertJsonPath('meta.current_page', 1) ->assertJsonPath('meta.last_page', 2) ->assertJsonPath('meta.total', 10); $this ->get(route('statamic.api.runway.index', ['resourceHandle' => 'posts', 'limit' => 5, 'page' => 2])) ->assertOk() ->assertJsonStructure(['data', 'meta']) ->assertJsonPath('meta.current_page', 2) ->assertJsonPath('meta.last_page', 2) ->assertJsonPath('meta.total', 10); } #[Test] public function filters_a_resource_list() { [$postA, $postB, $postC] = Post::factory()->count(3)->create(); $postA->update(['title' => 'Test One']); $postB->update(['title' => 'Test Two']); $postC->update(['title' => 'Test Three']); $this ->get(route('statamic.api.runway.index', ['resourceHandle' => 'posts'])) ->assertOk() ->assertJsonStructure(['data', 'meta']) ->assertJsonPath('meta.total', 3); $this ->get(route('statamic.api.runway.index', ['resourceHandle' => 'posts', 'filter[title:contains]' => 'one'])) ->assertOk() ->assertJsonStructure(['data', 'meta']) ->assertJsonPath('meta.total', 1); $this ->get(route('statamic.api.runway.index', ['resourceHandle' => 'posts', 'filter[title:contains]' => 'test'])) ->assertOk() ->assertJsonStructure(['data', 'meta']) ->assertJsonPath('meta.total', 3); } #[Test] public function wont_filter_a_resource_list_on_a_forbidden_filter() { [$postA, $postB, $postC] = Post::factory()->count(3)->create(); $postA->update(['title' => 'Test One']); $postB->update(['title' => 'Test Two']); $postC->update(['title' => 'Test Three']); $this ->get(route('statamic.api.runway.index', ['resourceHandle' => 'posts', 'filter[slug:contains]' => 'one'])) ->assertStatus(422); } #[Test] public function gets_a_resource_model_that_exists() { $post = Post::factory()->create(); $this ->get(route('statamic.api.runway.show', ['resourceHandle' => 'posts', 'model' => $post->id])) ->assertOk() ->assertSee(['data']) ->assertJsonPath('data.id', $post->id) ->assertJsonPath('data.title', $post->title); } #[Test] public function gets_a_resource_model_with_nested_fields() { $post = Post::factory()->create([ 'values' => [ 'alt_title' => 'Alternative Title...', 'alt_body' => 'This is a **great** post! You should *read* it.', ], ]); $this ->get(route('statamic.api.runway.show', ['resourceHandle' => 'posts', 'model' => $post->id])) ->assertOk() ->assertSee(['data']) ->assertJsonPath('data.id', $post->id) ->assertJsonPath('data.values.alt_title', 'Alternative Title...') ->assertJsonPath('data.values.alt_body', '<p>This is a <strong>great</strong> post! You should <em>read</em> it.</p> '); } #[Test] public function gets_a_resource_model_with_belongs_to_relationship() { $post = Post::factory()->create(); $this ->get(route('statamic.api.runway.show', ['resourceHandle' => 'posts', 'model' => $post->id])) ->assertOk() ->assertSee(['data']) ->assertJsonPath('data.id', $post->id) ->assertJsonPath('data.author_id.id', $post->author->id) ->assertJsonPath('data.author_id.name', $post->author->name); } #[Test] public function returns_not_found_on_a_model_that_does_not_exist() { $this ->get(route('statamic.api.runway.show', ['resourceHandle' => 'posts', 'model' => 44])) ->assertNotFound(); } #[Test] public function it_doesnt_return_unpublished_model() { $post = Post::factory()->unpublished()->create(); $this ->get(route('statamic.api.runway.show', ['resourceHandle' => 'posts', 'model' => $post->id])) ->assertNotFound(); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/Http/Controllers/CP/ResourceActionControllerTest.php
tests/Http/Controllers/CP/ResourceActionControllerTest.php
<?php namespace StatamicRadPack\Runway\Tests\Http\Controllers\CP; use PHPUnit\Framework\Attributes\Test; use Statamic\Actions\Action; use Statamic\Facades\User; use StatamicRadPack\Runway\Tests\TestCase; class ResourceActionControllerTest extends TestCase { protected function setUp(): void { parent::setUp(); BarAction::register(); } #[Test] public function can_run_action() { $this->assertFalse(BarAction::$hasRun); $this ->actingAs(User::make()->makeSuper()->save()) ->post('/cp/runway/post/actions', [ 'action' => 'bar', 'selections' => ['post'], 'values' => [], ]) ->assertOk() ->assertJson(['message' => 'Bar action run!']); $this->assertTrue(BarAction::$hasRun); } } class BarAction extends Action { protected static $handle = 'bar'; public static bool $hasRun = false; public function run($items, $values) { static::$hasRun = true; return 'Bar action run!'; } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/Http/Controllers/CP/ModelActionControllerTest.php
tests/Http/Controllers/CP/ModelActionControllerTest.php
<?php namespace StatamicRadPack\Runway\Tests\Http\Controllers\CP; use PHPUnit\Framework\Attributes\Test; use Statamic\Actions\Action; use Statamic\Facades\User; use StatamicRadPack\Runway\Tests\Fixtures\Models\Post; use StatamicRadPack\Runway\Tests\TestCase; class ModelActionControllerTest extends TestCase { protected function setUp(): void { parent::setUp(); FooAction::register(); } #[Test] public function can_run_action() { $post = Post::factory()->create(); $this->assertFalse(FooAction::$hasRun); $this ->actingAs(User::make()->makeSuper()->save()) ->post('/cp/runway/post/models/actions', [ 'action' => 'foo', 'selections' => [$post->id], 'values' => [], ]) ->assertOk() ->assertJson(['message' => 'Foo action run!']); $this->assertTrue(FooAction::$hasRun); } #[Test] public function can_get_bulk_actions_list() { $post = Post::factory()->create(); $this ->actingAs(User::make()->makeSuper()->save()) ->post('/cp/runway/post/models/actions/list', [ 'selections' => [$post->id], ]) ->assertOk() ->assertJsonPath('0.handle', 'unpublish'); } } class FooAction extends Action { protected static $handle = 'foo'; public static bool $hasRun = false; public function run($items, $values) { static::$hasRun = true; return 'Foo action run!'; } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/Http/Controllers/CP/ModelRevisionsControllerTest.php
tests/Http/Controllers/CP/ModelRevisionsControllerTest.php
<?php namespace StatamicRadPack\Runway\Tests\Http\Controllers\CP; use Illuminate\Support\Carbon; use PHPUnit\Framework\Attributes\Test; use Statamic\Facades\Folder; use Statamic\Facades\User; use StatamicRadPack\Runway\Tests\Fixtures\Models\Post; use StatamicRadPack\Runway\Tests\TestCase; class ModelRevisionsControllerTest extends TestCase { private $dir; protected function setUp(): void { parent::setUp(); $this->dir = __DIR__.'/tmp'; config(['statamic.revisions.enabled' => true]); config(['statamic.revisions.path' => $this->dir]); } protected function tearDown(): void { Folder::delete($this->dir); parent::tearDown(); } #[Test] public function it_gets_revisions() { $this->travelTo('2024-01-01 10:30:00'); $model = Post::factory()->create(['title' => 'Original title']); tap($model->makeRevision(), function ($copy) { $copy->message('Revision one'); $copy->date(Carbon::parse('2023-12-12 15:00:00')); })->save(); tap($model->makeRevision(), function ($copy) { $copy->message('Revision two'); $copy->date(Carbon::parse('2024-01-01 08:00:00')); })->save(); tap($model->makeWorkingCopy(), function ($copy) { $attrs = $copy->attributes(); $attrs['data']['title'] = 'Title modified in working copy'; $copy->attributes($attrs); })->save(); $this ->actingAs(User::make()->id('user-1')->makeSuper()->save()) ->get($model->runwayRevisionsUrl()) ->assertOk() ->assertJsonPath('0.revisions.0.action', 'revision') ->assertJsonPath('0.revisions.0.message', 'Revision one') ->assertJsonPath('0.revisions.0.attributes.data.title', 'Original title') ->assertJsonPath('0.revisions.0.attributes.item_url', "http://localhost/cp/runway/post/{$model->id}/revisions/".Carbon::parse('2023-12-12 15:00:00')->timestamp) ->assertJsonPath('1.revisions.0.action', 'revision') ->assertJsonPath('1.revisions.0.message', false) ->assertJsonPath('1.revisions.0.attributes.data.title', 'Title modified in working copy') ->assertJsonPath('1.revisions.0.attributes.item_url', "http://localhost/cp/runway/post/{$model->id}/revisions/".Carbon::parse('2024-01-01 10:30:00')->timestamp) ->assertJsonPath('1.revisions.1.action', 'revision') ->assertJsonPath('1.revisions.1.message', 'Revision two') ->assertJsonPath('1.revisions.1.attributes.data.title', 'Original title') ->assertJsonPath('1.revisions.1.attributes.item_url', "http://localhost/cp/runway/post/{$model->id}/revisions/".Carbon::parse('2024-01-01 08:00:00')->timestamp); } #[Test] public function it_creates_a_revision() { $model = Post::factory()->unpublished()->create(['title' => 'Original title']); tap($model->makeWorkingCopy(), function ($copy) { $attrs = $copy->attributes(); $attrs['data']['title'] = 'Title modified in working copy'; $copy->attributes($attrs); })->save(); $this->assertFalse($model->published()); $this->assertCount(0, $model->revisions()); $this ->actingAs(User::make()->id('user-1')->makeSuper()->save()) ->post($model->runwayCreateRevisionUrl(), ['message' => 'Test!']) ->assertOk(); $model->refresh(); $this->assertEquals($model->title, 'Original title'); $this->assertFalse($model->published()); $this->assertCount(1, $model->revisions()); $revision = $model->latestRevision(); $this->assertEquals($model->id, $revision->attributes()['id']); $this->assertFalse($revision->attributes()['published']); $this->assertEquals('Title modified in working copy', $revision->attributes()['data']['title']); $this->assertEquals('user-1', $revision->user()->id()); $this->assertEquals('Test!', $revision->message()); $this->assertEquals('revision', $revision->action()); $this->assertTrue($model->hasWorkingCopy()); } #[Test] public function it_gets_revision() { $model = Post::factory()->create(['title' => 'Original title']); $revision = $model->makeRevision() ->message('The revision') ->date(Carbon::parse('2023-12-12 15:00:00')); $revision->save(); $this ->actingAs(User::make()->id('user-1')->makeSuper()->save()) ->get($model->runwayRevisionUrl($revision)) ->assertOk() ->assertJson([ 'title' => 'Original title', 'editing' => true, 'values' => [ 'id' => $model->id, 'title' => 'Original title', ], 'readOnly' => true, ]); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/Http/Controllers/CP/ResourceControllerTest.php
tests/Http/Controllers/CP/ResourceControllerTest.php
<?php namespace StatamicRadPack\Runway\Tests\Http\Controllers\CP; use Illuminate\Support\Facades\DB; use PHPUnit\Framework\Attributes\Test; use Statamic\Facades\Blueprint; use Statamic\Facades\Config; use Statamic\Facades\Role; use Statamic\Facades\User; use Statamic\Facades\UserGroup; use StatamicRadPack\Runway\Runway; use StatamicRadPack\Runway\Tests\Fixtures\Models\Author; use StatamicRadPack\Runway\Tests\Fixtures\Models\Post; use StatamicRadPack\Runway\Tests\Fixtures\Models\User as UserModel; use StatamicRadPack\Runway\Tests\TestCase; class ResourceControllerTest extends TestCase { #[Test] public function get_model_index() { Post::factory()->count(2)->create(); $user = User::make()->makeSuper()->save(); $this ->actingAs($user) ->get(cp_route('runway.index', ['resource' => 'post'])) ->assertOk() ->assertViewIs('runway::index') ->assertSee([ 'filters', 'columns', ]); } #[Test] public function can_create_resource() { $user = User::make()->makeSuper()->save(); $this ->actingAs($user) ->get(cp_route('runway.create', ['resource' => 'post'])) ->assertOk(); } #[Test] public function cant_create_resource_if_resource_is_read_only() { Config::set('runway.resources.'.Post::class.'.read_only', true); Runway::discoverResources(); $user = User::make()->makeSuper()->save(); $this ->actingAs($user) ->get(cp_route('runway.create', ['resource' => 'post'])) ->assertRedirect(); } #[Test] public function cant_create_resource_when_blueprint_is_hidden() { $blueprint = Blueprint::find('runway::post'); Blueprint::shouldReceive('find')->with('user')->andReturn(new \Statamic\Fields\Blueprint); Blueprint::shouldReceive('find')->with('runway::author')->andReturn(new \Statamic\Fields\Blueprint); Blueprint::shouldReceive('find')->with('runway::post')->andReturn($blueprint->setHidden(true)); $user = User::make()->makeSuper()->save(); $this ->actingAs($user) ->get(cp_route('runway.create', ['resource' => 'post'])) ->assertRedirect(); } #[Test] public function can_store_resource() { $author = Author::factory()->create(); $user = User::make()->makeSuper()->save(); $this ->actingAs($user) ->post(cp_route('runway.store', ['resource' => 'post']), [ 'published' => true, 'title' => 'Jingle Bells', 'slug' => 'jingle-bells', 'body' => 'Jingle Bells, Jingle Bells, jingle all the way...', 'author_id' => [$author->id], ]) ->assertOk() ->assertJsonStructure(['data', 'saved']); $this->assertDatabaseHas('posts', [ 'title' => 'Jingle Bells', ]); } #[Test] public function cant_store_resource_if_resource_is_read_only() { Config::set('runway.resources.'.Post::class.'.read_only', true); Runway::discoverResources(); $author = Author::factory()->create(); $user = User::make()->makeSuper()->save(); $this ->actingAs($user) ->post(cp_route('runway.store', ['resource' => 'post']), [ 'title' => 'Jingle Bells', 'slug' => 'jingle-bells', 'body' => 'Jingle Bells, Jingle Bells, jingle all the way...', 'author_id' => [$author->id], ]) ->assertRedirect(); $this->assertDatabaseMissing('posts', [ 'title' => 'Jingle Bells', ]); } #[Test] public function cant_store_resource_when_blueprint_is_hidden() { $postBlueprint = Blueprint::find('runway::post'); Blueprint::shouldReceive('find')->with('user')->andReturn(new \Statamic\Fields\Blueprint); Blueprint::shouldReceive('find')->with('runway::author')->andReturn(new \Statamic\Fields\Blueprint); Blueprint::shouldReceive('find')->with('runway::post')->andReturn($postBlueprint->setHidden(true)); $author = Author::factory()->create(); $user = User::make()->makeSuper()->save(); $this ->actingAs($user) ->post(cp_route('runway.store', ['resource' => 'post']), [ 'title' => 'Jingle Bells', 'slug' => 'jingle-bells', 'body' => 'Jingle Bells, Jingle Bells, jingle all the way...', 'author_id' => [$author->id], ]) ->assertRedirect(); $this->assertDatabaseMissing('posts', [ 'title' => 'Jingle Bells', ]); } #[Test] public function can_store_resource_and_ensure_computed_field_isnt_saved_to_database() { $author = Author::factory()->create(); $user = User::make()->makeSuper()->save(); $this ->actingAs($user) ->post(cp_route('runway.store', ['resource' => 'post']), [ 'published' => true, 'title' => 'Jingle Bells', 'slug' => 'jingle-bells', 'body' => 'Jingle Bells, Jingle Bells, jingle all the way...', 'author_id' => [$author->id], 'age' => 25, // This is the computed field ]) ->assertOk() ->assertJsonStructure(['data', 'saved']); $this->assertDatabaseHas('posts', [ 'title' => 'Jingle Bells', ]); } #[Test] public function can_store_resource_and_ensure_field_isnt_saved_to_database() { $author = Author::factory()->create(); $user = User::make()->makeSuper()->save(); $this ->actingAs($user) ->post(cp_route('runway.store', ['resource' => 'post']), [ 'published' => true, 'title' => 'Jingle Bells', 'slug' => 'jingle-bells', 'body' => 'Jingle Bells, Jingle Bells, jingle all the way...', 'author_id' => [$author->id], 'dont_save' => 25, ]) ->assertOk() ->assertJsonStructure(['data', 'saved']); $this->assertDatabaseHas('posts', [ 'title' => 'Jingle Bells', ]); } #[Test] public function can_store_resource_and_ensure_appended_attribute_doesnt_attempt_to_get_saved() { $author = Author::factory()->create(); $user = User::make()->makeSuper()->save(); $this ->actingAs($user) ->post(cp_route('runway.store', ['resource' => 'post']), [ 'published' => true, 'title' => 'Jingle Bells', 'slug' => 'jingle-bells', 'body' => 'Jingle Bells, Jingle Bells, jingle all the way...', 'excerpt' => 'This is an excerpt.', 'author_id' => [$author->id], ]) ->assertOk() ->assertJsonStructure(['data', 'saved']); $this->assertDatabaseHas('posts', [ 'title' => 'Jingle Bells', ]); } #[Test] public function can_store_resource_with_nested_field() { $author = Author::factory()->create(); $user = User::make()->makeSuper()->save(); $this ->actingAs($user) ->post(cp_route('runway.store', ['resource' => 'post']), [ 'published' => true, 'title' => 'Jingle Bells', 'slug' => 'jingle-bells', 'body' => 'Jingle Bells, Jingle Bells, jingle all the way...', 'values_alt_title' => 'Batman Smells', 'author_id' => [$author->id], ]) ->assertOk() ->assertJsonStructure(['data', 'saved']); $this->assertDatabaseHas('posts', [ 'values->alt_title' => 'Batman Smells', ]); } #[Test] public function can_store_resource_and_ensure_date_comparison_validation_works() { $author = Author::factory()->create(); $user = User::make()->makeSuper()->save(); $this ->actingAs($user) ->post(cp_route('runway.store', ['resource' => 'post']), [ 'title' => 'Jingle Bells', 'slug' => 'jingle-bells', 'body' => 'Jingle Bells, Jingle Bells, jingle all the way...', 'author_id' => [$author->id], 'start_date' => [ 'date' => '2023-09-01', 'time' => '00:00', ], 'end_date' => [ 'date' => '2023-08-01', 'time' => '00:00', ], ]) ->assertSessionHasErrors('start_date'); $this->assertDatabaseMissing('posts', [ 'title' => 'Jingle Bells', ]); } #[Test] public function can_edit_resource() { $post = Post::factory()->create(); $user = User::make()->makeSuper()->save(); $this ->actingAs($user) ->get(cp_route('runway.edit', ['resource' => 'post', 'model' => $post->id])) ->assertOk() ->assertSee($post->title) ->assertSee($post->body); } #[Test] public function cant_edit_resource_when_it_does_not_exist() { $user = User::make()->makeSuper()->save(); $this ->actingAs($user) ->get(cp_route('runway.edit', ['resource' => 'post', 'model' => 12345])) ->assertNotFound() ->assertSee('Page Not Found'); } #[Test] public function can_edit_resource_with_simple_date_field() { $postBlueprint = Blueprint::find('runway::post'); Blueprint::shouldReceive('find')->with('user')->andReturn(new \Statamic\Fields\Blueprint); Blueprint::shouldReceive('find')->with('runway::author')->andReturn(new \Statamic\Fields\Blueprint); Blueprint::shouldReceive('find')->with('runway::post')->andReturn($postBlueprint->ensureField('created_at', [ 'type' => 'date', 'mode' => 'single', 'time_enabled' => false, 'time_required' => false, ])); $user = User::make()->makeSuper()->save(); $post = Post::factory()->create(); $resource = Runway::findResource('post'); $model = $resource->model()->where($resource->routeKey(), $post->getKey())->first(); $this->assertEquals($post->getKey(), $model->getKey()); $response = $this ->actingAs($user) ->get(cp_route('runway.edit', [ 'resource' => 'post', 'model' => $post->id, ])) ->assertOk(); $this->assertEquals( [ 'date' => $post->created_at->format('Y-m-d'), 'time' => null, ], $response->viewData('values')['created_at'] ); } #[Test] public function can_edit_resource_with_date_field_with_default_format() { $postBlueprint = Blueprint::find('runway::post'); Blueprint::shouldReceive('find')->with('user')->andReturn(new \Statamic\Fields\Blueprint); Blueprint::shouldReceive('find')->with('runway::author')->andReturn(new \Statamic\Fields\Blueprint); Blueprint::shouldReceive('find')->with('runway::post')->andReturn($postBlueprint->ensureField('created_at', [ 'type' => 'date', 'mode' => 'single', 'format' => 'Y-m-d', 'time_enabled' => false, 'time_required' => false, ])); $post = Post::factory()->create(); $user = User::make()->makeSuper()->save(); $resource = Runway::findResource('post'); $model = $resource->model()->where($resource->routeKey(), $post->getKey())->first(); $this->assertEquals($post->getKey(), $model->getKey()); $response = $this ->actingAs($user) ->get(cp_route('runway.edit', [ 'resource' => 'post', 'model' => $post->id, ])) ->assertOk(); $this->assertEquals( [ 'date' => $post->created_at->format('Y-m-d'), 'time' => null, ], $response->viewData('values')['created_at'] ); } #[Test] public function can_edit_resource_with_date_field_with_custom_format() { $postBlueprint = Blueprint::find('runway::post'); Blueprint::shouldReceive('find')->with('user')->andReturn(new \Statamic\Fields\Blueprint); Blueprint::shouldReceive('find')->with('runway::author')->andReturn(new \Statamic\Fields\Blueprint); Blueprint::shouldReceive('find')->with('runway::post')->andReturn($postBlueprint->ensureField('created_at', [ 'type' => 'date', 'mode' => 'single', 'format' => 'Y-m-d H:i', 'time_enabled' => true, 'time_required' => false, ])); $post = Post::factory()->create(); $user = User::make()->makeSuper()->save(); $resource = Runway::findResource('post'); $model = $resource->model()->where($resource->routeKey(), $post->getKey())->first(); $this->assertEquals($post->getKey(), $model->getKey()); $response = $this ->actingAs($user) ->get(cp_route('runway.edit', [ 'resource' => 'post', 'model' => $post->id, ])) ->assertOk(); $this->assertEquals( [ 'date' => $post->created_at->format('Y-m-d'), 'time' => $post->created_at->format('H:i'), ], $response->viewData('values')['created_at'] ); } #[Test] public function can_edit_resource_with_nested_field() { $post = Post::factory()->create([ 'values' => [ 'alt_title' => 'Im Toby Ziegler, and I work at the White House.', ], ]); $user = User::make()->makeSuper()->save(); $this ->actingAs($user) ->get(cp_route('runway.edit', ['resource' => 'post', 'model' => $post->id])) ->assertOk() ->assertSee($post->title) ->assertSee($post->body) ->assertSee('Im Toby Ziegler, and I work at the White House.'); } #[Test] public function can_edit_resource_if_resource_is_read_only() { Config::set('runway.resources.'.Post::class.'.read_only', true); Runway::discoverResources(); $post = Post::factory()->create(); $user = User::make()->makeSuper()->save(); $this ->actingAs($user) ->get(cp_route('runway.edit', ['resource' => 'post', 'model' => $post->id])) ->assertOk() ->assertSee($post->title) ->assertSee($post->body); } #[Test] public function can_edit_resource_with_nested_field_cast_to_object_in_model() { $post = Post::factory()->create([ 'external_links' => [ 'links' => [ ['label' => 'NORAD Santa Tracker', 'url' => 'noradsanta.org'], ['label' => 'North Pole HQ', 'url' => 'northpole.com'], ], ], ]); $user = User::make()->makeSuper()->save(); $this->actingAs($user) ->get(cp_route('runway.edit', ['resource' => 'post', 'model' => $post->id])) ->assertOk() ->assertSee($post->external_links->links[0]->label) ->assertSee($post->external_links->links[1]->url); } #[Test] public function can_edit_resource_if_model_is_user_model() { Config::set('auth.providers.users.model', UserModel::class); $user = UserModel::create([ 'name' => 'John Doe', 'email' => 'john.doe@example.com', ]); UserGroup::make('admins')->title('Admins')->save(); DB::table('group_user')->insert(['user_id' => $user->id, 'group_id' => 'admins']); Role::make('developer')->title('Developer')->save(); DB::table('role_user')->insert(['user_id' => $user->id, 'role_id' => 'developer']); $this ->actingAs(User::make()->makeSuper()->save()) ->get(cp_route('runway.edit', ['resource' => 'user', 'model' => $user->id])) ->assertOk() ->assertSee($user->name) ->assertSee($user->email) ->assertSee('developer') ->assertSee('admins'); } #[Test] public function can_update_resource() { $post = Post::factory()->create(); $user = User::make()->makeSuper()->save(); $this ->actingAs($user) ->patch(cp_route('runway.update', ['resource' => 'post', 'model' => $post->id]), [ 'published' => true, 'title' => 'Santa is coming home', 'slug' => 'santa-is-coming-home', 'body' => $post->body, 'author_id' => [$post->author_id], ]) ->assertOk() ->assertJsonStructure(['data', 'saved']); $post->refresh(); $this->assertEquals($post->title, 'Santa is coming home'); } #[Test] public function cant_update_resource_if_resource_is_read_only() { Config::set('runway.resources.'.Post::class.'.read_only', true); Runway::discoverResources(); $post = Post::factory()->create(); $user = User::make()->makeSuper()->save(); $this ->actingAs($user) ->patch(cp_route('runway.update', ['resource' => 'post', 'model' => $post->id]), [ 'title' => 'Santa is coming home', 'slug' => 'santa-is-coming-home', 'body' => $post->body, 'author_id' => [$post->author_id], ]) ->assertRedirect(); $post->refresh(); $this->assertNotSame($post->title, 'Santa is coming home'); } #[Test] public function can_update_resource_and_ensure_computed_field_isnt_saved_to_database() { $post = Post::factory()->create(); $user = User::make()->makeSuper()->save(); $this ->actingAs($user) ->patch(cp_route('runway.update', ['resource' => 'post', 'model' => $post->id]), [ 'published' => true, 'title' => 'Santa is coming home', 'slug' => 'santa-is-coming-home', 'body' => $post->body, 'author_id' => [$post->author_id], 'age' => 19, // This is the computed field ]) ->assertOk() ->assertJsonStructure(['data', 'saved']); $post->refresh(); $this->assertEquals($post->title, 'Santa is coming home'); } #[Test] public function can_update_resource_and_ensure__field_isnt_saved_to_database() { $post = Post::factory()->create(); $user = User::make()->makeSuper()->save(); $this ->actingAs($user) ->patch(cp_route('runway.update', ['resource' => 'post', 'model' => $post->id]), [ 'published' => true, 'title' => 'Santa is coming home', 'slug' => 'santa-is-coming-home', 'body' => $post->body, 'author_id' => [$post->author_id], 'dont_save' => 19, ]) ->assertOk() ->assertJsonStructure(['data', 'saved']); $post->refresh(); $this->assertEquals($post->title, 'Santa is coming home'); } #[Test] public function can_update_resource_and_ensure_appended_attribute_doesnt_attempt_to_get_saved() { $post = Post::factory()->create(); $user = User::make()->makeSuper()->save(); $this ->actingAs($user) ->patch(cp_route('runway.update', ['resource' => 'post', 'model' => $post->id]), [ 'published' => true, 'title' => 'Santa is coming home', 'slug' => 'santa-is-coming-home', 'body' => $post->body, 'excerpt' => 'This is an excerpt.', 'author_id' => [$post->author_id], ]) ->assertOk() ->assertJsonStructure(['data', 'saved']); $post->refresh(); $this->assertEquals($post->title, 'Santa is coming home'); } #[Test] public function can_update_resource_with_nested_field() { $post = Post::factory()->create(); $user = User::make()->makeSuper()->save(); $this ->actingAs($user) ->patch(cp_route('runway.update', ['resource' => 'post', 'model' => $post->id]), [ 'published' => true, 'title' => 'Santa is coming home', 'slug' => 'santa-is-coming-home', 'body' => $post->body, 'values_alt_title' => 'Claus is venturing out', 'author_id' => [$post->author_id], ]) ->assertOk() ->assertJsonStructure(['data', 'saved']); $post->refresh(); $this->assertEquals($post->values['alt_title'], 'Claus is venturing out'); } #[Test] public function can_update_resource_if_model_is_user_model() { Config::set('auth.providers.users.model', UserModel::class); $user = UserModel::create([ 'name' => 'John Doe', 'email' => 'john.doe@example.com', ]); UserGroup::make('admins')->title('Admins')->save(); Role::make('developer')->title('Developer')->save(); $this ->actingAs(User::make()->makeSuper()->save()) ->patch(cp_route('runway.update', ['resource' => 'user', 'model' => $user->id]), [ 'name' => 'Jane Doe', 'email' => 'jane.doe@example.com', 'roles' => ['developer'], 'groups' => ['admins'], ]) ->assertOk() ->assertJsonStructure(['data', 'saved']); $user->refresh(); $this->assertEquals($user->name, 'Jane Doe'); $this->assertDatabaseHas('role_user', [ 'user_id' => $user->id, 'role_id' => 'developer', ]); $this->assertDatabaseHas('group_user', [ 'user_id' => $user->id, 'group_id' => 'admins', ]); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/Http/Controllers/CP/RestoreModelRevisionController.php
tests/Http/Controllers/CP/RestoreModelRevisionController.php
<?php namespace StatamicRadPack\Runway\Tests\Http\Controllers\CP; use PHPUnit\Framework\Attributes\Test; use Statamic\Facades\Folder; use Statamic\Facades\User; use StatamicRadPack\Runway\Tests\Fixtures\Models\Post; use StatamicRadPack\Runway\Tests\TestCase; class RestoreModelRevisionController extends TestCase { private $dir; protected function setUp(): void { parent::setUp(); $this->dir = __DIR__.'/tmp'; config(['statamic.revisions.enabled' => true]); config(['statamic.revisions.path' => $this->dir]); } protected function tearDown(): void { Folder::delete($this->dir); parent::tearDown(); } #[Test] public function it_restores_revision() { $model = Post::factory()->create(['title' => 'Some new title']); $revision = $model->makeRevision() ->message('The revision') ->attributes([ 'id' => $model->id, 'published' => true, 'data' => collect($model->getAttributes())->merge([ 'title' => 'Original title', ])->all(), ]); $revision->save(); $this ->actingAs(User::make()->id('user-1')->makeSuper()->save()) ->post($model->runwayRestoreRevisionUrl(), ['revision' => $revision->id()]) ->assertOk() ->assertSessionHas('success'); $workingCopy = $model->workingCopy(); $this->assertEquals($model->id, $workingCopy->attributes()['id']); $this->assertEquals('Original title', $workingCopy->attributes()['data']['title']); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/Http/Controllers/CP/ResourceListingControllerTest.php
tests/Http/Controllers/CP/ResourceListingControllerTest.php
<?php namespace StatamicRadPack\Runway\Tests\Http\Controllers\CP; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Support\Facades\Config; use PHPUnit\Framework\Attributes\Test; use Statamic\Facades\Blink; use Statamic\Facades\User; use StatamicRadPack\Runway\Runway; use StatamicRadPack\Runway\Tests\Fixtures\Enums\MembershipStatus; use StatamicRadPack\Runway\Tests\Fixtures\Models\Author; use StatamicRadPack\Runway\Tests\Fixtures\Models\Post; use StatamicRadPack\Runway\Tests\TestCase; class ResourceListingControllerTest extends TestCase { use RefreshDatabase, WithFaker; #[Test] public function user_with_no_permissions_cannot_access_resource_listing() { $this ->actingAs(User::make()->save()) ->get(cp_route('runway.listing-api', ['resource' => 'post'])) ->assertRedirect(); } #[Test] public function can_sort_listing_rows() { $user = User::make()->makeSuper()->save(); $posts = Post::factory()->count(2)->create(); $this ->actingAs($user) ->get(cp_route('runway.listing-api', ['resource' => 'post'])) ->assertOk() ->assertJson([ 'data' => [ [ 'title' => $posts[0]->title, 'edit_url' => "http://localhost/cp/runway/post/{$posts[0]->id}", 'id' => $posts[0]->id, ], [ 'title' => $posts[1]->title, 'edit_url' => "http://localhost/cp/runway/post/{$posts[1]->id}", 'id' => $posts[1]->id, ], ], ]); } #[Test] public function listing_rows_are_ordered_as_per_config() { Config::set('runway.resources.StatamicRadPack\Runway\Tests\Fixtures\Models\Post.order_by', 'id'); Config::set('runway.resources.StatamicRadPack\Runway\Tests\Fixtures\Models\Post.order_by_direction', 'desc'); Runway::discoverResources(); $user = User::make()->makeSuper()->save(); $posts = Post::factory()->count(2)->create(); $this ->actingAs($user) ->get(cp_route('runway.listing-api', ['resource' => 'post'])) ->assertOk() ->assertJson([ 'data' => [ [ 'title' => $posts[1]->title, 'edit_url' => "http://localhost/cp/runway/post/{$posts[1]->id}", 'id' => $posts[1]->id, ], [ 'title' => $posts[0]->title, 'edit_url' => "http://localhost/cp/runway/post/{$posts[0]->id}", 'id' => $posts[0]->id, ], ], ]); } #[Test] public function listing_rows_are_ordered_from_runway_listing_scope() { $user = User::make()->makeSuper()->save(); $posts = Post::factory()->count(2)->create(); Blink::put('RunwayListingScopeOrderBy', ['id', 'desc']); $this ->actingAs($user) ->get(cp_route('runway.listing-api', ['resource' => 'post'])) ->assertOk() ->assertJson([ 'data' => [ [ 'title' => $posts[1]->title, 'edit_url' => "http://localhost/cp/runway/post/{$posts[1]->id}", 'id' => $posts[1]->id, ], [ 'title' => $posts[0]->title, 'edit_url' => "http://localhost/cp/runway/post/{$posts[0]->id}", 'id' => $posts[0]->id, ], ], ]); } #[Test] public function listing_rows_arent_ordered_from_runway_listing_scope_when_user_defines_an_order() { $user = User::make()->makeSuper()->save(); $posts = Post::factory()->count(2)->create(); Blink::put('RunwayListingScopeOrderBy', ['id', 'desc']); $this ->actingAs($user) ->get(cp_route('runway.listing-api', ['resource' => 'post', 'sort' => 'id', 'order' => 'asc'])) ->assertOk() ->assertJson([ 'data' => [ [ 'title' => $posts[0]->title, 'edit_url' => "http://localhost/cp/runway/post/{$posts[0]->id}", 'id' => $posts[0]->id, ], [ 'title' => $posts[1]->title, 'edit_url' => "http://localhost/cp/runway/post/{$posts[1]->id}", 'id' => $posts[1]->id, ], ], ]); } #[Test] public function listing_rows_are_ordered_when_user_defines_an_order_and_no_runway_listing_scope_order_exists() { $user = User::make()->makeSuper()->save(); $posts = Post::factory()->count(2)->create(); $this ->actingAs($user) ->get(cp_route('runway.listing-api', ['resource' => 'post', 'sort' => 'id', 'order' => 'desc'])) ->assertOk() ->assertJson([ 'data' => [ [ 'title' => $posts[1]->title, 'edit_url' => "http://localhost/cp/runway/post/{$posts[1]->id}", 'id' => $posts[1]->id, ], [ 'title' => $posts[0]->title, 'edit_url' => "http://localhost/cp/runway/post/{$posts[0]->id}", 'id' => $posts[0]->id, ], ], ]); } #[Test] public function listing_rows_can_be_ordered_by_nested_field() { $user = User::make()->makeSuper()->save(); $posts = Post::factory()->count(2)->create(); $posts[0]->update(['values' => ['alt_title' => 'Banana Split']]); $posts[1]->update(['values' => ['alt_title' => 'Apple Pie']]); $this ->actingAs($user) ->get(cp_route('runway.listing-api', ['resource' => 'post', 'sort' => 'values_alt_title', 'order' => 'asc'])) ->assertOk() ->assertJson([ 'data' => [ [ 'title' => $posts[1]->title, 'edit_url' => "http://localhost/cp/runway/post/{$posts[1]->id}", 'id' => $posts[1]->id, ], [ 'title' => $posts[0]->title, 'edit_url' => "http://localhost/cp/runway/post/{$posts[0]->id}", 'id' => $posts[0]->id, ], ], ]); } #[Test] public function can_search() { $user = User::make()->makeSuper()->save(); $posts = Post::factory()->count(2)->create(); $posts[0]->update(['title' => 'Apple Pie']); $this ->actingAs($user) ->get(cp_route('runway.listing-api', ['resource' => 'post', 'search' => 'Apple'])) ->assertOk() ->assertJson([ 'data' => [ [ 'title' => $posts[0]->title, 'edit_url' => "http://localhost/cp/runway/post/{$posts[0]->id}", 'id' => $posts[0]->id, ], ], ]); } #[Test] public function can_search_models_with_has_many_relationship() { $user = User::make()->makeSuper()->save(); $author = Author::factory()->withPosts()->create(['name' => 'Colin The Caterpillar']); $this ->actingAs($user) ->get(cp_route('runway.listing-api', [ 'resource' => 'author', 'search' => 'Colin', 'columns' => 'name,posts', ])) ->assertOk() ->assertJson([ 'data' => [ [ 'name' => 'Colin The Caterpillar', 'edit_url' => "http://localhost/cp/runway/author/{$author->id}", 'id' => $author->id, ], ], ]); } #[Test] public function can_search_using_a_search_index() { Config::set('statamic.search.indexes.test_search_index', [ 'driver' => 'local', 'searchables' => ['runway:post'], 'fields' => ['title', 'slug'], ]); Config::set('runway.resources.StatamicRadPack\Runway\Tests\Fixtures\Models\Post.search_index', 'test_search_index'); Runway::discoverResources(); $user = User::make()->makeSuper()->save(); $posts = Post::factory()->count(2)->create(); $posts[0]->update(['title' => 'Apple Pie']); $this ->actingAs($user) ->get(cp_route('runway.listing-api', ['resource' => 'post', 'search' => 'Apple'])) ->assertOk() ->assertJson([ 'data' => [ [ 'title' => $posts[0]->title, 'edit_url' => "http://localhost/cp/runway/post/{$posts[0]->id}", 'id' => $posts[0]->id, ], ], ]); } #[Test] public function can_paginate_results() { Post::factory()->count(15)->create(); $user = User::make()->makeSuper()->save(); $this ->actingAs($user) ->get(cp_route('runway.listing-api', ['resource' => 'post']).'?perPage=5') ->assertOk() ->assertJson([ 'meta' => [ 'per_page' => '5', 'to' => 5, 'total' => 15, ], ]); } #[Test] public function can_get_values_from_nested_fields() { $posts = Post::factory()->count(3)->create([ 'values' => [ 'alt_title' => $this->faker()->words(6, true), ], ]); $user = User::make()->makeSuper()->save(); $this ->actingAs($user) ->get(cp_route('runway.listing-api', ['resource' => 'post']).'?columns=title,values_alt_title') ->assertOk() ->assertSee($posts[0]->values['alt_title']) ->assertSee($posts[1]->values['alt_title']) ->assertSee($posts[2]->values['alt_title']); } #[Test] public function can_get_value_from_enum_column() { Post::factory()->create(['membership_status' => MembershipStatus::Free]); Post::factory()->create(['membership_status' => MembershipStatus::Paid]); $user = User::make()->makeSuper()->save(); $this ->actingAs($user) ->get(cp_route('runway.listing-api', ['resource' => 'post']).'?columns=title,membership_status') ->assertOk() ->assertJsonPath('data.0.membership_status', ['Free']) ->assertJsonPath('data.1.membership_status', ['Paid']); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/Http/Controllers/CP/PublishedModelsControllerTest.php
tests/Http/Controllers/CP/PublishedModelsControllerTest.php
<?php namespace StatamicRadPack\Runway\Tests\Http\Controllers\CP; use PHPUnit\Framework\Attributes\Test; use Statamic\Facades\Folder; use Statamic\Facades\User; use StatamicRadPack\Runway\Tests\Fixtures\Models\Post; use StatamicRadPack\Runway\Tests\TestCase; class PublishedModelsControllerTest extends TestCase { private $dir; protected function setUp(): void { parent::setUp(); $this->dir = __DIR__.'/tmp'; config(['statamic.revisions.enabled' => true]); config(['statamic.revisions.path' => $this->dir]); } protected function tearDown(): void { Folder::delete($this->dir); parent::tearDown(); } #[Test] public function can_publish_a_model() { $model = Post::factory()->unpublished()->create(); $this ->actingAs(User::make()->makeSuper()->save()) ->post($model->runwayPublishUrl(), [ 'message' => 'Live live live!', ]) ->assertJsonStructure([ 'data' => [ 'id', 'reference', 'title', 'published', ], ]); $this->assertTrue($model->fresh()->published()); } #[Test] public function can_unpublish_a_model() { $model = Post::factory()->create(); $this ->actingAs(User::make()->makeSuper()->save()) ->post($model->runwayUnpublishUrl(), [ 'message' => 'Live live live!', ]) ->assertJsonStructure([ 'data' => [ 'id', 'reference', 'title', 'published', ], ]); $this->assertFalse($model->fresh()->published()); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/UpdateScripts/ChangePermissionNamesTest.php
tests/UpdateScripts/ChangePermissionNamesTest.php
<?php namespace StatamicRadPack\Runway\Tests\UpdateScripts; use Illuminate\Support\Facades\File; use PHPUnit\Framework\Attributes\Test; use StatamicRadPack\Runway\Tests\TestCase; use StatamicRadPack\Runway\UpdateScripts\ChangePermissionNames; class ChangePermissionNamesTest extends TestCase { use RunsUpdateScripts; #[Test] public function it_can_change_permission_names() { File::ensureDirectoryExists(resource_path('users')); File::put( config('statamic.users.repositories.file.paths.roles'), File::get(__DIR__.'/../__fixtures__/resources/users/roles.yaml') ); $this->runUpdateScript(ChangePermissionNames::class); $roles = File::get(config('statamic.users.repositories.file.paths.roles')); $this->assertStringContainsString('view post', $roles); $this->assertStringNotContainsString('View Posts', $roles); $this->assertStringContainsString('edit post', $roles); $this->assertStringNotContainsString('Edit Posts', $roles); $this->assertStringContainsString('create post', $roles); $this->assertStringNotContainsString('Create new Post', $roles); $this->assertStringContainsString('delete post', $roles); $this->assertStringNotContainsString('Delete Post', $roles); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/UpdateScripts/RunsUpdateScripts.php
tests/UpdateScripts/RunsUpdateScripts.php
<?php namespace StatamicRadPack\Runway\Tests\UpdateScripts; trait RunsUpdateScripts { /** * Run update script in your tests without checking package version. * * @param string $fqcn * @param string $package */ protected function runUpdateScript($fqcn, $package = 'statamic-rad-pack/runway') { $script = new $fqcn($package); $script->update(); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/UpdateScripts/AddManagePublishStatesPermissionTest.php
tests/UpdateScripts/AddManagePublishStatesPermissionTest.php
<?php namespace StatamicRadPack\Runway\Tests\UpdateScripts; use PHPUnit\Framework\Attributes\Test; use Statamic\Facades\Role; use StatamicRadPack\Runway\Tests\TestCase; use StatamicRadPack\Runway\UpdateScripts\AddManagePublishStatesPermission; class AddManagePublishStatesPermissionTest extends TestCase { use RunsUpdateScripts; #[Test] public function publish_permission_is_added_to_role_with_create_permission() { Role::make('test') ->addPermission('view post') ->addPermission('create post') ->save(); $this->runUpdateScript(AddManagePublishStatesPermission::class); $this->assertEquals([ 'view post', 'create post', 'publish post', ], Role::find('test')->permissions()->all()); } #[Test] public function publish_permission_is_not_added_to_role_without_create_permission() { Role::make('test') ->addPermission('view post') ->save(); $this->runUpdateScript(AddManagePublishStatesPermission::class); $this->assertEquals([ 'view post', ], Role::find('test')->permissions()->all()); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/Actions/DeleteModelTest.php
tests/Actions/DeleteModelTest.php
<?php namespace StatamicRadPack\Runway\Tests\Actions; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Config; use PHPUnit\Framework\Attributes\Test; use Statamic\Facades\Collection; use Statamic\Facades\Entry; use Statamic\Facades\Role; use Statamic\Facades\User; use Statamic\Testing\Concerns\PreventsSavingStacheItemsToDisk; use StatamicRadPack\Runway\Actions\DeleteModel; use StatamicRadPack\Runway\Runway; use StatamicRadPack\Runway\Tests\Fixtures\Models\Post; use StatamicRadPack\Runway\Tests\TestCase; class DeleteModelTest extends TestCase { use PreventsSavingStacheItemsToDisk; #[Test] public function it_returns_title() { $this->assertEquals('Delete', DeleteModel::title()); } #[Test] public function is_visible_to_eloquent_model() { $visibleTo = (new DeleteModel)->visibleTo(Post::factory()->create()); $this->assertTrue($visibleTo); } #[Test] public function is_not_visible_to_eloquent_model_when_resource_is_read_only() { Config::set('runway.resources.StatamicRadPack\Runway\Tests\Fixtures\Models\Post.read_only', true); Runway::discoverResources(); $visibleTo = (new DeleteModel)->visibleTo(Post::factory()->create()); $this->assertFalse($visibleTo); } #[Test] public function is_not_visible_to_eloquent_model_without_a_runway_resource() { $model = new class extends Model { protected $table = 'posts'; }; $visibleTo = (new DeleteModel)->visibleTo(new $model); $this->assertFalse($visibleTo); } #[Test] public function is_not_visible_to_entry() { Collection::make('posts')->save(); $visibleTo = (new DeleteModel)->visibleTo( tap(Entry::make()->collection('posts')->slug('hello-world'))->save() ); $this->assertFalse($visibleTo); } #[Test] public function is_visible_to_eloquent_models_in_bulk() { $posts = Post::factory()->count(3)->create(); $visibleToBulk = (new DeleteModel)->visibleToBulk($posts); $this->assertTrue($visibleToBulk); } #[Test] public function is_not_visible_to_entries_in_bulk() { Collection::make('posts')->save(); $entries = collect([ tap(Entry::make()->collection('posts')->slug('hello-world'))->save(), tap(Entry::make()->collection('posts')->slug('foo-bar'))->save(), tap(Entry::make()->collection('posts')->slug('bye-bye'))->save(), ]); $visibleToBulk = (new DeleteModel)->visibleToBulk($entries); $this->assertFalse($visibleToBulk); } #[Test] public function super_user_is_authorized() { $user = User::make()->makeSuper()->save(); $authorize = (new DeleteModel)->authorize($user, Post::factory()->create()); $this->assertTrue($authorize); } #[Test] public function user_with_permission_is_authorized() { Role::make('editor')->addPermission('delete post')->save(); $user = User::make()->assignRole('editor')->save(); $authorize = (new DeleteModel)->authorize($user, Post::factory()->create()); $this->assertTrue($authorize); Role::find('editor')->delete(); } #[Test] public function user_without_permission_is_not_authorized() { $user = User::make()->save(); $authorize = (new DeleteModel)->authorize($user, Post::factory()->create()); $this->assertFalse($authorize); } #[Test] public function it_deletes_models() { $posts = Post::factory()->count(5)->create(); $this->assertCount(5, Post::all()); (new DeleteModel)->run($posts, []); $this->assertCount(0, Post::all()); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/Actions/UnpublishTest.php
tests/Actions/UnpublishTest.php
<?php namespace StatamicRadPack\Runway\Tests\Actions; use Illuminate\Support\Facades\Config; use PHPUnit\Framework\Attributes\Test; use Statamic\Facades\Collection; use Statamic\Facades\Entry; use Statamic\Facades\Role; use Statamic\Facades\User; use Statamic\Testing\Concerns\PreventsSavingStacheItemsToDisk; use StatamicRadPack\Runway\Actions\Unpublish; use StatamicRadPack\Runway\Runway; use StatamicRadPack\Runway\Tests\Fixtures\Models\Post; use StatamicRadPack\Runway\Tests\TestCase; class UnpublishTest extends TestCase { use PreventsSavingStacheItemsToDisk; #[Test] public function it_returns_title() { $this->assertEquals('Unpublish', Unpublish::title()); } #[Test] public function is_visible_to_eloquent_model() { $visibleTo = (new Unpublish)->context([])->visibleTo(Post::factory()->create()); $this->assertTrue($visibleTo); } #[Test] public function is_not_visible_to_unpublished_eloquent_model() { $visibleTo = (new Unpublish)->context([])->visibleTo(Post::factory()->unpublished()->create()); $this->assertFalse($visibleTo); } #[Test] public function is_not_visible_to_eloquent_model_when_resource_is_read_only() { Config::set('runway.resources.StatamicRadPack\Runway\Tests\Fixtures\Models\Post.read_only', true); Runway::discoverResources(); $visibleTo = (new Unpublish)->context([])->visibleTo(Post::factory()->create()); $this->assertFalse($visibleTo); } #[Test] public function is_not_visible_to_entry() { Collection::make('posts')->save(); $visibleTo = (new Unpublish)->context([])->visibleTo( tap(Entry::make()->collection('posts')->slug('hello-world'))->save() ); $this->assertFalse($visibleTo); } #[Test] public function is_not_visible_in_bulk_to_entry() { Collection::make('posts')->save(); Entry::make()->collection('posts')->slug('hello-world')->save(); $visibleTo = (new Unpublish)->context([])->visibleToBulk(Entry::all()); $this->assertFalse($visibleTo); } #[Test] public function is_visible_to_eloquent_models_in_bulk() { $posts = Post::factory()->count(3)->create(); $visibleToBulk = (new Unpublish)->context([])->visibleToBulk($posts); $this->assertTrue($visibleToBulk); } #[Test] public function is_not_visible_to_eloquent_models_in_bulk_when_not_all_models_are_published() { $posts = Post::factory()->count(3)->create(); $posts->first()->update(['published' => false]); $visibleToBulk = (new Unpublish)->context([])->visibleToBulk($posts); $this->assertFalse($visibleToBulk); } #[Test] public function super_user_is_authorized() { $user = User::make()->makeSuper()->save(); $authorize = (new Unpublish)->authorize($user, Post::factory()->create()); $this->assertTrue($authorize); } #[Test] public function user_with_permission_is_authorized() { Role::make('editor')->addPermission('publish post')->save(); $user = User::make()->assignRole('editor')->save(); $authorize = (new Unpublish)->authorize($user, Post::factory()->create()); $this->assertTrue($authorize); Role::find('editor')->delete(); } #[Test] public function user_without_permission_is_not_authorized() { $user = User::make()->save(); $authorize = (new Unpublish)->authorize($user, Post::factory()->create()); $this->assertFalse($authorize); } #[Test] public function it_publishes_models() { $posts = Post::factory()->count(5)->create(); $posts->each(fn (Post $post) => $this->assertTrue($post->published)); (new Unpublish)->run($posts, []); $posts->each(fn (Post $post) => $this->assertFalse($post->published)); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/Actions/PublishTest.php
tests/Actions/PublishTest.php
<?php namespace StatamicRadPack\Runway\Tests\Actions; use Illuminate\Support\Facades\Config; use PHPUnit\Framework\Attributes\Test; use Statamic\Facades\Collection; use Statamic\Facades\Entry; use Statamic\Facades\Role; use Statamic\Facades\User; use Statamic\Testing\Concerns\PreventsSavingStacheItemsToDisk; use StatamicRadPack\Runway\Actions\Publish; use StatamicRadPack\Runway\Runway; use StatamicRadPack\Runway\Tests\Fixtures\Models\Post; use StatamicRadPack\Runway\Tests\TestCase; class PublishTest extends TestCase { use PreventsSavingStacheItemsToDisk; #[Test] public function it_returns_title() { $this->assertEquals('Publish', Publish::title()); } #[Test] public function is_visible_to_eloquent_model() { $visibleTo = (new Publish)->context([])->visibleTo(Post::factory()->unpublished()->create()); $this->assertTrue($visibleTo); } #[Test] public function is_not_visible_to_published_eloquent_model() { $visibleTo = (new Publish)->context([])->visibleTo(Post::factory()->create()); $this->assertFalse($visibleTo); } #[Test] public function is_not_visible_to_eloquent_model_when_resource_is_read_only() { Config::set('runway.resources.StatamicRadPack\Runway\Tests\Fixtures\Models\Post.read_only', true); Runway::discoverResources(); $visibleTo = (new Publish)->context([])->visibleTo(Post::factory()->unpublished()->create()); $this->assertFalse($visibleTo); } #[Test] public function is_not_visible_to_entry() { Collection::make('posts')->save(); $visibleTo = (new Publish)->context([])->visibleTo( tap(Entry::make()->collection('posts')->slug('hello-world'))->save() ); $this->assertFalse($visibleTo); } #[Test] public function is_visible_to_eloquent_models_in_bulk() { $posts = Post::factory()->count(3)->unpublished()->create(); $visibleToBulk = (new Publish)->context([])->visibleToBulk($posts); $this->assertTrue($visibleToBulk); } #[Test] public function is_not_visible_in_bulk_to_entry() { Collection::make('posts')->save(); Entry::make()->collection('posts')->slug('hello-world')->save(); $visibleTo = (new Publish)->context([])->visibleToBulk(Entry::all()); $this->assertFalse($visibleTo); } #[Test] public function is_not_visible_to_eloquent_models_in_bulk_when_not_all_models_are_unpublished() { $posts = Post::factory()->count(3)->unpublished()->create(); $posts->first()->update(['published' => true]); $visibleToBulk = (new Publish)->context([])->visibleToBulk($posts); $this->assertFalse($visibleToBulk); } #[Test] public function super_user_is_authorized() { $user = User::make()->makeSuper()->save(); $authorize = (new Publish)->authorize($user, Post::factory()->create()); $this->assertTrue($authorize); } #[Test] public function user_with_permission_is_authorized() { Role::make('editor')->addPermission('publish post')->save(); $user = User::make()->assignRole('editor')->save(); $authorize = (new Publish)->authorize($user, Post::factory()->create()); $this->assertTrue($authorize); Role::find('editor')->delete(); } #[Test] public function user_without_permission_is_not_authorized() { $user = User::make()->save(); $authorize = (new Publish)->authorize($user, Post::factory()->create()); $this->assertFalse($authorize); } #[Test] public function it_publishes_models() { $posts = Post::factory()->count(5)->unpublished()->create(); $posts->each(fn (Post $post) => $this->assertFalse($post->published)); (new Publish)->run($posts, []); $posts->each(fn (Post $post) => $this->assertTrue($post->published)); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/Actions/DuplicateModelTest.php
tests/Actions/DuplicateModelTest.php
<?php namespace StatamicRadPack\Runway\Tests\Actions; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Config; use PHPUnit\Framework\Attributes\Test; use Statamic\Facades\Blueprint; use Statamic\Facades\Collection; use Statamic\Facades\Entry; use Statamic\Facades\Role; use Statamic\Facades\User; use Statamic\Testing\Concerns\PreventsSavingStacheItemsToDisk; use StatamicRadPack\Runway\Actions\DuplicateModel; use StatamicRadPack\Runway\Runway; use StatamicRadPack\Runway\Tests\Fixtures\Models\Post; use StatamicRadPack\Runway\Tests\TestCase; class DuplicateModelTest extends TestCase { use PreventsSavingStacheItemsToDisk; #[Test] public function it_returns_title() { $this->assertEquals('Duplicate', DuplicateModel::title()); } #[Test] public function is_visible_to_eloquent_model() { $visibleTo = (new DuplicateModel)->visibleTo(Post::factory()->create()); $this->assertTrue($visibleTo); } #[Test] public function is_not_visible_to_eloquent_model_when_resource_is_read_only() { Config::set('runway.resources.StatamicRadPack\Runway\Tests\Fixtures\Models\Post.read_only', true); Runway::discoverResources(); $visibleTo = (new DuplicateModel)->visibleTo(Post::factory()->create()); $this->assertFalse($visibleTo); } #[Test] public function is_not_visible_to_eloquent_model_when_blueprint_is_hidden() { $blueprint = Blueprint::find('runway::post'); Blueprint::shouldReceive('find')->with('runway::post')->andReturn($blueprint->setHidden(true)); $visibleTo = (new DuplicateModel)->visibleTo(Post::factory()->create()); $this->assertFalse($visibleTo); } #[Test] public function is_not_visible_to_eloquent_model_without_a_runway_resource() { $model = new class extends Model { protected $table = 'posts'; }; $visibleTo = (new DuplicateModel)->visibleTo(new $model); $this->assertFalse($visibleTo); } #[Test] public function is_not_visible_to_an_entry() { Collection::make('posts')->save(); $visibleTo = (new DuplicateModel)->visibleTo( tap(Entry::make()->collection('posts')->slug('hello-world'))->save() ); $this->assertFalse($visibleTo); } #[Test] public function is_visible_to_eloquent_models_in_bulk() { $posts = Post::factory()->count(3)->create(); $visibleToBulk = (new DuplicateModel)->visibleToBulk($posts); $this->assertTrue($visibleToBulk); } #[Test] public function is_not_visible_to_entries_in_bulk() { Collection::make('posts')->save(); $entries = collect([ tap(Entry::make()->collection('posts')->slug('hello-world'))->save(), tap(Entry::make()->collection('posts')->slug('foo-bar'))->save(), tap(Entry::make()->collection('posts')->slug('bye-bye'))->save(), ]); $visibleToBulk = (new DuplicateModel)->visibleToBulk($entries); $this->assertFalse($visibleToBulk); } #[Test] public function super_user_is_authorized() { $user = User::make()->makeSuper()->save(); $authorize = (new DuplicateModel)->authorize($user, Post::factory()->create()); $this->assertTrue($authorize); } #[Test] public function user_with_permission_is_authorized() { Role::make('editor')->addPermission('create post')->save(); $user = User::make()->assignRole('editor')->save(); $authorize = (new DuplicateModel)->authorize($user, Post::factory()->create()); $this->assertTrue($authorize); Role::find('editor')->delete(); } #[Test] public function user_without_permission_is_not_authorized() { $user = User::make()->save(); $authorize = (new DuplicateModel)->authorize($user, Post::factory()->create()); $this->assertFalse($authorize); } #[Test] public function it_duplicates_models() { $post = Post::factory()->create(['title' => 'Hello World']); $this->assertCount(1, Post::where('title', 'like', 'Hello World%')->get()); (new DuplicateModel)->run(collect([$post]), []); $this->assertCount(2, Post::where('title', 'like', 'Hello World%')->get()); $duplicate = Post::query()->whereNot('id', $post->id)->first(); $this->assertEquals('Hello World (Duplicate)', $duplicate->title); $this->assertNotNull($duplicate->start_date); $this->assertFalse($duplicate->published()); } #[Test] public function only_duplicates_fields_where_duplication_is_enabled() { $blueprint = Blueprint::find('runway::post'); $blueprint->ensureFieldHasConfig('start_date', ['duplicate' => false]); Blueprint::shouldReceive('find') ->with('runway::post') ->andReturn($blueprint); $post = Post::factory()->create(['title' => 'Hello World', 'start_date' => now()]); (new DuplicateModel)->run(collect([$post]), []); $duplicate = Post::query()->whereNot('id', $post->id)->first(); $this->assertEquals('Hello World (Duplicate)', $duplicate->title); $this->assertNull($duplicate->start_date); $this->assertFalse($duplicate->published()); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/Query/Scopes/Filters/ModelsTest.php
tests/Query/Scopes/Filters/ModelsTest.php
<?php namespace StatamicRadPack\Runway\Tests\Query\Scopes\Filters; use PHPUnit\Framework\Attributes\Test; use Statamic\Fields\Field; use StatamicRadPack\Runway\Fieldtypes\BelongsToFieldtype; use StatamicRadPack\Runway\Scopes\Fields\Models; use StatamicRadPack\Runway\Tests\Fixtures\Models\Author; use StatamicRadPack\Runway\Tests\Fixtures\Models\Post; use StatamicRadPack\Runway\Tests\TestCase; class ModelsTest extends TestCase { #[Test] public function it_gets_field_items() { $fieldtype = new BelongsToFieldtype; $fieldtype->setField(new Field('author', ['resource' => 'post'])); $fieldItems = (new Models($fieldtype))->fieldItems(); $this->assertIsArray($fieldItems); $this->assertArrayHasKey('field', $fieldItems); $this->assertArrayHasKey('operator', $fieldItems); $this->assertArrayHasKey('value', $fieldItems); $this->assertEquals([ 'id' => 'ID', 'title' => 'Title', ], $fieldItems['field']['options']); } #[Test] public function can_apply_filter_on_normal_column() { Post::factory()->count(5)->create(); $author = Author::factory()->withPosts(3)->create(['name' => 'David Hasselhoff']); $fieldtype = new BelongsToFieldtype; $fieldtype->setField(new Field('author_id', ['resource' => 'author'])); $query = Post::query(); $apply = (new Models($fieldtype))->apply( $query, 'author_id', [ 'field' => 'name', 'operator' => 'like', 'value' => 'Hasselhoff', ] ); $results = $query->get(); $this->assertCount(3, $results); $this->assertEquals($author->id, $results[0]->author_id); $this->assertEquals($author->id, $results[1]->author_id); $this->assertEquals($author->id, $results[2]->author_id); } #[Test] public function can_get_badge() { $fieldtype = new BelongsToFieldtype; $fieldtype->setField(new Field('author_id', ['resource' => 'author'])); $badge = (new Models($fieldtype))->badge([ 'field' => 'name', 'operator' => 'like', 'value' => 'Hasselhoff', ]); $this->assertEquals('Author Id Name contains Hasselhoff', $badge); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/Fieldtypes/HasManyFieldtypeTest.php
tests/Fieldtypes/HasManyFieldtypeTest.php
<?php namespace StatamicRadPack\Runway\Tests\Fieldtypes; use Illuminate\Contracts\Pagination\Paginator; use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Schema; use PHPUnit\Framework\Attributes\Test; use Statamic\Facades\Blink; use Statamic\Facades\Entry; use Statamic\Fields\Field; use Statamic\Http\Requests\FilteredRequest; use Statamic\Testing\Concerns\PreventsSavingStacheItemsToDisk; use StatamicRadPack\Runway\Fieldtypes\HasManyFieldtype; use StatamicRadPack\Runway\Runway; use StatamicRadPack\Runway\Tests\Fixtures\Models\Author; use StatamicRadPack\Runway\Tests\Fixtures\Models\Post; use StatamicRadPack\Runway\Tests\TestCase; class HasManyFieldtypeTest extends TestCase { use PreventsSavingStacheItemsToDisk, WithFaker; protected HasManyFieldtype $fieldtype; protected function setUp(): void { parent::setUp(); $this->fieldtype = tap(new HasManyFieldtype) ->setField(new Field('posts', [ 'mode' => 'stack', 'resource' => 'post', 'display' => 'Posts', 'type' => 'has_many', ])); } #[Test] public function unlink_behavior_is_unlink_when_relationship_column_is_nullable() { Schema::shouldReceive('getColumns')->with('posts')->andReturn([ ['name' => 'author_id', 'type' => 'integer', 'nullable' => true], ]); Schema::shouldIgnoreMissing(); $author = Author::factory()->create(); $field = new Field('posts', [ 'mode' => 'stack', 'resource' => 'post', 'display' => 'Posts', 'type' => 'has_many', ]); $field->setParent($author); $fieldtype = new HasManyFieldtype; $fieldtype->setField($field); $this->assertEquals('unlink', $fieldtype->preload()['unlinkBehavior']); } #[Test] public function unlink_behavior_is_delete_when_relationship_column_is_not_nullable() { Schema::shouldReceive('getColumns')->with('posts')->andReturn([ ['name' => 'author_id', 'type' => 'integer', 'nullable' => false], ]); Schema::shouldIgnoreMissing(); $author = Author::factory()->create(); $field = new Field('posts', [ 'mode' => 'stack', 'resource' => 'post', 'display' => 'Posts', 'type' => 'has_many', ]); $field->setParent($author); $fieldtype = new HasManyFieldtype; $fieldtype->setField($field); $this->assertEquals('delete', $fieldtype->preload()['unlinkBehavior']); } #[Test] public function unlink_behavior_is_unlink_when_field_is_used_on_entry() { \Statamic\Facades\Collection::make('pages')->save(); $field = new Field('posts', [ 'mode' => 'stack', 'resource' => 'post', 'display' => 'Posts', 'type' => 'has_many', ]); $field->setParent(Entry::make()->collection('pages')); $fieldtype = new HasManyFieldtype; $fieldtype->setField($field); $this->assertEquals('unlink', $fieldtype->preload()['unlinkBehavior']); } #[Test] public function can_get_index_items() { $author = Author::factory()->create(); Post::factory()->count(10)->create(['author_id' => $author->id]); $getIndexItemsWithPagination = $this->fieldtype->getIndexItems( new FilteredRequest(['paginate' => true]) ); $getIndexItemsWithoutPagination = $this->fieldtype->getIndexItems( new FilteredRequest(['paginate' => false]) ); $this->assertIsObject($getIndexItemsWithPagination); $this->assertTrue($getIndexItemsWithPagination instanceof Paginator); $this->assertEquals($getIndexItemsWithPagination->count(), 10); $this->assertIsObject($getIndexItemsWithoutPagination); $this->assertTrue($getIndexItemsWithoutPagination instanceof Collection); $this->assertEquals($getIndexItemsWithoutPagination->count(), 10); } #[Test] public function can_get_index_items_in_order_specified_in_runway_config() { Config::set('runway.resources.StatamicRadPack\Runway\Tests\Fixtures\Models\Post.order_by', 'title'); Config::set('runway.resources.StatamicRadPack\Runway\Tests\Fixtures\Models\Post.order_by_direction', 'asc'); Runway::discoverResources(); Post::factory()->create(['title' => 'Arnold A']); Post::factory()->create(['title' => 'Richard B']); Post::factory()->create(['title' => 'Graham C']); $getIndexItems = $this->fieldtype->getIndexItems(new FilteredRequest(['paginate' => false])); $this->assertIsObject($getIndexItems); $this->assertTrue($getIndexItems instanceof Collection); $this->assertEquals($getIndexItems->count(), 3); $this->assertEquals($getIndexItems->all()[0]['title'], 'Arnold A'); $this->assertEquals($getIndexItems->all()[1]['title'], 'Graham C'); $this->assertEquals($getIndexItems->all()[2]['title'], 'Richard B'); } #[Test] public function can_get_index_items_in_order_from_runway_listing_scope() { Post::factory()->create(['title' => 'Arnold A']); Post::factory()->create(['title' => 'Richard B']); Post::factory()->create(['title' => 'Graham C']); Blink::put('RunwayListingScopeOrderBy', ['title', 'asc']); $getIndexItems = $this->fieldtype->getIndexItems(new FilteredRequest(['paginate' => false])); $this->assertIsObject($getIndexItems); $this->assertTrue($getIndexItems instanceof Collection); $this->assertEquals($getIndexItems->count(), 3); $this->assertEquals($getIndexItems->all()[0]['title'], 'Arnold A'); $this->assertEquals($getIndexItems->all()[1]['title'], 'Graham C'); $this->assertEquals($getIndexItems->all()[2]['title'], 'Richard B'); } #[Test] public function can_get_index_items_in_order_from_runway_listing_scope_when_user_defines_an_order() { Post::factory()->create(['title' => 'Arnold A']); Post::factory()->create(['title' => 'Richard B']); Post::factory()->create(['title' => 'Graham C']); Blink::put('RunwayListingScopeOrderBy', ['title', 'asc']); $getIndexItems = $this->fieldtype->getIndexItems(new FilteredRequest(['paginate' => false, 'sort' => 'title', 'order' => 'desc'])); $this->assertIsObject($getIndexItems); $this->assertTrue($getIndexItems instanceof Collection); $this->assertEquals($getIndexItems->count(), 3); $this->assertEquals($getIndexItems->all()[0]['title'], 'Richard B'); $this->assertEquals($getIndexItems->all()[1]['title'], 'Graham C'); $this->assertEquals($getIndexItems->all()[2]['title'], 'Arnold A'); } #[Test] public function can_get_index_items_and_search() { $author = Author::factory()->create(); Post::factory()->count(10)->create(['author_id' => $author->id]); $spacePandaPosts = Post::factory()->count(3)->create(['author_id' => $author->id, 'title' => 'Space Pandas']); $getIndexItems = $this->fieldtype->getIndexItems( new FilteredRequest(['search' => 'space pan']) ); $this->assertIsObject($getIndexItems); $this->assertTrue($getIndexItems instanceof Paginator); $this->assertEquals($getIndexItems->count(), 3); $this->assertEquals($getIndexItems->first()['title'], $spacePandaPosts[0]->title); $this->assertEquals($getIndexItems->last()['title'], $spacePandaPosts[1]->title); $this->assertEquals($getIndexItems->last()['title'], $spacePandaPosts[2]->title); } #[Test] public function can_get_index_items_and_search_using_a_search_index() { Config::set('statamic.search.indexes.test_search_index', [ 'driver' => 'local', 'searchables' => ['runway:post'], 'fields' => ['title', 'slug'], ]); Config::set('runway.resources.StatamicRadPack\Runway\Tests\Fixtures\Models\Post.search_index', 'test_search_index'); Runway::discoverResources(); $author = Author::factory()->create(); Post::factory()->count(10)->create(['author_id' => $author->id]); $spacePandaPosts = Post::factory()->count(3)->create(['author_id' => $author->id, 'title' => 'Space Pandas']); $getIndexItems = $this->fieldtype->getIndexItems( new FilteredRequest(['search' => 'space pan']) ); $this->assertIsObject($getIndexItems); $this->assertTrue($getIndexItems instanceof Paginator); $this->assertEquals($getIndexItems->count(), 3); $this->assertEquals($getIndexItems->first()['title'], $spacePandaPosts[0]->title); $this->assertEquals($getIndexItems->last()['title'], $spacePandaPosts[1]->title); $this->assertEquals($getIndexItems->last()['title'], $spacePandaPosts[2]->title); } #[Test] public function can_get_item_array_with_title_format() { $author = Author::factory()->create(); $posts = Post::factory()->count(2)->create(['author_id' => $author->id]); $this->fieldtype->setField(new Field('posts', [ 'mode' => 'default', 'resource' => 'post', 'display' => 'Posts', 'type' => 'has_many', 'title_format' => '{{ title }} TEST {{ created_at format="Y" }}', ])); $item = $this->fieldtype->getItemData([$posts[0]->id, $posts[1]->id]); $this->assertEquals($item->first()['title'], $posts[0]->title.' TEST '.now()->format('Y')); $this->assertEquals($item->last()['title'], $posts[1]->title.' TEST '.now()->format('Y')); } #[Test] public function can_get_pre_process_index() { $author = Author::factory()->create(); $posts = Post::factory()->count(10)->create(['author_id' => $author->id]); $preProcessIndex = $this->fieldtype->preProcessIndex($author->posts); $this->assertTrue($preProcessIndex instanceof Collection); $this->assertEquals($preProcessIndex->first(), [ 'id' => $posts[0]->id, 'title' => $posts[0]->title, 'edit_url' => 'http://localhost/cp/runway/post/'.$posts[0]->id, ]); } #[Test] public function can_get_augment_value() { $author = Author::factory()->create(); $posts = Post::factory()->count(5)->create(['author_id' => $author->id]); $augment = $this->fieldtype->augment( $author->posts->pluck('id')->toArray() ); $this->assertIsArray($augment); $this->assertCount(5, $augment); $this->assertEquals($posts[0]->id, $augment[0]['id']->value()); $this->assertEquals($posts[0]->title, (string) $augment[0]['title']->value()); } #[Test] public function can_get_item_data() { // Under the hood, this tests the toItemArray method. $author = Author::factory()->create(); $posts = Post::factory()->count(5)->create(['author_id' => $author->id]); $getItemData = $this->fieldtype->getItemData( $author->posts ); $this->assertIsObject($getItemData); $this->assertTrue($getItemData instanceof Collection); $this->assertArrayHasKey('id', $getItemData[0]); $this->assertArrayHasKey('title', $getItemData[0]); $this->assertArrayNotHasKey('created_at', $getItemData[0]); $this->assertArrayHasKey('id', $getItemData[1]); $this->assertArrayHasKey('title', $getItemData[1]); $this->assertArrayNotHasKey('created_at', $getItemData[1]); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/Fieldtypes/BelongsToFieldtypeTest.php
tests/Fieldtypes/BelongsToFieldtypeTest.php
<?php namespace StatamicRadPack\Runway\Tests\Fieldtypes; use Illuminate\Contracts\Pagination\Paginator; use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Config; use PHPUnit\Framework\Attributes\Test; use Statamic\Facades\Blink; use Statamic\Fields\Field; use Statamic\Http\Requests\FilteredRequest; use StatamicRadPack\Runway\Fieldtypes\BelongsToFieldtype; use StatamicRadPack\Runway\Runway; use StatamicRadPack\Runway\Tests\Fixtures\Models\Author; use StatamicRadPack\Runway\Tests\Fixtures\Scopes\TheHoff; use StatamicRadPack\Runway\Tests\TestCase; class BelongsToFieldtypeTest extends TestCase { use WithFaker; protected BelongsToFieldtype $fieldtype; protected function setUp(): void { parent::setUp(); $this->fieldtype = tap(new BelongsToFieldtype) ->setField(new Field('author', [ 'max_items' => 1, 'mode' => 'stack', 'resource' => 'author', 'display' => 'Author', 'type' => 'belongs_to', ])); } #[Test] public function unlink_behavior_is_unlink() { $this->assertEquals('unlink', $this->fieldtype->preload()['unlinkBehavior']); } #[Test] public function can_get_index_items() { Author::factory()->count(10)->create(); $getIndexItemsWithPagination = $this->fieldtype->getIndexItems( new FilteredRequest(['paginate' => true]) ); $getIndexItemsWithoutPagination = $this->fieldtype->getIndexItems( new FilteredRequest(['paginate' => false]) ); $this->assertIsObject($getIndexItemsWithPagination); $this->assertTrue($getIndexItemsWithPagination instanceof Paginator); $this->assertEquals($getIndexItemsWithPagination->count(), 10); $this->assertIsObject($getIndexItemsWithoutPagination); $this->assertTrue($getIndexItemsWithoutPagination instanceof Collection); $this->assertEquals($getIndexItemsWithoutPagination->count(), 10); } #[Test] public function can_get_index_items_in_order_specified_in_runway_config() { Config::set('runway.resources.StatamicRadPack\Runway\Tests\Fixtures\Models\Author.order_by', 'name'); Config::set('runway.resources.StatamicRadPack\Runway\Tests\Fixtures\Models\Author.order_by_direction', 'desc'); Author::factory()->create(['name' => 'Scully']); Author::factory()->create(['name' => 'Jake Peralta']); Author::factory()->create(['name' => 'Amy Santiago']); $getIndexItems = $this->fieldtype->getIndexItems(new FilteredRequest(['paginate' => false])); $this->assertIsObject($getIndexItems); $this->assertTrue($getIndexItems instanceof Collection); $this->assertEquals($getIndexItems->count(), 3); $this->assertEquals($getIndexItems->all()[0]->name, 'Scully'); $this->assertEquals($getIndexItems->all()[1]->name, 'Jake Peralta'); $this->assertEquals($getIndexItems->all()[2]->name, 'Amy Santiago'); } #[Test] public function can_get_index_items_in_order_from_runway_listing_scope() { Author::factory()->create(['name' => 'Scully']); Author::factory()->create(['name' => 'Jake Peralta']); Author::factory()->create(['name' => 'Amy Santiago']); Blink::put('RunwayListingScopeOrderBy', ['name', 'desc']); $getIndexItems = $this->fieldtype->getIndexItems(new FilteredRequest(['paginate' => false])); $this->assertIsObject($getIndexItems); $this->assertTrue($getIndexItems instanceof Collection); $this->assertEquals($getIndexItems->count(), 3); $this->assertEquals($getIndexItems->all()[0]->name, 'Scully'); $this->assertEquals($getIndexItems->all()[1]->name, 'Jake Peralta'); $this->assertEquals($getIndexItems->all()[2]->name, 'Amy Santiago'); } #[Test] public function can_get_index_items_in_order_from_runway_listing_scope_when_user_defines_an_order() { Author::factory()->create(['name' => 'Scully']); Author::factory()->create(['name' => 'Jake Peralta']); Author::factory()->create(['name' => 'Amy Santiago']); Blink::put('RunwayListingScopeOrderBy', ['name', 'desc']); $getIndexItems = $this->fieldtype->getIndexItems(new FilteredRequest(['paginate' => false, 'sort' => 'name', 'order' => 'asc'])); $this->assertIsObject($getIndexItems); $this->assertTrue($getIndexItems instanceof Collection); $this->assertEquals($getIndexItems->count(), 3); $this->assertEquals($getIndexItems->all()[0]->name, 'Amy Santiago'); $this->assertEquals($getIndexItems->all()[1]->name, 'Jake Peralta'); $this->assertEquals($getIndexItems->all()[2]->name, 'Scully'); } #[Test] public function can_get_index_items_with_query_scopes() { TheHoff::register(); Author::factory()->count(10)->create(); $hasselhoff = Author::factory()->create(['name' => 'David Hasselhoff']); $fieldtype = tap(new BelongsToFieldtype) ->setField(new Field('author', [ 'max_items' => 1, 'mode' => 'stack', 'resource' => 'author', 'display' => 'Author', 'type' => 'belongs_to', 'query_scopes' => ['the_hoff'], ])); $getIndexItems = $fieldtype->getIndexItems( new FilteredRequest(['paginate' => true]) ); $this->assertIsObject($getIndexItems); $this->assertTrue($getIndexItems instanceof Paginator); $this->assertEquals($getIndexItems->count(), 1); $this->assertEquals($getIndexItems->first()['id'], $hasselhoff->id); } #[Test] public function can_get_index_items_and_search() { Author::factory()->count(10)->create(); $hasselhoff = Author::factory()->create(['name' => 'David Hasselhoff']); $getIndexItems = $this->fieldtype->getIndexItems( new FilteredRequest(['search' => 'hasselhoff']) ); $this->assertIsObject($getIndexItems); $this->assertTrue($getIndexItems instanceof Paginator); $this->assertEquals($getIndexItems->count(), 1); $this->assertEquals($getIndexItems->first()['id'], $hasselhoff->id); } #[Test] public function can_get_index_items_and_search_using_a_search_index() { Config::set('statamic.search.indexes.test_search_index', [ 'driver' => 'local', 'searchables' => ['runway:author'], 'fields' => ['name'], ]); Config::set('runway.resources.StatamicRadPack\Runway\Tests\Fixtures\Models\Author.search_index', 'test_search_index'); Runway::discoverResources(); Author::factory()->count(10)->create(); $hasselhoff = Author::factory()->create(['name' => 'David Hasselhoff']); $getIndexItems = $this->fieldtype->getIndexItems( new FilteredRequest(['search' => 'hasselhoff']) ); $this->assertIsObject($getIndexItems); $this->assertTrue($getIndexItems instanceof Paginator); $this->assertEquals($getIndexItems->count(), 1); $this->assertEquals($getIndexItems->first()['id'], $hasselhoff->id); } #[Test] public function can_get_item_array_with_title_format() { $author = Author::factory()->create(); $this->fieldtype->setField(new Field('author', [ 'max_items' => 1, 'mode' => 'default', 'resource' => 'author', 'display' => 'Author', 'type' => 'belongs_to', 'title_format' => 'AUTHOR {{ name }}', ])); $item = $this->fieldtype->getItemData([1]); $this->assertEquals('AUTHOR '.$author->name, $item->first()['title']); } #[Test] public function can_get_pre_process_index() { $author = Author::factory()->create(); $preProcessIndex = $this->fieldtype->preProcessIndex($author); $this->assertTrue($preProcessIndex instanceof Collection); $this->assertEquals($preProcessIndex->first(), [ 'id' => $author->id, 'title' => $author->name, 'edit_url' => 'http://localhost/cp/runway/author/1', ]); } #[Test] public function can_get_pre_process_index_with_model_id() { $author = Author::factory()->create(); $preProcessIndex = $this->fieldtype->preProcessIndex($author->id); $this->assertTrue($preProcessIndex instanceof Collection); $this->assertEquals($preProcessIndex->first(), [ 'id' => $author->id, 'title' => $author->name, 'edit_url' => 'http://localhost/cp/runway/author/1', ]); } #[Test] public function can_get_augment_value() { $author = Author::factory()->create(); $augment = $this->fieldtype->augment($author->id); $this->assertIsArray($augment); $this->assertEquals($author->id, $augment['id']->value()); $this->assertEquals($author->name, $augment['name']->value()); } #[Test] public function can_get_item_data() { // Under the hood, this tests the toItemArray method. $author = Author::factory()->create(); $getItemData = $this->fieldtype->getItemData($author->id); $this->assertIsObject($getItemData); $this->assertTrue($getItemData instanceof Collection); $this->assertArrayHasKey('id', $getItemData[0]); $this->assertArrayHasKey('title', $getItemData[0]); $this->assertArrayNotHasKey('created_at', $getItemData[0]); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/Console/Commands/RebuildUriCacheTest.php
tests/Console/Commands/RebuildUriCacheTest.php
<?php namespace StatamicRadPack\Runway\Tests\Console\Commands; use Illuminate\Database\Eloquent\Model; use PHPUnit\Framework\Attributes\Test; use StatamicRadPack\Runway\Routing\RunwayUri; use StatamicRadPack\Runway\Tests\Fixtures\Models\Author; use StatamicRadPack\Runway\Tests\Fixtures\Models\Post; use StatamicRadPack\Runway\Tests\TestCase; class RebuildUriCacheTest extends TestCase { #[Test] public function it_rebuilds_the_uri_cache() { Post::factory()->count(5)->createQuietly(); $this ->artisan('runway:rebuild-uris') ->expectsConfirmation( 'You are about to rebuild your entire URI cache. This may take part of your site down while running. Are you sure you want to continue?', 'yes' ); $this->assertCount(5, RunwayUri::all()); } #[Test] public function can_build_uri_with_antlers() { Post::factory()->createQuietly(['slug' => 'hello-world']); $this ->artisan('runway:rebuild-uris') ->expectsConfirmation( 'You are about to rebuild your entire URI cache. This may take part of your site down while running. Are you sure you want to continue?', 'yes' ); $this->assertCount(1, RunwayUri::all()); $this->assertEquals('/posts/hello-world', RunwayUri::first()->uri); } #[Test] public function does_not_rebuild_uri_cache_when_no_confirmation_is_provided() { Post::factory()->count(5)->create(); // `create` will trigger the URIs to be built via model events. $this ->artisan('runway:rebuild-uris') ->expectsConfirmation( 'You are about to rebuild your entire URI cache. This may take part of your site down while running. Are you sure you want to continue?', 'no' ); $this->assertCount(5, RunwayUri::all()); } #[Test] public function skips_resources_without_routing_configured() { Author::factory()->count(3)->createQuietly(); $this ->artisan('runway:rebuild-uris') ->expectsConfirmation( 'You are about to rebuild your entire URI cache. This may take part of your site down while running. Are you sure you want to continue?', 'yes' ) ->expectsOutputToContain('Skipping Authors, routing not configured.'); $this->assertCount(0, RunwayUri::all()); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/Console/Commands/ListResourcesTest.php
tests/Console/Commands/ListResourcesTest.php
<?php namespace StatamicRadPack\Runway\Tests\Console\Commands; use Illuminate\Support\Facades\Config; use PHPUnit\Framework\Attributes\Test; use StatamicRadPack\Runway\Runway; use StatamicRadPack\Runway\Tests\Fixtures\Models\Author; use StatamicRadPack\Runway\Tests\Fixtures\Models\Post; use StatamicRadPack\Runway\Tests\TestCase; class ListResourcesTest extends TestCase { #[Test] public function it_lists_resources() { $this ->artisan('runway:resources') ->expectsTable( ['Handle', 'Model', 'Route'], [ ['author', Author::class, 'N/A'], ['post', Post::class, '/posts/{{ slug }}'], ] ); } #[Test] public function it_outputs_error_when_no_resources_exist() { Config::set('runway.resources', []); Runway::discoverResources(); $this ->artisan('runway:resources') ->expectsOutputToContain("Your application doesn't have any resources."); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/Search/SearchableTest.php
tests/Search/SearchableTest.php
<?php namespace StatamicRadPack\Runway\Tests\Search; use PHPUnit\Framework\Attributes\Test; use StatamicRadPack\Runway\Data\AugmentedModel; use StatamicRadPack\Runway\Runway; use StatamicRadPack\Runway\Search\Searchable; use StatamicRadPack\Runway\Tests\Fixtures\Models\Post; use StatamicRadPack\Runway\Tests\TestCase; class SearchableTest extends TestCase { #[Test] public function can_get_resource() { $post = Post::factory()->create(); $searchable = new Searchable($post); $this->assertEquals(Runway::findResource('post'), $searchable->resource()); } #[Test] public function can_get_queryable_value() { $post = Post::factory()->create(); $searchable = new Searchable($post); $this->assertEquals($post->title, $searchable->getQueryableValue('title')); $this->assertEquals($post->slug, $searchable->getQueryableValue('slug')); $this->assertEquals($post->id, $searchable->getQueryableValue('id')); $this->assertEquals('default', $searchable->getQueryableValue('site')); } #[Test] public function can_get_search_value() { $post = Post::factory()->create(); $searchable = new Searchable($post); $this->assertEquals($post->title, $searchable->getSearchValue('title')); $this->assertEquals($post->slug, $searchable->getSearchValue('slug')); $this->assertEquals($post->id, $searchable->getSearchValue('id')); $this->assertEquals($post->searchMethod(), $searchable->getSearchValue('searchMethod')); } #[Test] public function can_get_search_reference() { $post = Post::factory()->create(); $searchable = new Searchable($post); $this->assertEquals("runway::post::{$post->id}", $searchable->getSearchReference()); } #[Test] public function can_get_search_result() { $post = Post::factory()->create(); $searchable = new Searchable($post); $result = $searchable->toSearchResult(); $this->assertEquals($searchable, $result->getSearchable()); $this->assertEquals("runway::post::{$post->id}", $result->getReference()); $this->assertEquals('runway:post', $result->getType()); } #[Test] public function can_get_cp_search_result_title() { $post = Post::factory()->create(); $searchable = new Searchable($post); $this->assertEquals($post->title, $searchable->getCpSearchResultTitle()); } #[Test] public function can_get_cp_search_result_url() { $post = Post::factory()->create(); $searchable = new Searchable($post); $this->assertStringContainsString("/runway/post/{$post->id}", $searchable->getCpSearchResultUrl()); } #[Test] public function can_get_cp_search_result_badge() { $post = Post::factory()->create(); $searchable = new Searchable($post); $this->assertEquals('Posts', $searchable->getCpSearchResultBadge()); } #[Test] public function can_get_new_augmented_instance() { $post = Post::factory()->create(); $searchable = new Searchable($post); $searchable->setSupplement('foo', 'bar'); $this->assertInstanceOf(AugmentedModel::class, $searchable->newAugmentedInstance()); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/Search/ProviderTest.php
tests/Search/ProviderTest.php
<?php namespace StatamicRadPack\Runway\Tests\Search; use PHPUnit\Framework\Attributes\Test; use StatamicRadPack\Runway\Search\Provider; use StatamicRadPack\Runway\Search\Searchable; use StatamicRadPack\Runway\Tests\Fixtures\Models\Post; use StatamicRadPack\Runway\Tests\TestCase; class ProviderTest extends TestCase { #[Test] public function it_gets_models() { $posts = Post::factory()->count(5)->create(); $provider = $this->makeProvider('en', ['searchables' => ['post']]); $models = $provider->provide(); $this->assertCount(5, $models); $this->assertInstanceOf(Searchable::class, $models[0]); $this->assertEquals("runway::post::{$posts[0]->id}", $models[0]->getSearchReference()); $this->assertInstanceOf(Searchable::class, $models[1]); $this->assertEquals("runway::post::{$posts[1]->id}", $models[1]->getSearchReference()); $this->assertInstanceOf(Searchable::class, $models[2]); $this->assertEquals("runway::post::{$posts[2]->id}", $models[2]->getSearchReference()); $this->assertInstanceOf(Searchable::class, $models[3]); $this->assertEquals("runway::post::{$posts[3]->id}", $models[3]->getSearchReference()); $this->assertInstanceOf(Searchable::class, $models[4]); $this->assertEquals("runway::post::{$posts[4]->id}", $models[4]->getSearchReference()); } #[Test] public function it_filters_out_unpublished_models() { $publishedModels = Post::factory()->count(2)->create(); Post::factory()->count(2)->unpublished()->create(); $provider = $this->makeProvider('en', ['searchables' => ['post']]); $models = $provider->provide(); $this->assertCount(2, $models); $this->assertEquals([ "runway::post::{$publishedModels[0]->id}", "runway::post::{$publishedModels[1]->id}", ], $models->map->getSearchReference()->all()); } private function makeProvider($locale, $config) { $index = $this->makeIndex($locale, $config); $keys = $this->normalizeSearchableKeys($config['searchables'] ?? null); return (new Provider)->setIndex($index)->setKeys($keys); } private function makeIndex($locale, $config) { $index = $this->mock(\Statamic\Search\Index::class); $index->shouldReceive('config')->andReturn($config); $index->shouldReceive('locale')->andReturn($locale); return $index; } private function normalizeSearchableKeys($keys) { // a bit of duplicated implementation logic. // but it makes the test look more like the real thing. return collect($keys === 'all' ? ['*'] : $keys) ->map(fn ($key) => str_replace('users:', '', $key)) ->all(); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/Data/AugmentedModelTest.php
tests/Data/AugmentedModelTest.php
<?php namespace StatamicRadPack\Runway\Tests\Data; use PHPUnit\Framework\Attributes\Test; use Spatie\TestTime\TestTime; use StatamicRadPack\Runway\Data\AugmentedModel; use StatamicRadPack\Runway\Tests\Fixtures\Models\Author; use StatamicRadPack\Runway\Tests\Fixtures\Models\Post; use StatamicRadPack\Runway\Tests\TestCase; class AugmentedModelTest extends TestCase { #[Test] public function it_gets_values() { TestTime::freeze('Y-m-d H:i:s', '2020-01-01 13:46:12'); $author = Author::factory()->create(['name' => 'John Doe']); $post = Post::factory()->create([ 'title' => 'My First Post', 'slug' => 'my-first-post', 'body' => 'Blah blah blah...', 'author_id' => $author->id, ]); $post->refresh(); $augmented = new AugmentedModel($post); $this->assertEquals('My First Post', $augmented->get('title')->value()); $this->assertEquals('my-first-post', $augmented->get('slug')->value()); $this->assertEquals('Blah blah blah...', $augmented->get('body')->value()); $this->assertEquals('2020-01-01 13:46:12', $augmented->get('created_at')->value()->format('Y-m-d H:i:s')); $this->assertEquals('/posts/my-first-post', $augmented->get('url')->value()); $this->assertIsArray($augmented->get('author')->value()); $this->assertEquals($author->id, $augmented->get('author')->value()['id']->value()); $this->assertEquals('John Doe', $augmented->get('author')->value()['name']->value()); $this->assertIsArray($augmented->get('author_id')->value()); $this->assertEquals($author->id, $augmented->get('author_id')->value()['id']->value()); $this->assertEquals('John Doe', $augmented->get('author_id')->value()['name']->value()); } #[Test] public function it_gets_nested_values_via_nested_field_prefix() { $post = Post::factory()->create([ 'values' => [ 'alt_title' => 'Alternative Title...', 'alt_body' => 'This is a **great** post! You should *read* it.', ], ]); $augmented = new AugmentedModel($post); $this->assertIsArray($augmented->get('values')->value()); // Eg. values:alt_title, values:alt_body $this->assertEquals('Alternative Title...', $augmented->get('values')->value()['alt_title']->value()); $this->assertEquals('<p>This is a <strong>great</strong> post! You should <em>read</em> it.</p>', trim($augmented->get('values')->value()['alt_body']->value())); } #[Test] public function it_gets_nested_values_via_nested_field_handle() { $post = Post::factory()->create([ 'values' => [ 'alt_title' => 'Alternative Title...', 'alt_body' => 'This is a **great** post! You should *read* it.', ], ]); $augmented = new AugmentedModel($post); $this->assertIsArray($augmented->get('values')->value()); // Eg. values_alt_title, values_alt_body $this->assertEquals('Alternative Title...', $augmented->get('values_alt_title')->value()); $this->assertEquals('<p>This is a <strong>great</strong> post! You should <em>read</em> it.</p>', trim($augmented->get('values_alt_body')->value())); } #[Test] public function it_gets_value_from_model_accessor() { $post = Post::factory()->create(); $augmented = new AugmentedModel($post); $this->assertEquals('This is an excerpt.', $augmented->get('excerpt')->value()); } #[Test] public function it_gets_value_from_appended_attribute() { $post = Post::factory()->create(); $augmented = new AugmentedModel($post); $this->assertEquals('This is an appended value.', $augmented->get('appended_value')->value()); } #[Test] public function it_gets_value_from_mutator() { $post = Post::factory()->create(['mutated_value' => 'Foo']); $augmented = new AugmentedModel($post); $this->assertEquals('Foo is a mutated value.', $augmented->get('mutated_value')->value()); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/__fixtures__/app/Scopes/TheHoff.php
tests/__fixtures__/app/Scopes/TheHoff.php
<?php namespace StatamicRadPack\Runway\Tests\Fixtures\Scopes; use Statamic\Query\Scopes\Scope; class TheHoff extends Scope { /** * Apply the scope. * * @param \Statamic\Query\Builder $query * @param array $values * @return void */ public function apply($query, $values) { $query->where('name', 'like', '%Hasselhoff%'); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/__fixtures__/app/Enums/MembershipStatus.php
tests/__fixtures__/app/Enums/MembershipStatus.php
<?php namespace StatamicRadPack\Runway\Tests\Fixtures\Enums; enum MembershipStatus: string { case Free = 'free'; case Paid = 'paid'; }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/__fixtures__/app/Models/User.php
tests/__fixtures__/app/Models/User.php
<?php namespace StatamicRadPack\Runway\Tests\Fixtures\Models; use Illuminate\Foundation\Auth\User as Authenticatable; use StatamicRadPack\Runway\Traits\HasRunwayResource; class User extends Authenticatable { use HasRunwayResource; /** * The attributes that are mass assignable. * * @var array<int, string> */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for serialization. * * @var array<int, string> */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast. * * @var array<string, string> */ protected $casts = [ 'email_verified_at' => 'datetime', 'preferences' => 'json', ]; }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/__fixtures__/app/Models/Author.php
tests/__fixtures__/app/Models/Author.php
<?php namespace StatamicRadPack\Runway\Tests\Fixtures\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Statamic\Facades\Blink; use StatamicRadPack\Runway\Tests\Fixtures\Database\Factories\AuthorFactory; use StatamicRadPack\Runway\Traits\HasRunwayResource; class Author extends Model { use HasFactory, HasRunwayResource; protected $fillable = [ 'name', 'start_date', 'end_date', ]; public function posts() { return $this->hasMany(Post::class); } public function pivottedPosts() { return $this->belongsToMany(Post::class, 'post_author'); } public function scopeRunwayListing($query) { if ($params = Blink::get('RunwayListingScopeOrderBy')) { $query->orderBy($params[0], $params[1]); } } protected static function newFactory() { return AuthorFactory::new(); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/__fixtures__/app/Models/Post.php
tests/__fixtures__/app/Models/Post.php
<?php namespace StatamicRadPack\Runway\Tests\Fixtures\Models; use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Statamic\Facades\Blink; use StatamicRadPack\Runway\Routing\Traits\RunwayRoutes; use StatamicRadPack\Runway\Tests\Fixtures\Database\Factories\PostFactory; use StatamicRadPack\Runway\Tests\Fixtures\Enums\MembershipStatus; use StatamicRadPack\Runway\Traits\HasRunwayResource; class Post extends Model { use HasFactory, HasRunwayResource, RunwayRoutes; protected $fillable = [ 'title', 'slug', 'body', 'values', 'external_links', 'author_id', 'sort_order', 'published', 'mutated_value', 'membership_status', ]; protected $appends = [ 'appended_value', 'excerpt', ]; protected $casts = [ 'values' => 'array', 'external_links' => 'object', 'published' => 'boolean', 'membership_status' => MembershipStatus::class, ]; public function scopeFood($query) { $query->whereIn('title', ['Pasta', 'Apple', 'Burger']); } public function scopeFruit($query, $smth) { if ($smth === 'idoo') { $query->whereIn('title', ['Apple']); } } public function scopeRunwayListing($query) { if ($params = Blink::get('RunwayListingScopeOrderBy')) { $query->orderBy($params[0], $params[1]); } } public function author() { return $this->belongsTo(Author::class); } public function excerpt(): Attribute { return Attribute::make( get: function () { return 'This is an excerpt.'; } ); } public function appendedValue(): Attribute { return Attribute::make( get: function () { return 'This is an appended value.'; } ); } public function mutatedValue(): Attribute { return Attribute::make( get: fn (string $value, array $attributes) => "{$value} is a mutated value.", ); } public function searchMethod() { return 'This is a value returned from a method'; } protected static function newFactory() { return PostFactory::new(); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/__fixtures__/app/Models/ExternalPost.php
tests/__fixtures__/app/Models/ExternalPost.php
<?php namespace StatamicRadPack\Runway\Tests\Fixtures\Models; use Illuminate\Database\Eloquent\Model; use StatamicRadPack\Runway\Traits\HasRunwayResource; class ExternalPost extends Model { use HasRunwayResource; protected $connection = 'external'; protected $table = 'external_posts'; protected $fillable = [ 'title', 'body', ]; }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/__fixtures__/config/runway.php
tests/__fixtures__/config/runway.php
<?php use StatamicRadPack\Runway\Tests\Fixtures\Models\Author; use StatamicRadPack\Runway\Tests\Fixtures\Models\Post; use StatamicRadPack\Runway\Tests\Fixtures\Models\User; return [ 'resources' => [ Author::class => [ 'name' => 'Authors', 'listing' => [ 'columns' => [ 'name', ], 'sort' => [ 'column' => 'name', 'direction' => 'asc', ], ], ], Post::class => [ 'name' => 'Posts', 'listing' => [ 'columns' => [ 'title', ], 'sort' => [ 'column' => 'title', 'direction' => 'desc', ], ], 'route' => '/posts/{{ slug }}', 'published' => true, 'revisions' => true, 'nested_field_prefixes' => [ 'values', 'external_links', ], ], User::class => [ 'name' => 'Users', ], ], ];
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/__fixtures__/database/factories/PostFactory.php
tests/__fixtures__/database/factories/PostFactory.php
<?php namespace StatamicRadPack\Runway\Tests\Fixtures\Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; use StatamicRadPack\Runway\Tests\Fixtures\Models\Author; use StatamicRadPack\Runway\Tests\Fixtures\Models\Post; class PostFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string */ protected $model = Post::class; /** * Define the model's default state. * * @return array */ public function definition() { return [ 'title' => $title = implode(' ', $this->faker->words(6)), 'slug' => Str::slug($title), 'body' => implode(' ', $this->faker->paragraphs(10)), 'author_id' => Author::factory()->create()->id, 'start_date' => now(), 'published' => true, 'mutated_value' => 'Foo', ]; } public function unpublished() { return $this->state([ 'published' => false, ]); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/__fixtures__/database/factories/AuthorFactory.php
tests/__fixtures__/database/factories/AuthorFactory.php
<?php namespace StatamicRadPack\Runway\Tests\Fixtures\Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; use StatamicRadPack\Runway\Tests\Fixtures\Models\Author; class AuthorFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string */ protected $model = Author::class; /** * Define the model's default state. * * @return array */ public function definition() { return [ 'name' => $this->faker->name(), ]; } public function withPosts(int $count = 1): Factory { return $this->afterCreating(function (Author $author) use ($count) { $author->posts()->createMany( PostFactory::new()->count($count)->make()->toArray() ); }); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/__fixtures__/database/migrations/2014_10_12_000000_create_users_tables.php
tests/__fixtures__/database/migrations/2014_10_12_000000_create_users_tables.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password')->nullable(); $table->rememberToken(); $table->timestamps(); $table->boolean('super')->default(false); $table->string('avatar')->nullable(); $table->json('preferences')->nullable(); $table->timestamp('last_login')->nullable(); }); Schema::create('role_user', function (Blueprint $table) { $table->id('id'); $table->foreignId('user_id')->constrained('users')->cascadeOnDelete(); $table->string('role_id'); }); Schema::create('group_user', function (Blueprint $table) { $table->id('id'); $table->foreignId('user_id')->constrained('users')->cascadeOnDelete(); $table->string('group_id'); }); Schema::create('password_activation_tokens', function (Blueprint $table) { $table->string('email')->index(); $table->string('token'); $table->timestamp('created_at')->nullable(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('users'); Schema::dropIfExists('role_user'); Schema::dropIfExists('group_user'); Schema::dropIfExists('password_activation_tokens'); } };
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/__fixtures__/database/migrations/2021_04_01_222222_create_authors_table.php
tests/__fixtures__/database/migrations/2021_04_01_222222_create_authors_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateAuthorsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('authors', function (Blueprint $table) { $table->id(); $table->string('name'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('authors'); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/__fixtures__/database/migrations/2020_12_12_220453_create_posts_table.php
tests/__fixtures__/database/migrations/2020_12_12_220453_create_posts_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreatePostsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('posts', function (Blueprint $table) { $table->id(); $table->string('title'); $table->string('slug'); $table->longText('body'); $table->json('values')->nullable(); $table->json('external_links')->nullable(); $table->integer('author_id')->nullable(); $table->integer('sort_order')->nullable(); $table->datetime('start_date')->nullable(); $table->datetime('end_date')->nullable(); $table->boolean('published')->default(false); $table->string('mutated_value')->nullable(); $table->string('membership_status')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('posts'); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/__fixtures__/database/migrations/2023_06_16_123456_create_post_author_table.php
tests/__fixtures__/database/migrations/2023_06_16_123456_create_post_author_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreatePostAuthorTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('post_author', function (Blueprint $table) { $table->integer('post_id'); $table->integer('author_id'); $table->integer('pivot_sort_order')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('authors'); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/GraphQL/ResourceInterfaceTest.php
tests/GraphQL/ResourceInterfaceTest.php
<?php namespace StatamicRadPack\Runway\Tests\GraphQL; use PHPUnit\Framework\Attributes\Test; use Rebing\GraphQL\Support\Facades\GraphQL; use StatamicRadPack\Runway\Tests\TestCase; class ResourceInterfaceTest extends TestCase { #[Test] public function it_adds_types() { $this->assertEquals([ 'runway_graphql_types_author', 'runway_graphql_types_post', 'Runway_NestedFields_Post_Values', 'Runway_NestedFields_Post_ExternalLinks', 'runway_graphql_types_user', ], array_keys(GraphQL::getTypes())); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/Policies/ResourcePolicyTest.php
tests/Policies/ResourcePolicyTest.php
<?php namespace StatamicRadPack\Runway\Tests\Policies; use PHPUnit\Framework\Attributes\Test; use Statamic\Facades\Role; use Statamic\Facades\User; use StatamicRadPack\Runway\Runway; use StatamicRadPack\Runway\Tests\Fixtures\Models\Post; use StatamicRadPack\Runway\Tests\TestCase; class ResourcePolicyTest extends TestCase { #[Test] public function can_view_resource() { $resource = Runway::findResource('post'); Role::make('test')->addPermission('view post')->save(); $user = User::make()->assignRole('test')->save(); $this->assertTrue($user->can('view', $resource)); } #[Test] public function can_view_resource_with_model() { $resource = Runway::findResource('post'); Role::make('test')->addPermission('view post')->save(); $user = User::make()->assignRole('test')->save(); $this->assertTrue($user->can('view', [$resource, new Post])); } #[Test] public function can_create_resource() { $resource = Runway::findResource('post'); Role::make('test')->addPermission('create post')->save(); $user = User::make()->assignRole('test')->save(); $this->assertTrue($user->can('create', $resource)); } public function can_edit_resource() { $resource = Runway::findResource('post'); Role::make('test')->addPermission('edit post')->save(); $user = User::make()->assignRole('test')->save(); $this->assertTrue($user->can('edit', $resource)); } #[Test] public function can_edit_resource_with_model() { $resource = Runway::findResource('post'); Role::make('test')->addPermission('edit post')->save(); $user = User::make()->assignRole('test')->save(); $this->assertTrue($user->can('edit', [$resource, new Post])); } public function can_delete_resource() { $resource = Runway::findResource('post'); Role::make('test')->addPermission('delete post')->save(); $user = User::make()->assignRole('test')->save(); $this->assertTrue($user->can('delete', $resource)); } #[Test] public function can_delete_resource_with_model() { $resource = Runway::findResource('post'); Role::make('test')->addPermission('delete post')->save(); $user = User::make()->assignRole('test')->save(); $this->assertTrue($user->can('delete', [$resource, new Post])); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/routes/cp.php
routes/cp.php
<?php use Illuminate\Support\Facades\Route; use StatamicRadPack\Runway\Http\Controllers\CP\ModelActionController; use StatamicRadPack\Runway\Http\Controllers\CP\ModelRevisionsController; use StatamicRadPack\Runway\Http\Controllers\CP\PublishedModelsController; use StatamicRadPack\Runway\Http\Controllers\CP\ResourceActionController; use StatamicRadPack\Runway\Http\Controllers\CP\ResourceController; use StatamicRadPack\Runway\Http\Controllers\CP\ResourceListingController; use StatamicRadPack\Runway\Http\Controllers\CP\RestoreModelRevisionController; Route::name('runway.')->prefix('runway')->group(function () { Route::get('/{resource}', [ResourceController::class, 'index'])->name('index'); Route::get('{resource}/listing-api', [ResourceListingController::class, 'index'])->name('listing-api'); Route::post('{resource}/actions', [ResourceActionController::class, 'run'])->name('actions.run'); Route::post('{resource}/models/actions', [ModelActionController::class, 'runAction'])->name('models.actions.run'); Route::post('{resource}/models/actions/list', [ModelActionController::class, 'bulkActionsList'])->name('models.actions.bulk'); Route::get('{resource}/create', [ResourceController::class, 'create'])->name('create'); Route::post('{resource}/create', [ResourceController::class, 'store'])->name('store'); Route::get('{resource}/{model}', [ResourceController::class, 'edit'])->name('edit'); Route::patch('{resource}/{model}', [ResourceController::class, 'update'])->name('update'); Route::group(['prefix' => '{resource}/{model}'], function () { Route::post('publish', [PublishedModelsController::class, 'store'])->name('published.store'); Route::post('unpublish', [PublishedModelsController::class, 'destroy'])->name('published.destroy'); Route::resource('revisions', ModelRevisionsController::class, [ 'as' => 'revisions', 'only' => ['index', 'store', 'show'], ])->names([ 'index' => 'revisions.index', 'store' => 'revisions.store', 'show' => 'revisions.show', ])->parameters(['revisions' => 'revisionId']); Route::post('restore-revision', RestoreModelRevisionController::class)->name('restore-revision'); }); });
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/config/runway.php
config/runway.php
<?php return [ /* |-------------------------------------------------------------------------- | Resources |-------------------------------------------------------------------------- | | Configure the resources (models) you'd like to be available in Runway. | */ 'resources' => [ // \App\Models\Order::class => [ // 'name' => 'Orders', // ], ], /* |-------------------------------------------------------------------------- | Runway URIs Table |-------------------------------------------------------------------------- | | When using Runway's front-end routing functionality, Runway will store model | URIs in a table to enable easy "URI -> model" lookups. If needed, you can | customize the table name here. | */ 'uris_table' => 'runway_uris', /* |-------------------------------------------------------------------------- | Disable Migrations? |-------------------------------------------------------------------------- | | Should Runway's migrations be disabled? | (eg. not automatically run when you next vendor:publish) | */ 'disable_migrations' => false, ];
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/database/migrations/2021_05_04_162552_create_runway_uris_table.php
database/migrations/2021_05_04_162552_create_runway_uris_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateRunwayUrisTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create(config('runway.uris_table', 'runway_uris'), function (Blueprint $table) { $table->id(); $table->string('uri'); $table->string('model_type'); $table->string('model_id', 36); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists(config('runway.uris_table', 'runway_uris')); } }
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/resources/views/pagination.blade.php
resources/views/pagination.blade.php
@if ($paginator->hasPages()) <nav role="navigation" aria-label="{{ __('Pagination Navigation') }}" class="flex items-center justify-between"> <div class="flex justify-between flex-1 sm:hidden"> @if ($paginator->onFirstPage()) <span class="relative inline-flex items-center px-4 py-2 text-sm font-medium text-grey-50 bg-white border border-grey-30 cursor-default leading-5 rounded-md"> {!! __('pagination.previous') !!} </span> @else <a href="{{ $paginator->previousPageUrl() }}" class="relative inline-flex items-center px-4 py-2 text-sm font-medium text-grey-100 bg-white border border-grey-30 leading-5 rounded-md hover:text-grey-50 focus:outline-none focus:shadow-outline-blue focus:border-blue-300 active:bg-grey-10 active:text-grey-100 transition ease-in-out duration-150"> {!! __('pagination.previous') !!} </a> @endif @if ($paginator->hasMorePages()) <a href="{{ $paginator->nextPageUrl() }}" class="relative inline-flex items-center px-4 py-2 ml-3 text-sm font-medium text-grey-100 bg-white border border-grey-30 leading-5 rounded-md hover:text-grey-50 focus:outline-none focus:shadow-outline-blue focus:border-blue-300 active:bg-grey-10 active:text-grey-100 transition ease-in-out duration-150"> {!! __('pagination.next') !!} </a> @else <span class="relative inline-flex items-center px-4 py-2 ml-3 text-sm font-medium text-grey-50 bg-white border border-grey-30 cursor-default leading-5 rounded-md"> {!! __('pagination.next') !!} </span> @endif </div> <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-center"> <div> <span class="relative z-0 inline-flex shadow rounded-md"> {{-- Previous Page Link --}} @if ($paginator->onFirstPage()) <span aria-disabled="true" aria-label="{{ __('pagination.previous') }}"> <span class="relative inline-flex items-center px-1.5 py-1 text-sm font-medium text-grey-50 bg-white border border-grey-30 cursor-default rounded-l-md leading-5" aria-hidden="true"> <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20"> <path fill-rule="evenodd" d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z" clip-rule="evenodd" /> </svg> </span> </span> @else <a href="{{ $paginator->previousPageUrl() }}" rel="prev" class="relative inline-flex items-center px-1.5 py-1 text-sm font-medium text-grey-50 bg-white border border-grey-30 rounded-l-md leading-5 hover:text-grey-40 focus:z-10 focus:outline-none focus:border-blue-300 focus:shadow-outline-blue active:bg-grey-10 active:text-grey-50 transition ease-in-out duration-150" aria-label="{{ __('pagination.previous') }}"> <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20"> <path fill-rule="evenodd" d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z" clip-rule="evenodd" /> </svg> </a> @endif {{-- Pagination Elements --}} @foreach ($elements as $element) {{-- "Three Dots" Separator --}} @if (is_string($element)) <span aria-disabled="true"> <span class="relative inline-flex items-center px-1.5 py-1 -ml-px text-sm font-medium text-grey-100 bg-white border border-grey-30 cursor-default leading-5">{{ $element }}</span> </span> @endif {{-- Array Of Links --}} @if (is_array($element)) @foreach ($element as $page => $url) @if ($page == $paginator->currentPage()) <span aria-current="page"> <span class="relative inline-flex items-center px-1.5 py-1 -ml-px h-full text-sm font-medium text-primary bg-white border border-grey-30 cursor-default leading-5">{{ $page }}</span> </span> @else <a href="{{ $url }}" class="relative inline-flex items-center px-1.5 py-1 -ml-px text-sm font-medium text-grey-100 bg-white border border-grey-30 leading-5 hover:text-grey-50 focus:z-10 focus:outline-none focus:border-blue-300 focus:shadow-outline-blue active:bg-grey-10 active:text-grey-100 transition ease-in-out duration-150" aria-label="{{ __('Go to page :page', ['page' => $page]) }}"> {{ $page }} </a> @endif @endforeach @endif @endforeach {{-- Next Page Link --}} @if ($paginator->hasMorePages()) <a href="{{ $paginator->nextPageUrl() }}" rel="next" class="relative inline-flex items-center px-1.5 py-1 -ml-px text-sm font-medium text-grey-50 bg-white border border-grey-30 rounded-r-md leading-5 hover:text-grey-40 focus:z-10 focus:outline-none focus:border-blue-300 focus:shadow-outline-blue active:bg-grey-10 active:text-grey-50 transition ease-in-out duration-150" aria-label="{{ __('pagination.next') }}"> <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20"> <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd" /> </svg> </a> @else <span aria-disabled="true" aria-label="{{ __('pagination.next') }}"> <span class="relative inline-flex items-center px-1.5 py-1 -ml-px text-sm font-medium text-grey-50 bg-white border border-grey-30 cursor-default rounded-r-md leading-5" aria-hidden="true"> <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20"> <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd" /> </svg> </span> </span> @endif </span> </div> </div> </nav> @endif
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/resources/views/edit.blade.php
resources/views/edit.blade.php
@inject('str', 'Statamic\Support\Str') @extends('statamic::layout') @section('title', $breadcrumbs->title($title)) @section('wrapper_class', 'max-w-3xl') @section('content') <runway-publish-form publish-container="base" :initial-actions='@json($actions)' method="patch" :resource='@json($resource->toArray())' :resource-has-routes="{{ $str::bool($resourceHasRoutes) }}" initial-title="{{ $title }}" initial-reference="{{ $reference }}" :initial-blueprint='@json($blueprint)' :initial-values='@json($values)' :initial-meta='@json($meta)' initial-permalink="{{ $permalink }}" :initial-is-working-copy="{{ $str::bool($hasWorkingCopy) }}" :initial-read-only="{{ $str::bool($readOnly) }}" initial-status="{{ $status }}" :breadcrumbs="{{ $breadcrumbs->toJson() }}" :can-edit-blueprint="{{ Auth::user()->can('configure fields') ? 'true' : 'false' }}" :can-manage-publish-state="{{ $str::bool($canManagePublishState) }}" create-another-url="{{ cp_route('runway.create', ['resource' => $resource->handle()]) }}" initial-listing-url="{{ cp_route('runway.index', ['resource' => $resource->handle()]) }}" :initial-item-actions="{{ json_encode($itemActions) }}" item-action-url="{{ cp_route('runway.models.actions.run', ['resource' => $resource->handle()]) }}" :revisions-enabled="{{ $str::bool($revisionsEnabled) }}" ></runway-publish-form> <script> window.Runway = { currentModel: @json($currentModel), currentResource: "{{ $resource->handle() }}", } </script> @endsection
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/resources/views/index.blade.php
resources/views/index.blade.php
@extends('statamic::layout') @section('title', $resource->name()) @section('wrapper_class', 'max-w-full') @section('content') <resource-view title="{{ $resource->name() }}" handle="{{ $resource->handle() }}" :can-create="{{ Statamic\Support\Str::bool($canCreate) }}" create-url="{{ $createUrl }}" create-label="{{ $createLabel }}" :columns="{{ $columns->toJson() }}" :filters="{{ $filters->toJson() }}" action-url="{{ $actionUrl }}" primary-column="{{ $primaryColumn }}" :has-publish-states="{{ Statamic\Support\Str::bool($resource->hasPublishStates()) }}" > <template #twirldown="{ actionCompleted }"> @can('configure fields') <dropdown-item :text="__('Edit Blueprint')" redirect="{{ cp_route('blueprints.edit', ['namespace' => 'runway', 'handle' => $resource->handle()]) }}"></dropdown-item> @endcan <data-list-inline-actions item="{{ $resource->handle() }}" url="{{ cp_route('runway.actions.run', ['resource' => $resource->handle()]) }}" :actions="{{ $actions }}" @completed="actionCompleted" ></data-list-inline-actions> </template> </resource-view> @endsection
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
statamic-rad-pack/runway
https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/resources/views/create.blade.php
resources/views/create.blade.php
@inject('str', 'Statamic\Support\Str') @extends('statamic::layout') @section('title', $breadcrumbs->title(__('Create :resource', ['resource' => $resource->singular()]))) @section('wrapper_class', 'max-w-3xl') @section('content') <runway-publish-form :is-creating="true" publish-container="base" :initial-actions='@json($actions)' method="post" :resource='@json($resource->toArray())' :resource-has-routes="{{ $str::bool($resourceHasRoutes) }}" initial-title="{{ $title }}" :initial-blueprint='@json($blueprint)' :initial-values='@json($values)' :initial-meta='@json($meta)' :breadcrumbs='{{ $breadcrumbs->toJson() }}' :can-manage-publish-state="{{ $str::bool($canManagePublishState) }}" create-another-url="{{ cp_route('runway.create', ['resource' => $resource->handle()]) }}" initial-listing-url="{{ cp_route('runway.index', ['resource' => $resource->handle()]) }}" :can-manage-publish-state="{{ $str::bool($canManagePublishState) }}" ></runway-publish-form> @endsection
php
MIT
27defcba1673a204ded32122e413172dbc6aa186
2026-01-05T05:10:50.689341Z
false
pheryjs/phery
https://github.com/pheryjs/phery/blob/f22d04625d84d4631c6b2ea0435fe6623c9b1c8e/demo.php
demo.php
<?php use Phery\Phery; use Phery\PheryException; use Phery\PheryFunction; use Phery\PheryResponse; //Ensure that it's completly compatible with strict mode and throws no notices or warnings, and not using any deprecated code error_reporting(-1); if (version_compare(PHP_VERSION, '5.3.3', '<')) { die('This demo needs at least PHP 5.3.3'); } ini_set('display_errors', 1); $end_line = 907; date_default_timezone_set('UTC'); $memory_start = 0; $start_time = microtime(true); require_once 'vendor/autoload.php'; PheryResponse::set_global('global', true); //sleep(2); // uncomment to emulate latency // Create a named response so we can include it later by the name PheryResponse::factory() ->j('<div/>', array( 'css' => array('cursor' => 'pointer','border' => 'solid 3px #000' ) )) ->html('This is a <i>new</i> <b>element</b>') ->one('click', PheryFunction::factory(array( //'function(){', 'var $this = $(this);', '$(this).fadeOut("slow").promise().done(function(){ $this.remove(); });', //'}' ) )) ->prependTo('body') ->set_response_name('my name is'); // << Name of this response PheryResponse::factory('html,body')->scrollTop(0)->set_response_name('scrollTop'); class myClass { function test($ajax_data, $callback_data) { return PheryResponse::factory('div.test') ->merge('scrollTop') // merge the named response ->filter(':eq(1)') ->addClass('fast') ->text($ajax_data['hi']) ->jquery('a') // Create callbacks directly from PHP! No need to do this, just to show it's possible // White space (CRLF, tabs, spaces) doesnt matter to JSON, it just adds extra bytes // to the response afterall. It's created through the special class PheryFunction ->each(PheryFunction::factory( <<<JSON function(i, el){ console.log("inside each!", i); if ($(this).text().length > 17) { $(this).css({"color":"green","textDecoration":"none"}); } } JSON )); } static function test2($ajax_data, $callback_data) { // Integers must be typecast, because JSON will // turn everything to a string, because // "1" + "2" = "12" // 1 + 2 = 3 foreach ($ajax_data as &$j) { $j = (int)$j; } return PheryResponse::factory()->call('test', $ajax_data); } function data($ajax_data, $callback_data, Phery $phery) { return PheryResponse::factory($callback_data['submit_id']) // submit_id will have #special2 ->merge('scrollTop') ->data('testing', array('nice' => 'awesome')) ->jquery('div.test2') ->css(array('backgroundColor' => '#f5a')) ->animate(array( 'width' => "70%", 'opacity' => 0.8, 'marginLeft' => "0.6in", 'fontSize' => "1em", 'borderWidth' => "10px" ), 1500, 'linear', PheryFunction::factory( <<<JSON function(){ $(this).append("<br>yes Ive finished animating and fired from inside PHP as an animate() completion callback using PheryFunction rawr!"); } JSON )); } } // You can return a string, or anything else than a standard // response, that the phery:done event will be triggered // before the parsing of the usual functions, so you can parse by // your own methods, and signal that the event should halt there function test($args) { return json_encode(array('hi' => $args['hello'], 'hello' => 'good')); } function trigger() { return PheryResponse::factory('div.test') ->trigger('test') ->jquery('<li/>') // Create a new element like in jQuery and append to the ul ->css('backgroundColor', '#0f0') ->html('<h1>Dynamically added, its already bound with phery.js AJAX upon creation because of jquery delegate()</h1>' . Phery::link_to('Click me (execute script calling window.location.reload)', 'surprise')) ->appendTo('#add'); } // data contains form data function form($data) { $files = array(); foreach (PheryResponse::files('file') as $file){ $files[] = 'filename: ' . strip_tags($file['name']) . ' / size: ' . $file['size'] . 'B'; } return PheryResponse::factory('div.test:eq(0)') ->merge('scrollTop') ->text(print_r($data, true)) ->unless(count($files) === 0) ->append("\n\n-----Files Uploaded-----\n\n" . join("\n\n", $files)) ->dump_vars($data); } function thisone($data) { return PheryResponse::factory() ->dump_vars($data); } function the_one_with_expr($data) { return PheryResponse::factory('.test2') ->css(array('backgroundColor' => 'red', 'color' => '#fff')) ->html('<pre>'. strip_tags($data['new-onthefly-var']) . '</pre>') ->show() ->merge(thisone($data)); } /** * Callback that executes before calling the remote ajax function * This is usually useful when dealing with repetitive tasks or to * centralize all the common tasks to one big callback */ function pre_callback($data, $callback_specific_data_as_array) { // Dont mess with data that is submited without ajax if (Phery::is_ajax()) { ob_start(); unset($callback_specific_data_as_array['phery']); var_export(array(array('$data' => $data), array('$callback_specific_data_as_array' => $callback_specific_data_as_array))); $dump = ob_get_clean(); $data['new-onthefly-var'] = $dump; } if (is_array($data)) { foreach ($data as &$d) { if (is_string($d)) { $d = strtoupper($d); } } } return $data; // Must return the data, or false if you want to stop further processing } /** * Post callback that might add some info to the phery response, * in this example, we will renew the CSRF after each request */ function post_callback($data, $callback_specific_data_as_array, $PheryResponse, $phery) { if ($PheryResponse instanceof PheryResponse) { //$PheryResponse->renew_csrf($phery); } } function timeout($data, $parameters) { $r = PheryResponse::factory(); session_write_close(); // Needed because it will hang future calls, when using CSRF if (isset($data['callback']) && !empty($parameters['retries'])) { // The URL will have a retries when doing a retry return $r->dump_vars('Second time it worked, no error callback call ;)'); } sleep(5); // Sleep for 5 seconds to timeout the AJAX request, and trigger our retry return $r; } /** * Callbacks to measure the memory used, for benchmarking reasons ;) */ function mem_start($data, $callback) { global $memory_start; $memory_start = memory_get_usage(); return $data; } function mem_end($data, $callback, $phery_answer) { global $memory_start, $start_time; $mem = array( round(memory_get_peak_usage() / 1024, 2) . 'Kb', round((memory_get_usage() - $memory_start) / 1024, 2) . 'Kb', (string)(round(microtime(true) - $start_time, 6)) ); if ($phery_answer instanceof PheryResponse) { $phery_answer->apply('memusage', $mem); } } /** * New instances of phery and our test class */ $instance = new myClass; $phery = new Phery; /* Pseudo page menu */ $menu = '<a href="?page=home">home</a> <a href="?page=about">about us</a> <a href="?page=contact">contact us</a> <a href="?page=notfound">Doesnt exist</a> <a href="?page=redirect">Redirect to home (inline)</a> <a href="?page=excluded#container">Excluded (full refresh)</a>'; /* Quick hack to emulate a controller based website */ function pseudo_controller() { if (isset($_GET['page'])) { switch ($_GET['page']) { case 'home': $title = 'Home'; $html = <<<HTML <h1>Home</h1> <p>Welcome to our website</p> <p><img src="http://lipsum.lipsum.com/images/lorem.gif"></p> HTML; return array($title, $html); break; case 'about': $title = 'About Us'; $html = <<<HTML <h1>About us</h1> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent ligula ante, auctor id commodo eu. </p> HTML; return array($title, $html); break; case 'contact': $title = 'Contact Us'; $form = Phery::form_for('', 'form'); $html = <<<"HTML" <h1>Contact us</h1> <p>Use the form below to contact us</p> {$form} <p> <label>Name</label> <input name="name" type="text"> </p> <p> <label>Email</label> <input name="email" type="email"> </p> <p> <label>Message</label> <textarea name="message"></textarea> </p> <p> <input type="submit" value="Send"> </p> </form> HTML; return array($title, $html); break; case 'excluded': return array('Excluded', '<h1>This is always reached through a full page load</h1><p>Because of the exclude param when creating the view</p>'); break; case 'redirect': return array(true, true); break; default: return array('Not Found', '<h1>404 Not Found</h1><p>The requested url was not found</p>'); break; } } else { return array('Welcome', '<h1>Welcome!</h1>'); } } $pseudo_controller = pseudo_controller(); $content = $menu . $pseudo_controller[1]; try { $phery->config( array( /** * Throw exceptions and return them in form of PheryException, * usually for debug purposes. If set to false (default), it fails * silently */ 'exceptions' => true, /** * Enable CSRF protection, needs to use Phery::instance()->csrf() on your * HTML head, to print the meta */ 'csrf' => true ) ) /** * Set up the views, pass the global variable $menu to our * container render callback */ ->data(array('menu' => $menu)) ->views(array( '#container' => function ($data, $param) { $render = pseudo_controller(); if ($render[0] === true) { return PheryResponse::factory() ->json(array('doesnt work')) ->j('#wont select') ->text('because redirect clear all commands') ->redirect('?page=home', $param['view']); } return PheryResponse::factory() ->render_view($param['menu'] . $render[1], array('title' => $render[0])); } )) /** * Set the callbacks for all functions, just for benchmark */ ->callback(array( 'before' => 'mem_start', 'after' => 'mem_end' )) /** * Set the aliases for the AJAX calls */ ->set(array( 'readcode' => function($config){ $file = fopen(realpath(__FILE__), 'r'); global $end_line; $r = new PheryResponse; if ( !empty($config['from']) && !empty($config['to']) && (int)$config['from'] > 0 && (int)$config['to'] > 0 && (int)$config['to'] < $end_line ) { $lines = 1; $code = array(); while (fgets($file) !== false) { if (++$lines === (int)$config['from']) { break; } } while (($line = fgets($file)) !== false) { if ($lines++ > (int)$config['to']) { break; } else { $code[] = $line; } } array_unshift($code, 'Lines: '.((int)$config['from']).' to '.((int)$config['to'])."\n\n"); $r->this->parent()->find('.code')->text(join("", $code)); } fclose($file); return $r; }, 'this'=> function(){ return PheryResponse::factory() ->this ->css(array( 'backgroundColor' => '#000', 'color' => '#fff' )) ->parent() ->append('<p>Nice!</p>'); }, 'dumpvars' => function ($data) { $r = new PheryResponse; $d = array(); $d['dummy_info'] = 'dummy to show in print/dump'; foreach ($data as $name => $value) { if ($name !== 'is_print') { $d[$name] = $value; } } if (!empty($data['is_print'])) { $r->print_vars($d); } else { $r->dump_vars($d); } return $r->this->phery('append_args', array('wow' => 'true')); }, // instance method call 'test' => array($instance, 'test'), // regular function 'test2' => 'test', // static function 'test4' => array('myClass', 'test2'), // Lambda 'test5' => function () { return PheryResponse::factory()->redirect('http://www.google.com'); }, // Use PHP-side animate() callback! 'data' => array($instance, 'data'), // Trigger even on another element 'trigger' => 'trigger', // Trigger even on another element 'form' => 'form', // Call this function even if it's not been submitted by AJAX, but IS a post 'thisone' => 'thisone', // Lambda, reload the page 'surprise' => function ($data) { return PheryResponse::factory()->call(array('location','reload'), true); }, // Invalid Javascript to trigger "EXCEPTION" callback 'invalid' => function () { return PheryResponse::factory()->script('not valid javascript')->jquery('a')->blah(); }, // Timeout 'timeout' => 'timeout', // Select chaining results 'chain' => function ($data, $complement) { $r = PheryResponse::factory($complement['submit_id'])->next('div'); // If the select has a name, the value of the select element will be passed as // a key => value of it's name. Or it could be used as // PheryResponse::factory()->this->next('div'); $html = array(); error_reporting(0); switch (Phery::coalesce($data['named'], $data[0])) { case 1: $html = array( '1' => '1-1', '2' => '1-2', '3' => '1-3' ); break; case 2: $html = array( '1' => '2-1', '2' => '2-2', '3' => '2-3' ); break; case 3: $html = array( '1' => '3-1', '2' => '3-2', '3' => '3-3', ); break; } // Return a new select inside the adjacent divs return $r->html(Phery::select_for('msgbox', $html, array('selected' => '3'))); }, // just alertbox the data 'msgbox' => function ($data) { return PheryResponse::factory() ->alert($data); }, 'json' => function($data) { $data = array(); for ($i = 0; $i < 8; $i++) { $data[] = array( 'id' => $i + 1000, 'data' => array( 'name' => 'name '.$i, 'value' => $i * 10, ) ); } return PheryResponse::factory()->json($data); }, // select multiple 'selectuple' => function ($data) { return PheryResponse::factory() ->dump_vars($data); }, 'before' => function ($data) { return PheryResponse::factory() ->call($data['callback'], $data['alert']); }, 'reuse' => function($data, $b) { $r = PheryResponse::factory('#widgets div')->removeClass('focus-widget') ->j($b['submit_id'])->addClass('focus-widget') ->find('div')->show(); if (count($data)) { foreach ($data as $d) { if (is_array($d)) { $d = json_encode($d); } $r->append(strip_tags($d).' '); } } return $r; }, 'img' => function ($data) { return PheryResponse::factory() ->script('if(confirm("Do you wanna go to Wikipedia?")) window.location.assign("http://wikipedia.org");'); }, 'REST' => function ($data, $params) { $r = new PheryResponse('#RESTAnswer'); if (session_id() == '') { @session_start(); } /* EMULATE A DATABASE USING SESSION */ switch ($params['method']) { case 'GET': if (!empty($_SESSION['data'][$_GET['id']])) { $r->text("Exists: \n" . print_r($_SESSION['data'][$_GET['id']], true)); } else { $r->text('ID doesnt exists'); } break; case 'PUT': if (!empty($_SESSION['data'][$_GET['id']])) { $_SESSION['data'][$_GET['id']] = array( 'alert' => $data['alert'], 'incoming' => $data['incoming'], 'named' => $data['named'], 'holy' => $data[0], 'one' => $data[1], ); $r->text('Updated'); } else { $r->text('ID doesnt exists, create it first'); } break; case 'POST': if (empty($_SESSION['data'][$_GET['id']])) { $_SESSION['data'][$_GET['id']] = array( 'alert' => $data['alert'], 'incoming' => $data['incoming'], ); $r->text('Created'); } else { $r->text('Already exists'); } break; case 'DELETE': if (!empty($_SESSION['data'][$_GET['id']])) { unset($_SESSION['data'][$_GET['id']]); $r->text('Item deleted'); } else { $r->text('ID doesnt exists'); } break; } return $r; }, 'nested'=> function(){ /* This is the same as doing: $(this).before( $('<p/>', { 'text' => 'Text content at UNIX ' + new Date().getTime() }) ); */ return PheryResponse::factory()->this->before( PheryResponse::factory('<p/>', array( 'text' => 'Text content at UNIX ' . time() )) ); }, )) /** * process(false) mean we will call phery again with * process(true)/process() to end the processing, so it doesn't * block the execution of the other process() call */ ->process(false); $csrf_token = $phery->csrf(); /** * To separate the callback from the rest of the other functions, * just call a second process() */ $phery /** * Set the callbacks ONLY for "test3" and "the_one_with_expr" */ ->callback(array( 'before' => 'pre_callback', 'after' => 'post_callback' )) ->set(array( // Set lambda with two alerts 'test3' => function ($args, $param) { // Lambda/anonymous function, without named parameters, using ordinal indexes return PheryResponse::factory() ->alert($args[0]) ->alert($args[1]) ->alert($param['param1']) ->alert((string)$param[0]) ->alert((string)$param[1]); }, 'the_one_with_expr' => 'the_one_with_expr', )) /** * Some extra data that will be passed to aliases functions * and callbacks. You can pass as many arguments you want, just * make sure to name them properly, so you dont get lost. * If you dont pass an associative array, you'll have to access * the arguments using ordinal indexes (that is the case with * the 1 and the 'argument') */ ->data(array('param1' => 'named as param1'), 1, 'argument') /** * Finally, process for "test3" or "the_one_with_expr" */ ->process(false); $phery ->config(array( // Catch ALL the errors and use the internal error handler 'error_reporting' => E_ALL )) ->callback(array('before' => array(), 'after' => array())) ->set(array( 'on_purpose_exception' => function () { strlen($code); }, 'deep-nesting' => function(){ $r = new PheryResponse('<h3/>'); $d = new PheryResponse('<p/>'); $v = new PheryResponse('<div id="blah_'.(mt_rand()).'"/>'); return $r->append( $d ->append( $v ->text('this element can be clicked') ->bind('click', PheryFunction::factory('function(){ alert(this.id); }')) ) )->insertAfter(PheryResponse::factory()->this); }, 'colorbox' => function($data){ if (!empty($data['close'])) { return PheryResponse::factory() //->jquery->colorbox->close(); // or // ->call(array('$', 'colorbox', 'close')); // or ->access(array('$','colorbox'))->close(); } if (empty($data['other-way-around'])) { return PheryResponse::factory() ->jquery ->colorbox(array( 'html' => Phery::link_to('Look, im inside PHP, loaded with everything already ;)<br>Clicking this will call $.colorbox.close();', 'colorbox', array('args' => array('close' => true))), )); } return PheryResponse::factory() ->jquery ->colorbox(array( 'inline' => true, 'href' => PheryResponse::factory()->this->parent(), )); }, 'fileupload' => function($data) { $r = new PheryResponse; $files = $r->files('files'); foreach ($files as $index => $file) { unset($files[$index]['tmp_name']); } return $r->dump_vars($files); }, 'autocomplete' => function($data) { $r = new PheryResponse; $states = array( 'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming', ); $lis = array(); $search = trim($data['state']); foreach($states as $state) { if (stripos($state, $search) !== false) { $lis[] = '<li>' . $state . '</li>'; } } $r->this->find('ul')->html(join('', $lis)); return $r; }, 'unless' => function(){ $r = new PheryResponse; return $r->jquery('<div>HELLO!</div>')->css('backgroundColor', 'red')->unless(PheryFunction::factory('return false;'))->appendTo('body')->alert('done!'); }, 'incase' => function(){ $r = new PheryResponse; return $r->incase(PheryResponse::factory()->this->phery('data', 'temp'))->alert('hi')->alert('2'); }, 'getjson' => function(){ $r = new PheryResponse; return $r->jquery->getJSON('https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=twitterapi&count=2'); }, 'setvar' => function(){ return PheryResponse::factory()->set_var('doh', array(1, PheryResponse::factory()->this)); }, 'unsetvar' => function(){ return PheryResponse::factory()->unset_var('doh'); }, 'getvar' => function(){ return PheryResponse::factory()->dump_vars('colorbox entry point', PheryResponse::factory()->access(array('$','colorbox'))); }, 'pubsub' => function(){ $r = new PheryResponse; switch (rand(1,4)): case 1: $r->publish('test', array(PheryResponse::factory()->this))->dump_vars(1); break; case 2: $r->publish('test2')->dump_vars(2); break; case 3: $r->publish('test2', array('hooray'))->dump_vars(3); break; case 4: $r->phery_broadcast('test', array('hooray'))->dump_vars(4); break; endswitch; return $r; }, 'objcall' => function(){ $r = new PheryResponse; return $r->objinstance->blob('param'); } )) ->process(); } catch (PheryException $exc) { /** * will trigger for "nonexistant" call * This will only be reached if 'exceptions' is set to TRUE * Otherwise it will fail silently, and return an empty * JSON response object {} */ Phery::respond( PheryResponse::factory() ->merge('my name is') // merge a named response ->renew_csrf($phery) ->exception($exc->getMessage()) ); exit; } $exception = array('from' => (__LINE__ - 17), 'to' => (__LINE__ - 2)); ?> <!doctype html> <html> <head> <script src="//code.jquery.com/jquery-2.1.1.min.js"></script> <meta charset="utf-8"> <title>phery.js AJAX jQuery</title> <?php echo $csrf_token; ?> <script src="//cdn.rawgit.com/jackmoore/colorbox/master/jquery.colorbox-min.js" id="colorbox-script" type="text/javascript"></script> <link rel="stylesheet" href="//cdn.rawgit.com/jackmoore/colorbox/master/example1/colorbox.css"> <script src="phery.js" type="text/javascript"></script> <script type="text/javascript"> function test(number_array) { var total = 0; for (var x = 0; x < number_array.length; x++) { total += number_array[x]; } alert(total); } var $peak, $usage; $(function () { // cache our DOM elements that will receive the memory info $peak = $('#peak'); $usage = $('#usage'); $('#version').text('jQuery Version: ' + $().jquery + ' / phery: ' + phery.version); $('div.test').on({ 'test':function () { // bind a custom event to the DIVs $(this).show(0).text('triggered custom event "TEST"!'); } }); $.scrollTo = function(el, speed){ el = $(el); if (el.length) { var top = el.offset().top; if (speed) { $(window).animate({'scrollTop': top}, speed); } else { $(window).scrollTop(top); } } }; /***************************** * RECEIVE ANY TYPE OF DATA * *****************************/ /* * * Manually process the result of ajax call, can be anything * */ $('#special').on({ 'phery:done':function (data, text, xhr) { // The object will receive the text, return data from 'test' function, it's a JSON string //alert(text); // Now lets convert back to an object var obj = $.parseJSON(text); console.log(['text: ', text, 'json: ', obj]); // Do stuff with new obj // Returning false will prevent the parser to continue executing the commands and parsing // for jquery calls, because this text/html answer won't have any return false; } }) // The data-phery-type must override the type to 'html', since the default is 'json' .phery('data', 'type', 'html'); /* * * Bind the phery:always, after data was received, and there was no error * */ $('#special2').on({ 'phery:always':function (xhr) { var $this = $(this); $this.show(0); if ($this.data('testing')) { $('div.test2').text(('$.data for item "nice" is "' + $this.data('testing')['nice']) + '"'); } } }); window.obj = function(blob){ this.hello = 'world'; this.blob = function(){ console.log(blob, Array.prototype.concat.call(arguments)); }; }; window.obj._private = function(msg){ console.log(msg); }; window.obj.method = function(){ this._private('Private this'); }; window.objinstance = new window.obj('blob'); /**************************** * FORMAT CODE FROM TABLES * ****************************/ var to_pre = function (e) { var $div = $('div.test:eq(0)'); var text = $div.html(); // This doesnt work for IE7 or IE8, no idea why, the CRLF wont be replaced by <br> $div.html('<pre>' + text + '</pre>'); }; /* * * Let's just bind to the form, so we can apply some formatting to the text coming from print_r() PHP * */ $(document).on('phery:always', 'form', to_pre); /************************** * TEST FORM TOGGLES * **************************/ var $form = $('#testform'); var f = function (el, name) { var $this = $(el); var $submit = $form.phery('data', 'submit'); $submit[name] = $this.prop('checked'); $form.phery('data', 'submit', $submit); }; $('#disable').click(function () { f(this, 'disabled'); }); $('#all').click(function () { f(this, 'all'); }); var $loading = $('#loading'); /************************** * EXCEPTION HIGHLIGHT * **************************/ $(document) .on('mouseenter', '#exceptions a', function(){ var $this = $(this); if ($this.data('target')) { $this.data('target').addClass('focus'); } }) .on('click', '#exceptions a', function(){ var $this = $(this); $.scrollTo($this.data('target')); }) .on('mouseout', '#exceptions a', function(){ var $this = $(this); if ($this.data('target')) { $this.data('target').removeClass('focus'); } }); /***************************** * SEE PHP CODE/TOGGLE CODE * *****************************/ $(document) .on('phery:beforeSend', '.togglecode', function(e){ var $this = $(this), code = $this.parent().find('.code'), empty = $.trim(code.text()) === ''; if (!empty) { code.toggle(); return false; } $this.text('Toggle PHP code'); code.show(); return true; }); /************************** * GLOBAL AJAX EVENTS * **************************/ /* * * Global phery.js events * * You can set global events to be triggered, in this case, fadeIn and out the loading div * On global events, the current delegated dom node will be available in event.target */ phery.on({ 'before':function (event) { $loading.removeClass('error').stop(true).fadeIn('fast'); // catch all event to apply some classes and arguments if (event.$target.is('#modify')) { event.$target.phery('set_args', { 'alert':event.$target.next('input').val(), 'callback':'callme' }); } else { // disable for our AJAX container and autocomplete if (!event.$target.is('div#container,div.autocomplete')) { $(event.$target).addClass('loading'); } } }, 'always':function (event, xhr) { $loading.stop(true).fadeOut('fast'); $(event.$target).removeClass('loading'); }, 'fail':function (event, xhr, status) { if (status !== 'canceled') { $loading.addClass('error'); } if (status === 'timeout') { event.$target.phery('exception', 'Timeout and gave up retrying!!'); // or event.$target.phery().exception('Timeout and gave up retrying!!'); } }, 'exception':function (event, exception, data) { var $exceptions = $('#exceptions'); var a = $('<a/>', { 'text': event.$target[0].tagName + (event.$target.attr('id') ? ' (' + event.$target.attr('id') + ')' : ''), 'title': 'Click to scroll into view' }).data('target', event.$target); if (data && 'code' in data) { var type = ''; switch (data.code) { case <?php echo E_NOTICE; ?>: type = 'E_NOTICE'; break; case <?php echo E_ERROR; ?>: type = 'E_ERROR'; break; case <?php echo E_WARNING; ?>: type = 'E_WARNING'; break; default: break; } $exceptions.append( $('<li/>', { 'text':type + ': ' + exception + ' on file ' + data.file + ' line ' + data.line + ' on ' }).append(a) ); } else { $exceptions.append( $('<li/>', { 'text':exception + ' on ' }).append(a) ); } var $window = $(window); while ($exceptions.height() > $window.height() + 10) { $exceptions.find('li:not(.clear):first').remove(); } } }); window.callme = function (e) { alert(e); }; /************************** * CONFIG PHERY.JS * **************************/ phery.config({ /* * Retry one more time, if fails, then trigger events.error */ 'ajax.retries':1, /* 2 seconds timeout for AJAX /* any AJAX option can be set through jQuery */ 'ajax.timeout': 5000, /* * Enable phery:* events on elements */ 'enable.per_element.events':true, /* * Enable logging and output to console.log. * Shouldn't be enabled on production because * of building up an internal log of messages */ 'enable.log':true, /* * Log messages that can be accessed on phery.log() */ 'enable.log_history':true, /* * Enable inline loading of responses */ 'inline.enabled': true }); $loading.fadeOut(0); /************************** * FORM VALIDATION * **************************/ $('#validate').click(function () { if ($(this).prop('checked')) { load_validate(); } }); /************************** * COLORBOX * **************************/ $('#colorbox-btn').click(function(){ phery.remote('colorbox'); }); /************************** * JSON LOADING DATA * **************************/ $('#loaddata').on({ 'phery:json': function(event, data){ var tbody = $('#datatable tbody'), tr; for (var x = 0; x < data.length; x++) { tr = $('<tr/>', { 'id': data[x].id }) .html('<td>'+data[x].id+'</td><td>'+data[x].data.name+'</td><td>'+data[x].data.value+'</td>'); tbody.append(tr); } } }); /************************** * AJAX PARTIAL VIEWS * **************************/ $('#ajax').on('click',function () { var $this = $(this); if ($this.prop('checked')) { /* Setup automatic view rendering using ajax */ phery.view({ '#container':{ 'render': function(html, data, passdata){ var $this = this; $this.fadeOut('slow').promise().done(function(){ $this.html('').html(html); $this.fadeIn('fast'); }); }, 'exclude': ['?page=excluded'], /* We want only the links inside the container to be ajaxified */ 'selector':'a', /* Enable the browser history, and change the title */ 'afterHtml':function (data, passdata) { document.title = data.title; if (window.history && typeof window.history['pushState'] === 'function') { /* Good browsers get history API */ if (typeof passdata['popstate'] === 'undefined') { window.history.pushState(data, data.title, data.url); } } }, /* phery:params let us add params, that ends in callback params and wont get mixed with arguments */ 'params':function (event, data) { // Show the calling URL to PHP, since it knows nothing data['origin'] = window.location.href; } } }); /* Good browsers get back/forward button ajax navigation ;) */ window.onpopstate = function (e) { phery.view('#container').navigate_to(document.location.href, null, {'popstate':true}); }; } else { phery.view({ // Disable view, page will work normally '#container':false }); } }).triggerHandler('click'); /************************** * ENABLE/DISABLE DEBUG * *************************/ $('#debug').click(function () { phery.config({ /* * Enable debug verbose */ 'debug.enable':!phery.config('debug.enable') }); var enabled = phery.config('debug.enable'); $(this) .css('color', enabled ? '#0f0' : '#f00') .find('span')
php
MIT
f22d04625d84d4631c6b2ea0435fe6623c9b1c8e
2026-01-05T05:11:11.357343Z
true
pheryjs/phery
https://github.com/pheryjs/phery/blob/f22d04625d84d4631c6b2ea0435fe6623c9b1c8e/src/Phery/PheryFunction.php
src/Phery/PheryFunction.php
<?php /** * The MIT License (MIT) * * Copyright © 2010-2013 Paulo Cesar, http://phery-php-ajax.net/ * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the “Software”), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * @link http://phery-php-ajax.net/ * @author Paulo Cesar * @version 2.7.2 * @license http://opensource.org/licenses/MIT MIT License */ namespace Phery; /** * Create an anonymous function for use on Javascript callbacks * * @package Phery */ class PheryFunction { /** * Parameters that will be replaced inside the response * @var array */ protected $parameters = array(); /** * The function string itself * @var array */ protected $value = null; /** * Sets new raw parameter to be passed, that will be eval'ed. * If you don't pass the function(){ } it will be appended * * <code> * $raw = new PheryFunction('function($val){ return $val; }'); * // or * $raw = new PheryFunction('alert("done");'); // turns into function(){ alert("done"); } * </code> * * @param string|array $value Raw function string. If you pass an array, * it will be joined with a line feed \n * @param array $parameters You can pass parameters that will be replaced * in the $value when compiling */ public function __construct($value, $parameters = array()) { if (!empty($value)) { // Set the expression string if (is_array($value)) { $this->value = join("\n", $value); } elseif (is_string($value)) { $this->value = $value; } if (!preg_match('/^\s*function/im', $this->value)) { $this->value = 'function(){' . $this->value . '}'; } $this->parameters = $parameters; } } /** * Bind a variable to a parameter. * * @param string $param parameter key to replace * @param mixed $var variable to use * @return PheryFunction */ public function bind($param, & $var) { $this->parameters[$param] =& $var; return $this; } /** * Set the value of a parameter. * * @param string $param parameter key to replace * @param mixed $value value to use * @return PheryFunction */ public function param($param, $value) { $this->parameters[$param] = $value; return $this; } /** * Add multiple parameter values. * * @param array $params list of parameter values * @return PheryFunction */ public function parameters(array $params) { $this->parameters = $params + $this->parameters; return $this; } /** * Get the value as a string. * * @return string */ public function value() { return (string) $this->value; } /** * Return the value of the expression as a string. * * <code> * echo $expression; * </code> * * @return string */ public function __toString() { return $this->value(); } /** * Compile function and return it. Replaces any parameters with * their given values. * * @return string */ public function compile() { $value = $this->value(); if ( ! empty($this->parameters)) { $params = $this->parameters; $value = strtr($value, $params); } return $value; } /** * Static instantation for PheryFunction * * @param string|array $value * @param array $parameters * * @return PheryFunction */ public static function factory($value, $parameters = array()) { return new PheryFunction($value, $parameters); } }
php
MIT
f22d04625d84d4631c6b2ea0435fe6623c9b1c8e
2026-01-05T05:11:11.357343Z
false
pheryjs/phery
https://github.com/pheryjs/phery/blob/f22d04625d84d4631c6b2ea0435fe6623c9b1c8e/src/Phery/PheryException.php
src/Phery/PheryException.php
<?php /** * The MIT License (MIT) * * Copyright © 2010-2013 Paulo Cesar, http://phery-php-ajax.net/ * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the “Software”), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * @link http://phery-php-ajax.net/ * @author Paulo Cesar * @version 2.7.2 * @license http://opensource.org/licenses/MIT MIT License */ namespace Phery; use Exception; /** * Exception class for Phery specific exceptions * * @package Phery */ class PheryException extends Exception { }
php
MIT
f22d04625d84d4631c6b2ea0435fe6623c9b1c8e
2026-01-05T05:11:11.357343Z
false
pheryjs/phery
https://github.com/pheryjs/phery/blob/f22d04625d84d4631c6b2ea0435fe6623c9b1c8e/src/Phery/PheryResponse.php
src/Phery/PheryResponse.php
<?php /** * The MIT License (MIT) * * Copyright © 2010-2013 Paulo Cesar, http://phery-php-ajax.net/ * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the “Software”), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * @link http://phery-php-ajax.net/ * @author Paulo Cesar * @version 2.7.2 * @license http://opensource.org/licenses/MIT MIT License */ namespace Phery; use ArrayObject; /** * Standard response for the json parser * * @package Phery * * @method PheryResponse ajax(string $url, array $settings = null) Perform an asynchronous HTTP (Ajax) request. * @method PheryResponse ajaxSetup(array $obj) Set default values for future Ajax requests. * @method PheryResponse post(string $url, PheryFunction $success = null) Load data from the server using a HTTP POST request. * @method PheryResponse get(string $url, PheryFunction $success = null) Load data from the server using a HTTP GET request. * @method PheryResponse getJSON(string $url, PheryFunction $success = null) Load JSON-encoded data from the server using a GET HTTP request. * @method PheryResponse getScript(string $url, PheryFunction $success = null) Load a JavaScript file from the server using a GET HTTP request, then execute it. * @method PheryResponse detach() Detach a DOM element retaining the events attached to it * @method PheryResponse prependTo(string $target) Prepend DOM element to target * @method PheryResponse appendTo(string $target) Append DOM element to target * @method PheryResponse replaceWith(string $newContent) The content to insert. May be an HTML string, DOM element, or jQuery object. * @method PheryResponse css(string $propertyName, mixed $value = null) propertyName: A CSS property name. value: A value to set for the property. * @method PheryResponse toggle($duration_or_array_of_options, PheryFunction $complete = null) Display or hide the matched elements. * @method PheryResponse is(string $selector) Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. * @method PheryResponse hide(string $speed = 0) Hide an object, can be animated with 'fast', 'slow', 'normal' * @method PheryResponse show(string $speed = 0) Show an object, can be animated with 'fast', 'slow', 'normal' * @method PheryResponse toggleClass(string $className) Add/Remove a class from an element * @method PheryResponse data(string $name, mixed $data) Add data to element * @method PheryResponse addClass(string $className) Add a class from an element * @method PheryResponse removeClass(string $className) Remove a class from an element * @method PheryResponse animate(array $prop, int $dur, string $easing = null, PheryFunction $cb = null) Perform a custom animation of a set of CSS properties. * @method PheryResponse trigger(string $eventName, array $args = null) Trigger an event * @method PheryResponse triggerHandler(string $eventType, array $extraParameters = null) Execute all handlers attached to an element for an event. * @method PheryResponse fadeIn(int|string $speed = null) Fade in an element * @method PheryResponse filter(string $selector) Reduce the set of matched elements to those that match the selector or pass the function's test. * @method PheryResponse fadeTo(int $dur, float $opacity) Fade an element to opacity * @method PheryResponse fadeOut(int|string $speed = null) Fade out an element * @method PheryResponse slideUp(int $dur, PheryFunction $cb = null) Hide with slide up animation * @method PheryResponse slideDown(int $dur, PheryFunction $cb = null) Show with slide down animation * @method PheryResponse slideToggle(int $dur, PheryFunction $cb = null) Toggle show/hide the element, using slide animation * @method PheryResponse unbind(string $name) Unbind an event from an element * @method PheryResponse undelegate() Remove a handler from the event for all elements which match the current selector, now or in the future, based upon a specific set of root elements. * @method PheryResponse stop() Stop animation on elements * @method PheryResponse val(string $content) Set the value of an element * @method PheryResponse removeData(string $name) Remove element data added with data() * @method PheryResponse removeAttr(string $name) Remove an attribute from an element * @method PheryResponse scrollTop(int $val) Set the scroll from the top * @method PheryResponse scrollLeft(int $val) Set the scroll from the left * @method PheryResponse height(int $val = null) Get or set the height from the left * @method PheryResponse width(int $val = null) Get or set the width from the left * @method PheryResponse slice(int $start, int $end) Reduce the set of matched elements to a subset specified by a range of indices. * @method PheryResponse not(string $val) Remove elements from the set of matched elements. * @method PheryResponse eq(int $selector) Reduce the set of matched elements to the one at the specified index. * @method PheryResponse offset(array $coordinates) Set the current coordinates of every element in the set of matched elements, relative to the document. * @method PheryResponse map(PheryFunction $callback) Pass each element in the current matched set through a function, producing a new jQuery object containing the return values. * @method PheryResponse children(string $selector) Get the children of each element in the set of matched elements, optionally filtered by a selector. * @method PheryResponse closest(string $selector) Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree. * @method PheryResponse find(string $selector) Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. * @method PheryResponse next(string $selector = null) Get the immediately following sibling of each element in the set of matched elements, optionally filtered by a selector. * @method PheryResponse nextAll(string $selector) Get all following siblings of each element in the set of matched elements, optionally filtered by a selector. * @method PheryResponse nextUntil(string $selector) Get all following siblings of each element up to but not including the element matched by the selector. * @method PheryResponse parentsUntil(string $selector) Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector. * @method PheryResponse offsetParent() Get the closest ancestor element that is positioned. * @method PheryResponse parent(string $selector = null) Get the parent of each element in the current set of matched elements, optionally filtered by a selector. * @method PheryResponse parents(string $selector) Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector. * @method PheryResponse prev(string $selector = null) Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector. * @method PheryResponse prevAll(string $selector) Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector. * @method PheryResponse prevUntil(string $selector) Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector. * @method PheryResponse siblings(string $selector) Get the siblings of each element in the set of matched elements, optionally filtered by a selector. * @method PheryResponse add(PheryResponse $selector) Add elements to the set of matched elements. * @method PheryResponse contents() Get the children of each element in the set of matched elements, including text nodes. * @method PheryResponse end() End the most recent filtering operation in the current chain and return the set of matched elements to its previous state. * @method PheryResponse after(string $content) Insert content, specified by the parameter, after each element in the set of matched elements. * @method PheryResponse before(string $content) Insert content, specified by the parameter, before each element in the set of matched elements. * @method PheryResponse insertAfter(string $target) Insert every element in the set of matched elements after the target. * @method PheryResponse insertBefore(string $target) Insert every element in the set of matched elements before the target. * @method PheryResponse unwrap() Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place. * @method PheryResponse wrap(string $wrappingElement) Wrap an HTML structure around each element in the set of matched elements. * @method PheryResponse wrapAll(string $wrappingElement) Wrap an HTML structure around all elements in the set of matched elements. * @method PheryResponse wrapInner(string $wrappingElement) Wrap an HTML structure around the content of each element in the set of matched elements. * @method PheryResponse delegate(string $selector, string $eventType, PheryFunction $handler) Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements. * @method PheryResponse one(string $eventType, PheryFunction $handler) Attach a handler to an event for the elements. The handler is executed at most once per element. * @method PheryResponse bind(string $eventType, PheryFunction $handler) Attach a handler to an event for the elements. * @method PheryResponse each(PheryFunction $function) Iterate over a jQ object, executing a function for each matched element. * @method PheryResponse phery(string $function = null, array $args = null) Access the phery() on the select element(s) * @method PheryResponse addBack(string $selector = null) Add the previous set of elements on the stack to the current set, optionally filtered by a selector. * @method PheryResponse clearQueue(string $queueName = null) Remove from the queue all items that have not yet been run. * @method PheryResponse clone(boolean $withDataAndEvents = null, boolean $deepWithDataAndEvents = null) Create a deep copy of the set of matched elements. * @method PheryResponse dblclick(array $eventData = null, PheryFunction $handler = null) Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element. * @method PheryResponse always(PheryFunction $callback) Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element. * @method PheryResponse done(PheryFunction $callback) Add handlers to be called when the Deferred object is resolved. * @method PheryResponse fail(PheryFunction $callback) Add handlers to be called when the Deferred object is rejected. * @method PheryResponse progress(PheryFunction $callback) Add handlers to be called when the Deferred object is either resolved or rejected. * @method PheryResponse then(PheryFunction $donecallback, PheryFunction $failcallback = null, PheryFunction $progresscallback = null) Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. * @method PheryResponse empty() Remove all child nodes of the set of matched elements from the DOM. * @method PheryResponse finish(string $queue) Stop the currently-running animation, remove all queued animations, and complete all animations for the matched elements. * @method PheryResponse focus(array $eventData = null, PheryFunction $handler = null) Bind an event handler to the "focusout" JavaScript event. * @method PheryResponse focusin(array $eventData = null, PheryFunction $handler = null) Bind an event handler to the "focusin" event. * @method PheryResponse focusout(array $eventData = null, PheryFunction $handler = null) Bind an event handler to the "focus" JavaScript event, or trigger that event on an element. * @method PheryResponse has(string $selector) Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. * @method PheryResponse index(string $selector = null) Search for a given element from among the matched elements. * @method PheryResponse on(string $events, string $selector, array $data = null, PheryFunction $handler = null) Attach an event handler function for one or more events to the selected elements. * @method PheryResponse off(string $events, string $selector = null, PheryFunction $handler = null) Remove an event handler. * @method PheryResponse prop(string $propertyName, $data_or_function = null) Set one or more properties for the set of matched elements. * @method PheryResponse promise(string $type = null, array $target = null) Return a Promise object to observe when all actions of a certain type bound to the collection, queued or not, have finished. * @method PheryResponse pushStack(array $elements, string $name = null, array $arguments = null) Add a collection of DOM elements onto the jQuery stack. * @method PheryResponse removeProp(string $propertyName) Remove a property for the set of matched elements. * @method PheryResponse resize($eventData_or_function = null, PheryFunction $handler = null) Bind an event handler to the "resize" JavaScript event, or trigger that event on an element. * @method PheryResponse scroll($eventData_or_function = null, PheryFunction $handler = null) Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element. * @method PheryResponse select($eventData_or_function = null, PheryFunction $handler = null) Bind an event handler to the "select" JavaScript event, or trigger that event on an element. * @method PheryResponse serializeArray() Encode a set of form elements as an array of names and values. * @method PheryResponse replaceAll(string $target) Replace each target element with the set of matched elements. * @method PheryResponse reset() Reset a form element. * @method PheryResponse toArray() Retrieve all the DOM elements contained in the jQuery set, as an array. * @property PheryResponse this The DOM element that is making the AJAX call * @property PheryResponse jquery The $ jQuery object, can be used to call $.getJSON, $.getScript, etc * @property PheryResponse window Shortcut for jquery('window') / $(window) * @property PheryResponse document Shortcut for jquery('document') / $(document) */ class PheryResponse extends ArrayObject { /** * All responses that were created in the run, access them through their name * * @var PheryResponse[] */ protected static $responses = array(); /** * Common data available to all responses * * @var array */ protected static $global = array(); /** * Last jQuery selector defined * * @var string */ protected $last_selector = null; /** * Restore the selector if set * * @var string */ protected $restore = null; /** * Array containing answer data * * @var array */ protected $data = array(); /** * Array containing merged data * * @var array */ protected $merged = array(); /** * This response config * * @var array */ protected $config = array(); /** * Name of the current response * * @var string */ protected $name = null; /** * Internal count for multiple paths * * @var int */ protected static $internal_count = 0; /** * Internal count for multiple commands * * @var int */ protected $internal_cmd_count = 0; /** * Is the criteria from unless fulfilled? * * @var bool */ protected $matched = true; /** * Construct a new response * * @param string $selector Create the object already selecting the DOM element * @param array $constructor Only available if you are creating an element, like $('&lt;p/&gt;') */ public function __construct($selector = null, array $constructor = array()) { parent::__construct(); $this->config = array( 'typecast_objects' => true, 'convert_integers' => true, ); $this->jquery($selector, $constructor); $this->set_response_name(uniqid("", true)); } /** * Change the config for this response * You may pass in an associative array of your config * * @param array $config * <pre> * array( * 'convert_integers' => true/false * 'typecast_objects' => true/false * </pre> * * @return PheryResponse */ public function set_config(array $config) { if (isset($config['convert_integers'])) { $this->config['convert_integers'] = (bool)$config['convert_integers']; } if (isset($config['typecast_objects'])) { $this->config['typecast_objects'] = (bool)$config['typecast_objects']; } return $this; } /** * Increment the internal counter, so there are no conflicting stacked commands * * @param string $type Selector * @param boolean $force Force unajusted selector into place * @return string The previous overwritten selector */ protected function set_internal_counter($type, $force = false) { $last = $this->last_selector; if ($force && $last !== null && !isset($this->data[$last])) { $this->data[$last] = array(); } $this->last_selector = '{' . $type . (self::$internal_count++) . '}'; return $last; } /** * Renew the CSRF token on a given Phery instance * Resets any selectors that were being chained before * * @param Phery $instance Instance of Phery * @return PheryResponse */ public function renew_csrf(Phery $instance) { if ($instance->config('csrf') === true) { $this->cmd(13, array($instance->csrf())); } return $this; } /** * Set the name of this response * * @param string $name Name of current response * * @return PheryResponse */ public function set_response_name($name) { if (!empty($this->name)) { unset(self::$responses[$this->name]); } $this->name = $name; self::$responses[$this->name] = $this; return $this; } /** * Broadcast a remote message to the client to all elements that * are subscribed to them. This removes the current selector if any * * @param string $name Name of the browser subscribed topic on the element * @param array [$params] Any params to pass to the subscribed topic * * @return PheryResponse */ public function phery_broadcast($name, array $params = array()) { $this->last_selector = null; return $this->cmd(12, array($name, array($this->typecast($params, true, true)), true)); } /** * Publish a remote message to the client that is subscribed to them * This removes the current selector (if any) * * @param string $name Name of the browser subscribed topic on the element * @param array [$params] Any params to pass to the subscribed topic * * @return PheryResponse */ public function publish($name, array $params = array()) { $this->last_selector = null; return $this->cmd(12, array($name, array($this->typecast($params, true, true)))); } /** * Get the name of this response * * @return null|string */ public function get_response_name() { return $this->name; } /** * Borrowed from Ruby, the next imediate instruction will be executed unless * it matches this criteria. * * <code> * $count = 3; * PheryResponse::factory() * // if not $count equals 2 then * ->unless($count === 2) * ->call('func'); // This won't trigger, $count is 2 * </code> * * <code> * PheryResponse::factory('.widget') * ->unless(PheryFunction::factory('return !this.hasClass("active");'), true) * ->remove(); // This won't remove if the element have the active class * </code> * * * @param boolean|PheryFunction $condition * When not remote, can be any criteria that evaluates to FALSE. * When it's remote, if passed a PheryFunction, it will skip the next * iteration unless the return value of the PheryFunction is false. * Passing a PheryFunction automatically sets $remote param to true * * @param bool $remote * Instead of doing it in the server side, do it client side, for example, * append something ONLY if an element exists. The context (this) of the function * will be the last selected element or the calling element. * * @return PheryResponse */ public function unless($condition, $remote = false) { if (!$remote && !($condition instanceof PheryFunction) && !($condition instanceof PheryResponse)) { $this->matched = !$condition; } else { $this->set_internal_counter('!', true); $this->cmd(0xff, array($this->typecast($condition, true, true))); } return $this; } /** * It's the opposite of unless(), the next command will be issued in * case the condition is true * * <code> * $count = 3; * PheryResponse::factory() * // if $count is greater than 2 then * ->incase($count > 2) * ->call('func'); // This will be executed, $count is greater than 2 * </code> * * <code> * PheryResponse::factory('.widget') * ->incase(PheryFunction::factory('return this.hasClass("active");'), true) * ->remove(); // This will remove the element if it has the active class * </code> * * @param boolean|callable|PheryFunction $condition * When not remote, can be any criteria that evaluates to TRUE. * When it's remote, if passed a PheryFunction, it will execute the next * iteration when the return value of the PheryFunction is true * * @param bool $remote * Instead of doing it in the server side, do it client side, for example, * append something ONLY if an element exists. The context (this) of the function * will be the last selected element or the calling element. * * @return PheryResponse */ public function incase($condition, $remote = false) { if (!$remote && !($condition instanceof PheryFunction) && !($condition instanceof PheryResponse)) { $this->matched = $condition; } else { $this->set_internal_counter('=', true); $this->cmd(0xff, array($this->typecast($condition, true, true))); } return $this; } /** * This helper function is intended to normalize the $_FILES array, because when uploading multiple * files, the order gets messed up. The result will always be in the format: * * <code> * array( * 'name of the file input' => array( * array( * 'name' => ..., * 'tmp_name' => ..., * 'type' => ..., * 'error' => ..., * 'size' => ..., * ), * array( * 'name' => ..., * 'tmp_name' => ..., * 'type' => ..., * 'error' => ..., * 'size' => ..., * ), * ) * ); * </code> * * So you can always do like (regardless of one or multiple files uploads) * * <code> * <input name="avatar" type="file" multiple> * <input name="pic" type="file"> * * <?php * foreach(PheryResponse::files('avatar') as $index => $file){ * if (is_uploaded_file($file['tmp_name'])){ * //... * } * } * * foreach(PheryResponse::files() as $field => $group){ * foreach ($group as $file){ * if (is_uploaded_file($file['tmp_name'])){ * if ($field === 'avatar') { * //... * } else if ($field === 'pic') { * //... * } * } * } * } * ?> * </code> * * If no files were uploaded, returns an empty array. * * @param string|bool $group Pluck out the file group directly * @return array */ public static function files($group = false) { $result = array(); foreach ($_FILES as $name => $keys) { if (is_array($keys)) { if (is_array($keys['name'])) { $len = count($keys['name']); for ($i = 0; $i < $len; $i++) { $result[$name][$i] = array( 'name' => $keys['name'][$i], 'tmp_name' => $keys['tmp_name'][$i], 'type' => $keys['type'][$i], 'error' => $keys['error'][$i], 'size' => $keys['size'][$i], ); } } else { $result[$name] = array( $keys ); } } } return $group !== false && isset($result[$group]) ? $result[$group] : $result; } /** * Set a global value that can be accessed through $pheryresponse['value'] * It's available in all responses, and can also be acessed using self['value'] * * @param array|string Key => value combination or the name of the global * @param mixed $value [Optional] */ public static function set_global($name, $value = null) { if (isset($name) && is_array($name)) { foreach ($name as $n => $v) { self::$global[$n] = $v; } } else { self::$global[$name] = $value; } } /** * Unset a global variable * * @param string $name Variable name */ public static function unset_global($name) { unset(self::$global[$name]); } /** * Will check for globals and local values * * @param string|int $index * * @return mixed */ public function offsetExists($index) { if (isset(self::$global[$index])) { return true; } return parent::offsetExists($index); } /** * Set local variables, will be available only in this instance * * @param string|int|null $index * @param mixed $newval * * @return void */ public function offsetSet($index, $newval) { if ($index === null) { $this[] = $newval; } else { parent::offsetSet($index, $newval); } } /** * Return null if no value * * @param mixed $index * * @return mixed|null */ public function offsetGet($index) { if (parent::offsetExists($index)) { return parent::offsetGet($index); } if (isset(self::$global[$index])) { return self::$global[$index]; } return null; } /** * Get a response by name * * @param string $name * * @return PheryResponse|null */ public static function get_response($name) { if (isset(self::$responses[$name]) && self::$responses[$name] instanceof PheryResponse) { return self::$responses[$name]; } return null; } /** * Get merged response data as a new PheryResponse. * This method works like a constructor if the previous response was destroyed * * @param string $name Name of the merged response * @return PheryResponse|null */ public function get_merged($name) { if (isset($this->merged[$name])) { if (isset(self::$responses[$name])) { return self::$responses[$name]; } $response = new PheryResponse; $response->data = $this->merged[$name]; return $response; } return null; } /** * Same as phery.remote() * * @param string $remote Function * @param array $args Arguments to pass to the * @param array $attr Here you may set like method, target, type, cache, proxy * @param boolean $directCall Setting to false returns the jQuery object, that can bind * events, append to DOM, etc * * @return PheryResponse */ public function phery_remote($remote, $args = array(), $attr = array(), $directCall = true) { $this->set_internal_counter('-'); return $this->cmd(0xff, array( $remote, $args, $attr, $directCall )); } /** * Set a global variable, that can be accessed directly through window object, * can set properties inside objects if you pass an array as the variable. * If it doesn't exist it will be created * * <code> * // window.customer_info = {'name': 'John','surname': 'Doe', 'age': 39} * PheryResponse::factory()->set_var('customer_info', array('name' => 'John', 'surname' => 'Doe', 'age' => 39)); * </code> * * <code> * // window.customer_info.name = 'John' * PheryResponse::factory()->set_var(array('customer_info','name'), 'John'); * </code> * * @param string|array $variable Global variable name * @param mixed $data Any data * @return PheryResponse */ public function set_var($variable, $data) { $this->last_selector = null; if (!empty($data) && is_array($data)) { foreach ($data as $name => $d) { $data[$name] = $this->typecast($d, true, true); } } else { $data = $this->typecast($data, true, true); } return $this->cmd(9, array( !is_array($variable) ? array($variable) : $variable, array($data) )); } /** * Delete a global variable, that can be accessed directly through window, can unset object properties, * if you pass an array * * <code> * PheryResponse::factory()->unset('customer_info'); * </code> * * <code> * PheryResponse::factory()->unset(array('customer_info','name')); // translates to delete customer_info['name'] * </code> * * @param string|array $variable Global variable name * @return PheryResponse */ public function unset_var($variable) { $this->last_selector = null; return $this->cmd(9, array( !is_array($variable) ? array($variable) : $variable, )); } /** * Create a new PheryResponse instance for chaining, fast and effective for one line returns * * <code> * function answer($data) * { * return * PheryResponse::factory('a#link-'.$data['rel']) * ->attr('href', '#') * ->alert('done'); * } * </code> * * @param string $selector optional * @param array $constructor Same as $('&lt;p/&gt;', {}) * * @static * @return PheryResponse */ public static function factory($selector = null, array $constructor = array()) { return new PheryResponse($selector, $constructor); } /** * Remove a batch of calls for a selector. Won't remove for merged responses.
php
MIT
f22d04625d84d4631c6b2ea0435fe6623c9b1c8e
2026-01-05T05:11:11.357343Z
true
pheryjs/phery
https://github.com/pheryjs/phery/blob/f22d04625d84d4631c6b2ea0435fe6623c9b1c8e/src/Phery/Phery.php
src/Phery/Phery.php
<?php /** * The MIT License (MIT) * * Copyright © 2010-2013 Paulo Cesar, http://phery-php-ajax.net/ * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the “Software”), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * @link http://phery-php-ajax.net/ * @author Paulo Cesar * @version 2.7.2 * @license http://opensource.org/licenses/MIT MIT License */ namespace Phery; use ArrayAccess; /** * Main class for Phery.js * * @package Phery */ class Phery implements ArrayAccess { /** * Exception on callback() function * * @see callback() * @type int */ const ERROR_CALLBACK = 0; /** * Exception on process() function * * @see process() */ const ERROR_PROCESS = 1; /** * Exception on set() function * * @see set() */ const ERROR_SET = 2; /** * Exception when the CSRF is invalid * * @see process() */ const ERROR_CSRF = 4; /** * Exception on static functions * * @see link_to() * @see select_for() * @see form_for() */ const ERROR_TO = 3; /** * Default encoding for your application * * @var string */ public static $encoding = 'UTF-8'; /** * Expose the paths on PheryResponse exceptions * * @var bool */ public static $expose_paths = false; /** * The functions registered * * @var array */ protected $functions = array(); /** * The callbacks registered * * @var array */ protected $callbacks = array(); /** * The callback data to be passed to callbacks and responses * @var array */ protected $data = array(); /** * Static instance for singleton * * @var Phery * @static */ protected static $instance = null; /** * Render view function * * @var array */ protected $views = array(); /** * Config * * <code> * 'exit_allowed' (boolean) * 'exceptions' (boolean) * 'return' (boolean) * 'error_reporting' (int) * 'csrf' (boolean) * 'set_always_available' (boolean) * 'auto_session' (boolean) * </code> * @var array * * @see config() */ protected $config = array(); /** * If the class was just initiated * * @var bool */ private $init = true; /** * Construct the new Phery instance * * @param array $config Config array */ public function __construct(array $config = array()) { $this->callbacks = array( 'before' => array(), 'after' => array() ); $config = array_replace( array( 'exit_allowed' => true, 'exceptions' => false, 'return' => false, 'csrf' => false, 'set_always_available' => false, 'error_reporting' => false, 'auto_session' => true, ), $config ); $this->config($config); } /** * Set callbacks for before and after filters. * Callbacks are useful for example, if you have 2 or more AJAX functions, and you need to perform * the same data manipulation, like removing an 'id' from the $_POST['args'], or to check for potential * CSRF or SQL injection attempts on all the functions, clean data or perform START TRANSACTION for database, etc * * @param array $callbacks The callbacks * * <pre> * array( * * // Set a function to be called BEFORE * // processing the request, if it's an * // AJAX to be processed request, can be * // an array of callbacks * * 'before' => array|function, * * // Set a function to be called AFTER * // processing the request, if it's an AJAX * // processed request, can be an array of * // callbacks * * 'after' => array|function * ); * </pre> * * The callback function should be * * <pre> * * // $additional_args is passed using the callback_data() function, * // in this case, a before callback * * function before_callback($ajax_data, $internal_data){ * // Do stuff * $_POST['args']['id'] = $additional_args['id']; * return true; * } * * // after callback would be to save the data perhaps? Just to keep the code D.R.Y. * * function after_callback($ajax_data, $internal_data, $PheryResponse){ * $this->database->save(); * $PheryResponse->merge(PheryResponse::factory('#loading')->fadeOut()); * return true; * } * </pre> * * Returning false on the callback will make the process() phase to RETURN, but won't exit. * You may manually exit on the after callback if desired * Any data that should be modified will be inside $_POST['args'] (can be accessed freely on 'before', * will be passed to the AJAX function) * * @return Phery */ public function callback(array $callbacks) { if (isset($callbacks['before'])) { if (is_array($callbacks['before']) && !is_callable($callbacks['before'])) { foreach ($callbacks['before'] as $func) { if (is_callable($func)) { $this->callbacks['before'][] = $func; } else { self::exception($this, "The provided before callback function isn't callable", self::ERROR_CALLBACK); } } } else { if (is_callable($callbacks['before'])) { $this->callbacks['before'][] = $callbacks['before']; } else { self::exception($this, "The provided before callback function isn't callable", self::ERROR_CALLBACK); } } } if (isset($callbacks['after'])) { if (is_array($callbacks['after']) && !is_callable($callbacks['after'])) { foreach ($callbacks['after'] as $func) { if (is_callable($func)) { $this->callbacks['after'][] = $func; } else { self::exception($this, "The provided after callback function isn't callable", self::ERROR_CALLBACK); } } } else { if (is_callable($callbacks['after'])) { $this->callbacks['after'][] = $callbacks['after']; } else { self::exception($this, "The provided after callback function isn't callable", self::ERROR_CALLBACK); } } } return $this; } /** * Throw an exception if enabled * * @param Phery $phery Instance * @param string $exception * @param integer $code * * @throws PheryException * @return boolean */ protected static function exception($phery, $exception, $code) { if ($phery instanceof Phery && $phery->config['exceptions'] === true) { throw new PheryException($exception, $code); } return false; } /** * Set any data to pass to the callbacks * * @param mixed $args,... Parameters, can be anything * * @return Phery */ public function data($args) { foreach (func_get_args() as $arg) { if (is_array($arg)) { $this->data = array_merge_recursive($arg, $this->data); } else { $this->data[] = $arg; } } return $this; } /** * Encode PHP code to put inside data-phery-args, usually for updating the data there * * @param array $data Any data that can be converted using json_encode * @param string $encoding Encoding for the arguments * * @return string Return json_encode'd and htmlentities'd string */ public static function args(array $data, $encoding = 'UTF-8') { return htmlentities(json_encode($data), ENT_COMPAT, $encoding, false); } /** * Get the current token from the $_SESSION * * @return bool */ public function get_csrf_token() { if (!empty($_SESSION['phery']['csrf'])) { return $_SESSION['phery']['csrf']; } return false; } /** * Output the meta HTML with the token. * This method needs to use sessions through session_start * * @param bool $check Check if the current token is valid * @param bool $force It will renew the current hash every call * @return string|bool */ public function csrf($check = false, $force = false) { if ($this->config['csrf'] !== true) { return !empty($check) ? true : ''; } if (session_id() == '' && $this->config['auto_session'] === true) { @session_start(); } if ($check === false) { $current_token = $this->get_csrf_token(); if (($current_token !== false && $force) || $current_token === false) { $token = sha1(uniqid(microtime(true), true)); $_SESSION['phery'] = array( 'csrf' => $token ); $token = base64_encode($token); } else { $token = base64_encode($_SESSION['phery']['csrf']); } return "<meta id=\"csrf-token\" name=\"csrf-token\" content=\"{$token}\" />\n"; } else { if (empty($_SESSION['phery']['csrf'])) { return false; } return $_SESSION['phery']['csrf'] === base64_decode($check, true); } } /** * Check if the current call is an ajax call * * @param bool $is_phery Check if is an ajax call and a phery specific call * * @static * @return bool */ public static function is_ajax($is_phery = false) { switch ($is_phery) { case true: return (bool)(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strcasecmp($_SERVER['HTTP_X_REQUESTED_WITH'], 'XMLHttpRequest') === 0 && strtoupper($_SERVER['REQUEST_METHOD']) === 'POST' && !empty($_SERVER['HTTP_X_PHERY'])); case false: return (bool)(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strcasecmp($_SERVER['HTTP_X_REQUESTED_WITH'], 'XMLHttpRequest') === 0); } return false; } /** * Strip slashes recursive * * @param array|string $variable * @return array|string */ private function stripslashes_recursive($variable) { if (!empty($variable) && is_string($variable)) { return stripslashes($variable); } if (!empty($variable) && is_array($variable)) { foreach ($variable as $i => $value) { $variable[$i] = $this->stripslashes_recursive($value); } } return $variable; } /** * Flush loop * * @param bool $clean Discard buffers */ private static function flush($clean = false) { while (ob_get_level() > 0) { $clean ? ob_end_clean() : ob_end_flush(); } } /** * Default error handler * * @param int $errno * @param string $errstr * @param string $errfile * @param int $errline */ public static function error_handler($errno, $errstr, $errfile, $errline) { self::flush(true); $response = PheryResponse::factory()->exception($errstr, array( 'code' => $errno, 'file' => self::$expose_paths ? $errfile : pathinfo($errfile, PATHINFO_BASENAME), 'line' => $errline )); self::respond($response); self::shutdown_handler(false, true); } /** * Default shutdown handler * * @param bool $errors * @param bool $handled */ public static function shutdown_handler($errors = false, $handled = false) { if ($handled) { self::flush(); } if ($errors === true && ($error = error_get_last()) && !$handled) { self::error_handler($error["type"], $error["message"], $error["file"], $error["line"]); } if (!$handled) { self::flush(); } if (session_id() != '') { session_write_close(); } exit; } /** * Helper function to properly output the headers for a PheryResponse in case you need * to manually return it (like when following a redirect) * * @param string|PheryResponse $response The response or a string * @param bool $echo Echo the response * * @return string */ public static function respond($response, $echo = true) { if ($response instanceof PheryResponse) { if (!headers_sent()) { if (session_id() != '') { session_write_close(); } header('Cache-Control: no-cache, must-revalidate', true); header('Expires: Sat, 26 Jul 1997 05:00:00 GMT', true); header('Content-Type: application/json; charset=' . (strtolower(self::$encoding)), true); header('Connection: close', true); } } if ($response) { $response = "{$response}"; } if ($echo === true) { echo $response; } return $response; } /** * Set the callback for view portions, as defined in Phery.view() * * @param array $views Array consisting of array('#id_of_view' => callback) * The callback is like a normal phery callback, but the second parameter * receives different data. But it MUST always return a PheryResponse with * render_view(). You can do any manipulation like you would in regular * callbacks. If you want to manipulate the DOM AFTER it was rendered, do it * javascript side, using the afterHtml callback when setting up the views. * * <pre> * Phery::instance()->views(array( * 'section#container' => function($data, $params){ * return * PheryResponse::factory() * ->render_view('html', array('extra data like titles, menus, etc')); * } * )); * </pre> * * @return Phery */ public function views(array $views) { foreach ($views as $container => $callback) { if (is_callable($callback)) { $this->views[$container] = $callback; } } return $this; } /** * Initialize stuff before calling the AJAX function * * @return void */ protected function before_user_func() { if ($this->config['error_reporting'] !== false) { set_error_handler(sprintf('%s::error_handler', __CLASS__), $this->config['error_reporting']); } if (empty($_POST['phery']['csrf'])) { $_POST['phery']['csrf'] = ''; } if ($this->csrf($_POST['phery']['csrf']) === false) { self::exception($this, 'Invalid CSRF token', self::ERROR_CSRF); } } /** * Process the requests if any * * @param boolean $last_call * * @return boolean */ private function process_data($last_call) { $response = null; $error = null; $view = false; if (empty($_POST['phery'])) { return self::exception($this, 'Non-Phery AJAX request', self::ERROR_PROCESS); } if (!empty($_GET['_'])) { $this->data['requested'] = (int)$_GET['_']; unset($_GET['_']); } if (isset($_GET['_try_count'])) { $this->data['retries'] = (int)$_GET['_try_count']; unset($_GET['_try_count']); } $args = array(); $remote = false; if (!empty($_POST['phery']['remote'])) { $remote = $_POST['phery']['remote']; } if (!empty($_POST['phery']['submit_id'])) { $this->data['submit_id'] = "#{$_POST['phery']['submit_id']}"; } if ($remote !== false) { $this->data['remote'] = $remote; } if (!empty($_POST['args'])) { $args = get_magic_quotes_gpc() ? $this->stripslashes_recursive($_POST['args']) : $_POST['args']; if ($last_call === true) { unset($_POST['args']); } } foreach ($_POST['phery'] as $name => $post) { if (!isset($this->data[$name])) { $this->data[$name] = $post; } } if (count($this->callbacks['before'])) { foreach ($this->callbacks['before'] as $func) { if (($args = call_user_func($func, $args, $this->data, $this)) === false) { return false; } } } if (!empty($_POST['phery']['view'])) { $this->data['view'] = $_POST['phery']['view']; } if ($remote !== false) { if (isset($this->functions[$remote])) { if (isset($_POST['phery']['remote'])) { unset($_POST['phery']['remote']); } $this->before_user_func(); $response = call_user_func($this->functions[$remote], $args, $this->data, $this); foreach ($this->callbacks['after'] as $func) { if (call_user_func($func, $args, $this->data, $response, $this) === false) { return false; } } if (($response = self::respond($response, false)) === null) { $error = 'Response was void for function "' . htmlentities($remote, ENT_COMPAT, null, false) . '"'; } $_POST['phery']['remote'] = $remote; } else { if ($last_call) { self::exception($this, 'The function provided "' . htmlentities($remote, ENT_COMPAT, null, false) . '" isn\'t set', self::ERROR_PROCESS); } } } else { if (!empty($this->data['view']) && isset($this->views[$this->data['view']])) { $view = $this->data['view']; $this->before_user_func(); $response = call_user_func($this->views[$this->data['view']], $args, $this->data, $this); foreach ($this->callbacks['after'] as $func) { if (call_user_func($func, $args, $this->data, $response, $this) === false) { return false; } } if (($response = self::respond($response, false)) === null) { $error = 'Response was void for view "' . htmlentities($this->data['view'], ENT_COMPAT, null, false) . '"'; } } else { if ($last_call) { if (!empty($this->data['view'])) { self::exception($this, 'The provided view "' . htmlentities($this->data['view'], ENT_COMPAT, null, false) . '" isn\'t set', self::ERROR_PROCESS); } else { self::exception($this, 'Empty request', self::ERROR_PROCESS); } } } } if ($error !== null) { self::error_handler(E_NOTICE, $error, '', 0); } elseif ($response === null && $last_call & !$view) { $response = PheryResponse::factory(); } elseif ($response !== null) { ob_start(); if (!$this->config['return']) { echo $response; } } if (!$this->config['return'] && $this->config['exit_allowed'] === true) { if ($last_call || $response !== null) { exit; } } elseif ($this->config['return']) { self::flush(true); } if ($this->config['error_reporting'] !== false) { restore_error_handler(); } return $response; } /** * Process the AJAX requests if any. * * @param bool $last_call Set this to false if any other further calls * to process() will happen, otherwise it will exit * * @throws PheryException * @return boolean Return false if any error happened */ public function process($last_call = true) { if (self::is_ajax(true)) { // AJAX call return $this->process_data($last_call); } return true; } /** * Config the current instance of Phery * * <code> * array( * // Defaults to true, stop further script execution * 'exit_allowed' => true|false, * * // Throw exceptions on errors * 'exceptions' => true|false, * * // Return the responses in the process() call instead of echo'ing * 'return' => true|false, * * // Error reporting temporarily using error_reporting(). 'false' disables * // the error_reporting and wont try to catch any error. * // Anything else than false will throw a PheryResponse->exception() with * // the message * 'error_reporting' => false|E_ALL|E_DEPRECATED|... * * // By default, the function Phery::instance()->set() will only * // register functions when the current request is an AJAX call, * // to save resources. In order to use Phery::instance()->get_function() * // anytime, you need to set this config value to true * 'set_always_available' => false|true * ); * </code> * * If you pass a string, it will return the current config for the key specified * Anything else, will output the current config as associative array * * @param string|array $config Associative array containing the following options * * @return Phery|string|array */ public function config($config = null) { $register_function = false; if (!empty($config)) { if (is_array($config)) { if (isset($config['exit_allowed'])) { $this->config['exit_allowed'] = (bool)$config['exit_allowed']; } if (isset($config['auto_session'])) { $this->config['auto_session'] = (bool)$config['auto_session']; } if (isset($config['return'])) { $this->config['return'] = (bool)$config['return']; } if (isset($config['set_always_available'])) { $this->config['set_always_available'] = (bool)$config['set_always_available']; } if (isset($config['exceptions'])) { $this->config['exceptions'] = (bool)$config['exceptions']; } if (isset($config['csrf'])) { $this->config['csrf'] = (bool)$config['csrf']; } if (isset($config['error_reporting'])) { if ($config['error_reporting'] !== false) { $this->config['error_reporting'] = (int)$config['error_reporting']; } else { $this->config['error_reporting'] = false; } $register_function = true; } if ($register_function || $this->init) { register_shutdown_function(sprintf('%s::shutdown_handler', __CLASS__), $this->config['error_reporting'] !== false); $this->init = false; } return $this; } elseif (!empty($config) && is_string($config) && isset($this->config[$config])) { return $this->config[$config]; } } return $this->config; } /** * Generates just one instance. Useful to use in many included files. Chainable * * @param array $config Associative config array * * @see __construct() * @see config() * @static * @return Phery */ public static function instance(array $config = array()) { if (!(self::$instance instanceof Phery)) { self::$instance = new Phery($config); } else if ($config) { self::$instance->config($config); } return self::$instance; } /** * Sets the functions to respond to the ajax call. * For security reasons, these functions should not be reacheable through POST/GET requests. * These will be set only for AJAX requests as it will only be set in case of an ajax request, * to save resources. * * You may set the config option "set_always_available" to true to always register the functions * regardless of if it's an AJAX function or not going on. * * The answer/process function, should have the following structure: * * <code> * function func($ajax_data, $callback_data, $phery){ * $r = new PheryResponse; // or PheryResponse::factory(); * * // Sometimes the $callback_data will have an item called 'submit_id', * // is the ID of the calling DOM element. * // if (isset($callback_data['submit_id'])) { } * // $phery will be the current phery instance that called this callback * * $r->jquery('#id')->animate(...); * return $r; //Should always return the PheryResponse unless you are dealing with plain text * } * </code> * * @param array $functions An array of functions to register to the instance. * <pre> * array( * 'function1' => 'function', * 'function2' => array($this, 'method'), * 'function3' => 'StaticClass::name', * 'function4' => array(new ClassName, 'method'), * 'function5' => function($data){} * ); * </pre> * @return Phery */ public function set(array $functions) { if ($this->config['set_always_available'] === false && !self::is_ajax(true)) { return $this; } if (isset($functions) && is_array($functions)) { foreach ($functions as $name => $func) { if (is_callable($func)) { $this->functions[$name] = $func; } else { self::exception($this, 'Provided function "' . $name . '" isnt a valid function or method', self::ERROR_SET); } } } else { self::exception($this, 'Call to "set" must be provided an array', self::ERROR_SET); } return $this; } /** * Unset a function previously set with set() * * @param string $name Name of the function * @see set() * @return Phery */ public function unset_function($name) { if (isset($this->functions[$name])) { unset($this->functions[$name]); } return $this; } /** * Get previously function set with set() method * If you pass aditional arguments, the function will be executed * and this function will return the PheryResponse associated with * that function * * <pre> * Phery::get_function('render', ['<html></html>'])->appendTo('body'); * </pre> * * @param string $function_name The name of the function registed with set * @param array $args Any arguments to pass to the function * @see Phery::set() * @return callable|array|string|PheryResponse|null */ public function get_function($function_name, array $args = array()) { if (isset($this->functions[$function_name])) { if (count($args)) { return call_user_func_array($this->functions[$function_name], $args); } return $this->functions[$function_name]; } return null; } /** * Create a new instance of Phery that can be chained, without the need of assigning it to a variable * * @param array $config Associative config array * * @see config() * @static * @return Phery */ public static function factory(array $config = array()) { return new Phery($config); } /** * Common check for all static factories * * @param array $attributes * @param bool $include_method * * @return string */ protected static function common_check(&$attributes, $include_method = true) { if (!empty($attributes['args'])) { $attributes['data-phery-args'] = json_encode($attributes['args']); unset($attributes['args']); } if (!empty($attributes['confirm'])) { $attributes['data-phery-confirm'] = $attributes['confirm']; unset($attributes['confirm']); } if (!empty($attributes['cache'])) { $attributes['data-phery-cache'] = "1"; unset($attributes['cache']); } if (!empty($attributes['target'])) { $attributes['data-phery-target'] = $attributes['target']; unset($attributes['target']); } if (!empty($attributes['related'])) { $attributes['data-phery-related'] = $attributes['related']; unset($attributes['related']); } if (!empty($attributes['phery-type'])) { $attributes['data-phery-type'] = $attributes['phery-type']; unset($attributes['phery-type']); } if (!empty($attributes['only'])) { $attributes['data-phery-only'] = $attributes['only']; unset($attributes['only']); } if (isset($attributes['clickable'])) { $attributes['data-phery-clickable'] = "1"; unset($attributes['clickable']); } if ($include_method) { if (isset($attributes['method'])) { $attributes['data-phery-method'] = $attributes['method']; unset($attributes['method']); } } $encoding = 'UTF-8'; if (isset($attributes['encoding'])) { $encoding = $attributes['encoding']; unset($attributes['encoding']); } return $encoding; } /** * Helper function that generates an ajax link, defaults to "A" tag * * @param string $content The content of the link. This is ignored for self closing tags, img, input, iframe * @param string $function The PHP function assigned name on Phery::set() * @param array $attributes Extra attributes that can be passed to the link, like class, style, etc * <pre> * array( * // Display confirmation on click * 'confirm' => 'Are you sure?', * * // The tag for the item, defaults to a. If the tag is set to img, the * // 'src' must be set in attributes parameter * 'tag' => 'a', * * // Define another URI for the AJAX call, this defines the HREF of A * 'href' => '/path/to/url', * * // Extra arguments to pass to the AJAX function, will be stored
php
MIT
f22d04625d84d4631c6b2ea0435fe6623c9b1c8e
2026-01-05T05:11:11.357343Z
true
dflydev/dflydev-dot-access-configuration
https://github.com/dflydev/dflydev-dot-access-configuration/blob/cfa0382461ef3ab411354323fbe92b078f6cf66e/src/Dflydev/DotAccessConfiguration/ConfigurationBuilderInterface.php
src/Dflydev/DotAccessConfiguration/ConfigurationBuilderInterface.php
<?php /* * This file is a part of dflydev/dot-access-configuration. * * (c) Dragonfly Development Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Dflydev\DotAccessConfiguration; interface ConfigurationBuilderInterface { /** * Build a Configuration * * @return ConfigurationInterface */ public function build(); }
php
MIT
cfa0382461ef3ab411354323fbe92b078f6cf66e
2026-01-05T05:11:16.185437Z
false
dflydev/dflydev-dot-access-configuration
https://github.com/dflydev/dflydev-dot-access-configuration/blob/cfa0382461ef3ab411354323fbe92b078f6cf66e/src/Dflydev/DotAccessConfiguration/ConfigurationFactory.php
src/Dflydev/DotAccessConfiguration/ConfigurationFactory.php
<?php /* * This file is a part of dflydev/dot-access-configuration. * * (c) Dragonfly Development Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Dflydev\DotAccessConfiguration; class ConfigurationFactory implements ConfigurationFactoryInterface { /** * {@inheritdocs} */ public function create() { return new Configuration(); } }
php
MIT
cfa0382461ef3ab411354323fbe92b078f6cf66e
2026-01-05T05:11:16.185437Z
false
dflydev/dflydev-dot-access-configuration
https://github.com/dflydev/dflydev-dot-access-configuration/blob/cfa0382461ef3ab411354323fbe92b078f6cf66e/src/Dflydev/DotAccessConfiguration/YamlFileConfigurationBuilder.php
src/Dflydev/DotAccessConfiguration/YamlFileConfigurationBuilder.php
<?php /* * This file is a part of dflydev/dot-access-configuration. * * (c) Dragonfly Development Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Dflydev\DotAccessConfiguration; use Dflydev\DotAccessData\Util as DotAccessDataUtil; use Symfony\Component\Yaml\Yaml; class YamlFileConfigurationBuilder extends AbstractConfigurationBuilder { /** * YAML Configuration Filenames * * @var array */ private $yamlConfigurationFilenames; /** * Constructor * * @param array $yamlConfigurationFilenames */ public function __construct(array $yamlConfigurationFilenames) { $this->yamlConfigurationFilenames = $yamlConfigurationFilenames; } /** * {@inheritdocs} */ public function internalBuild(ConfigurationInterface $configuration) { $config = array(); $imports = array(); foreach ($this->yamlConfigurationFilenames as $yamlConfigurationFilename) { if (file_exists($yamlConfigurationFilename)) { $config = DotAccessDataUtil::mergeAssocArray($config, Yaml::parse(file_get_contents($yamlConfigurationFilename))); if (isset($config['imports'])) { foreach ((array) $config['imports'] as $file) { if (0 === strpos($file, '/')) { // Absolute path $imports[] = $file; } else { if ($realpath = realpath(dirname($yamlConfigurationFilename) . '/' . $file)) { $imports[] = $realpath; } } } } } } if ($imports) { $importsBuilder = new static($imports); // We want to reconfigure the imports builder to have the // same basic configuration as this instance. $this->reconfigure($importsBuilder); $configuration->import($importsBuilder->build()); $internalImports = $configuration->get('imports'); } else { $internalImports = null; } $configuration->importRaw($config); if ($internalImports) { foreach ((array) $internalImports as $import) { $configuration->append('imports', $import); } } return $configuration; } }
php
MIT
cfa0382461ef3ab411354323fbe92b078f6cf66e
2026-01-05T05:11:16.185437Z
false
dflydev/dflydev-dot-access-configuration
https://github.com/dflydev/dflydev-dot-access-configuration/blob/cfa0382461ef3ab411354323fbe92b078f6cf66e/src/Dflydev/DotAccessConfiguration/AbstractPlaceholderResolverFactory.php
src/Dflydev/DotAccessConfiguration/AbstractPlaceholderResolverFactory.php
<?php /* * This file is a part of dflydev/dot-access-configuration. * * (c) Dragonfly Development Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Dflydev\DotAccessConfiguration; use Dflydev\PlaceholderResolver\DataSource\DataSourceInterface; abstract class AbstractPlaceholderResolverFactory implements PlaceholderResolverFactoryInterface { /** * {@inheritdocs} */ public function create(ConfigurationInterface $configuration) { return $this->createInternal($configuration, new ConfigurationDataSource($configuration)); } /** * Internal create * * @param ConfigurationInterface $configuration * @param DataSourceInterface $dataSource * * @return PlaceholderResolverInterface */ abstract protected function createInternal(ConfigurationInterface $configuration, DataSourceInterface $dataSource); }
php
MIT
cfa0382461ef3ab411354323fbe92b078f6cf66e
2026-01-05T05:11:16.185437Z
false
dflydev/dflydev-dot-access-configuration
https://github.com/dflydev/dflydev-dot-access-configuration/blob/cfa0382461ef3ab411354323fbe92b078f6cf66e/src/Dflydev/DotAccessConfiguration/ConfigurationDataSource.php
src/Dflydev/DotAccessConfiguration/ConfigurationDataSource.php
<?php /* * This file is a part of dflydev/dot-access-configuration. * * (c) Dragonfly Development Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Dflydev\DotAccessConfiguration; use Dflydev\PlaceholderResolver\DataSource\DataSourceInterface; class ConfigurationDataSource implements DataSourceInterface { private $configuration; /** * Constructor * * @param ConfigurationInterface $configuration */ public function __construct(ConfigurationInterface $configuration) { $this->setConfiguration($configuration); } /** * {@inheritdoc} */ public function exists($key, $system = false) { if ($system) { return false; } return null !== $this->configuration->getRaw($key); } /** * {@inheritdoc} */ public function get($key, $system = false) { if ($system) { return null; } return $this->configuration->getRaw($key); } /** * Set Configuration * * @param ConfigurationInterface $configuration * * @return ConfigurationDataSource */ public function setConfiguration(ConfigurationInterface $configuration) { $this->configuration = $configuration; return $this; } }
php
MIT
cfa0382461ef3ab411354323fbe92b078f6cf66e
2026-01-05T05:11:16.185437Z
false
dflydev/dflydev-dot-access-configuration
https://github.com/dflydev/dflydev-dot-access-configuration/blob/cfa0382461ef3ab411354323fbe92b078f6cf66e/src/Dflydev/DotAccessConfiguration/PlaceholderResolverFactoryInterface.php
src/Dflydev/DotAccessConfiguration/PlaceholderResolverFactoryInterface.php
<?php /* * This file is a part of dflydev/dot-access-configuration. * * (c) Dragonfly Development Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Dflydev\DotAccessConfiguration; use Dflydev\PlaceholderResolver\PlaceholderResolverInterface; interface PlaceholderResolverFactoryInterface { /** * Configuration * * @param ConfigurationInterface $configuration * * @return PlaceholderResolverInterface */ public function create(ConfigurationInterface $configuration); }
php
MIT
cfa0382461ef3ab411354323fbe92b078f6cf66e
2026-01-05T05:11:16.185437Z
false
dflydev/dflydev-dot-access-configuration
https://github.com/dflydev/dflydev-dot-access-configuration/blob/cfa0382461ef3ab411354323fbe92b078f6cf66e/src/Dflydev/DotAccessConfiguration/PlaceholderResolverFactory.php
src/Dflydev/DotAccessConfiguration/PlaceholderResolverFactory.php
<?php /* * This file is a part of dflydev/dot-access-configuration. * * (c) Dragonfly Development Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Dflydev\DotAccessConfiguration; use Dflydev\PlaceholderResolver\DataSource\DataSourceInterface; use Dflydev\PlaceholderResolver\RegexPlaceholderResolver; class PlaceholderResolverFactory extends AbstractPlaceholderResolverFactory { /** * {@inheritdocs} */ protected function createInternal(ConfigurationInterface $configuration, DataSourceInterface $dataSource) { return new RegexPlaceholderResolver($dataSource, '%', '%'); } }
php
MIT
cfa0382461ef3ab411354323fbe92b078f6cf66e
2026-01-05T05:11:16.185437Z
false
dflydev/dflydev-dot-access-configuration
https://github.com/dflydev/dflydev-dot-access-configuration/blob/cfa0382461ef3ab411354323fbe92b078f6cf66e/src/Dflydev/DotAccessConfiguration/Configuration.php
src/Dflydev/DotAccessConfiguration/Configuration.php
<?php /* * This file is a part of dflydev/dot-access-configuration. * * (c) Dragonfly Development Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Dflydev\DotAccessConfiguration; class Configuration extends AbstractConfiguration { /** * Constructor * * @param array|null $config */ public function __construct(?array $config = null) { $this->importRaw($config); } }
php
MIT
cfa0382461ef3ab411354323fbe92b078f6cf66e
2026-01-05T05:11:16.185437Z
false
dflydev/dflydev-dot-access-configuration
https://github.com/dflydev/dflydev-dot-access-configuration/blob/cfa0382461ef3ab411354323fbe92b078f6cf66e/src/Dflydev/DotAccessConfiguration/ConfigurationInterface.php
src/Dflydev/DotAccessConfiguration/ConfigurationInterface.php
<?php /* * This file is a part of dflydev/dot-access-configuration. * * (c) Dragonfly Development Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Dflydev\DotAccessConfiguration; use Dflydev\DotAccessData\Data; use Dflydev\PlaceholderResolver\PlaceholderResolverInterface; interface ConfigurationInterface { /** * Get a value (with placeholders unresolved) * * @param string $key * * @return mixed */ public function getRaw($key); /** * Get a value (with placeholders resolved) * * @param string $key * * @return mixed */ public function get($key); /** * Set a value * * @param string $key * @param mixed $value */ public function set($key, $value = null); /** * Append a value * * Will force key to be an array if it is only a string * * @param string $key * @param mixed $value */ public function append($key, $value = null); /** * Export configuration data as an associtaive array (with placeholders unresolved) * * @return array */ public function exportRaw(); /** * Export configuration data as an associtaive array (with placeholders resolved) * * @return array */ public function export(); /** * Underlying Data representation * * Will have all placeholders resolved. * * @return Data */ public function exportData(); /** * Import another Configuration * * @param array $imported * @param bool $clobber */ public function importRaw($imported, $clobber = true); /** * Import another Configuration * * @param ConfigurationInterface $imported * @param bool $clobber */ public function import(ConfigurationInterface $imported, $clobber = true); /** * Resolve placeholders in value from configuration * * @param string|null $value * * @return string */ public function resolve($value = null); /** * Set Placeholder Resolver * * @param PlaceholderResolver $placeholderResolver * * @return ConfigurationInterface */ public function setPlaceholderResolver(PlaceholderResolverInterface $placeholderResolver); }
php
MIT
cfa0382461ef3ab411354323fbe92b078f6cf66e
2026-01-05T05:11:16.185437Z
false
dflydev/dflydev-dot-access-configuration
https://github.com/dflydev/dflydev-dot-access-configuration/blob/cfa0382461ef3ab411354323fbe92b078f6cf66e/src/Dflydev/DotAccessConfiguration/AbstractConfigurationBuilder.php
src/Dflydev/DotAccessConfiguration/AbstractConfigurationBuilder.php
<?php /* * This file is a part of dflydev/dot-access-configuration. * * (c) Dragonfly Development Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Dflydev\DotAccessConfiguration; abstract class AbstractConfigurationBuilder implements ConfigurationBuilderInterface { private $configurationFactory; private $placeholderResolverFactory; /** * Set Configuration Factory * * @param ConfigurationFactoryInterface $configurationFactory * * @return AbstractConfigurationBuilder */ public function setConfigurationFactory(ConfigurationFactoryInterface $configurationFactory) { $this->configurationFactory = $configurationFactory; return $this; } /** * Configuration Factory * * @return ConfigurationFactoryInterface */ protected function configurationFactory() { if (null === $this->configurationFactory) { $this->configurationFactory = new ConfigurationFactory(); } return $this->configurationFactory; } /** * {@inheritdocs} */ public function build() { $configuration = $this->configurationFactory()->create(); if (null !== $this->placeholderResolverFactory) { $placeholderResolver = $this->placeholderResolverFactory->create($configuration); $configuration->setPlaceholderResolver($placeholderResolver); } $this->internalBuild($configuration); return $configuration; } /** * Set Placeholder Resolver Factory * * @param PlaceholderResolverFactoryInterface $placeholderResolverFactory */ public function setPlaceholderResolverFactory(PlaceholderResolverFactoryInterface $placeholderResolverFactory) { $this->placeholderResolverFactory = $placeholderResolverFactory; } /** * Called to reconfigure the specified Configuration Builder to be similar to this instance * * @param AbstractConfigurationBuilder $configurationBuilder */ public function reconfigure(AbstractConfigurationBuilder $configurationBuilder) { if (null !== $this->placeholderResolverFactory) { $configurationBuilder->setPlaceholderResolverFactory($this->placeholderResolverFactory); } $configurationBuilder->setConfigurationFactory($this->configurationFactory()); } /** * Internal build * * @param ConfigurationInterface $configuration */ abstract protected function internalBuild(ConfigurationInterface $configuration); }
php
MIT
cfa0382461ef3ab411354323fbe92b078f6cf66e
2026-01-05T05:11:16.185437Z
false
dflydev/dflydev-dot-access-configuration
https://github.com/dflydev/dflydev-dot-access-configuration/blob/cfa0382461ef3ab411354323fbe92b078f6cf66e/src/Dflydev/DotAccessConfiguration/AbstractConfiguration.php
src/Dflydev/DotAccessConfiguration/AbstractConfiguration.php
<?php /* * This file is a part of dflydev/dot-access-configuration. * * (c) Dragonfly Development Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Dflydev\DotAccessConfiguration; use Dflydev\DotAccessData\Data; use Dflydev\DotAccessData\Exception\MissingPathException; use Dflydev\PlaceholderResolver\PlaceholderResolverInterface; use Dflydev\PlaceholderResolver\RegexPlaceholderResolver; abstract class AbstractConfiguration implements ConfigurationInterface { private $placeholderResolver; private $data; private $exportIsDirty = true; private $resolvedExport; /** * {@inheritdocs} */ public function getRaw($key) { try { return $this->data()->get($key); } catch (MissingPathException $e) { return null; } } /** * {@inheritdocs} */ public function get($key) { $value = $this->getRaw($key); if (is_object($value)) { return $value; } $this->resolveValues($value); return $value; } /** * {@inheritdocs} */ public function set($key, $value = null) { $this->exportIsDirty = true; return $this->data()->set($key, $value); } /** * {@inheritdocs} */ public function append($key, $value = null) { $this->exportIsDirty = true; return $this->data()->append($key, $value); } /** * {@inheritdocs} */ public function exportRaw() { return $this->data()->export(); } /** * {@inheritdocs} */ public function export() { if ($this->exportIsDirty) { $this->resolvedExport = $this->data()->export(); $this->resolveValues($this->resolvedExport); $this->exportIsDirty = false; } return $this->resolvedExport; } /** * {@inheritdocs} */ public function exportData() { return new Data($this->export()); } /** * {@inheritdocs} */ public function importRaw($imported = null, $clobber = true) { $this->exportIsDirty = true; if (null !== $imported) { $this->data()->import($imported, $clobber); } } /** * {@inheritdocs} */ public function import(ConfigurationInterface $imported, $clobber = true) { return $this->importRaw($imported->exportRaw(), $clobber); } /** * {@inheritdocs} */ public function resolve($value = null) { if (null === $value) { return null; } return $this->placeholderResolver()->resolvePlaceholder($value); } /** * {@inheritdocs} */ public function setPlaceholderResolver(PlaceholderResolverInterface $placeholderResolver) { $this->placeholderResolver = $placeholderResolver; return $this; } /** * Resolve values * * For objects, do nothing. For strings, resolve placeholder. * For arrays, call resolveValues() on each item. * * @param mixed $input */ protected function resolveValues(&$input = null) { if (is_array($input)) { foreach ($input as $idx => $value) { $this->resolveValues($value); $input[$idx] = $value; } } else { if (!is_object($input)) { $input = $this->placeholderResolver()->resolvePlaceholder($input); } } } /** * Data * * @return Data */ protected function data() { if (null === $this->data) { $this->data = new Data(); } return $this->data; } /** * Placeholder Resolver * * @return PlaceholderResolverInterface */ protected function placeholderResolver() { if (null === $this->placeholderResolver) { $this->placeholderResolver = new RegexPlaceholderResolver(new ConfigurationDataSource($this), '%', '%'); } return $this->placeholderResolver; } }
php
MIT
cfa0382461ef3ab411354323fbe92b078f6cf66e
2026-01-05T05:11:16.185437Z
false
dflydev/dflydev-dot-access-configuration
https://github.com/dflydev/dflydev-dot-access-configuration/blob/cfa0382461ef3ab411354323fbe92b078f6cf66e/src/Dflydev/DotAccessConfiguration/ConfigurationFactoryInterface.php
src/Dflydev/DotAccessConfiguration/ConfigurationFactoryInterface.php
<?php /* * This file is a part of dflydev/dot-access-configuration. * * (c) Dragonfly Development Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Dflydev\DotAccessConfiguration; interface ConfigurationFactoryInterface { /** * Create a Configuration * * @return ConfigurationInterface */ public function create(); }
php
MIT
cfa0382461ef3ab411354323fbe92b078f6cf66e
2026-01-05T05:11:16.185437Z
false
dflydev/dflydev-dot-access-configuration
https://github.com/dflydev/dflydev-dot-access-configuration/blob/cfa0382461ef3ab411354323fbe92b078f6cf66e/src/Dflydev/DotAccessConfiguration/YamlConfigurationBuilder.php
src/Dflydev/DotAccessConfiguration/YamlConfigurationBuilder.php
<?php /* * This file is a part of dflydev/dot-access-configuration. * * (c) Dragonfly Development Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Dflydev\DotAccessConfiguration; use Psr\Log\InvalidArgumentException; use Symfony\Component\Yaml\Yaml; class YamlConfigurationBuilder extends AbstractConfigurationBuilder { /** * YAML input string * * @var string */ protected $input; /** * Constructor * * @param string|null $input */ public function __construct($input = null) { $this->input = $input; } /** * {@inheritdocs} */ public function internalBuild(ConfigurationInterface $configuration) { if (null !== $this->input) { try { $yml = Yaml::parse($this->input, Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE); } catch (\Exception $e) { throw new InvalidArgumentException($e->getMessage(), 0, $e); } if (is_string($yml)) { throw(new \InvalidArgumentException('Yaml could not be parsed, parser detected a string.')); } $configuration->importRaw($yml); } } }
php
MIT
cfa0382461ef3ab411354323fbe92b078f6cf66e
2026-01-05T05:11:16.185437Z
false
dflydev/dflydev-dot-access-configuration
https://github.com/dflydev/dflydev-dot-access-configuration/blob/cfa0382461ef3ab411354323fbe92b078f6cf66e/tests/bootstrap.php
tests/bootstrap.php
<?php /* * This file is a part of dflydev/dot-access-configuration. * * (c) Dragonfly Development Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ $loader = require dirname(__DIR__) . '/vendor/autoload.php';
php
MIT
cfa0382461ef3ab411354323fbe92b078f6cf66e
2026-01-05T05:11:16.185437Z
false
dflydev/dflydev-dot-access-configuration
https://github.com/dflydev/dflydev-dot-access-configuration/blob/cfa0382461ef3ab411354323fbe92b078f6cf66e/tests/Dflydev/DotAccessConfiguration/PlaceholderResolverFactoryTest.php
tests/Dflydev/DotAccessConfiguration/PlaceholderResolverFactoryTest.php
<?php /* * This file is a part of dflydev/dot-access-configuration. * * (c) Dragonfly Development Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Dflydev\DotAccessConfiguration; use PHPUnit\Framework\TestCase; class PlaceholderResolverFactoryTest extends TestCase { public function testCreate() { $configuration = $this->getMockBuilder(\Dflydev\DotAccessConfiguration\Configuration::class)->getMock(); $placeholderResolverFactory = new PlaceholderResolverFactory(); $placeholderResolver = $placeholderResolverFactory->create($configuration); $this->assertNotNull($placeholderResolver); } }
php
MIT
cfa0382461ef3ab411354323fbe92b078f6cf66e
2026-01-05T05:11:16.185437Z
false
dflydev/dflydev-dot-access-configuration
https://github.com/dflydev/dflydev-dot-access-configuration/blob/cfa0382461ef3ab411354323fbe92b078f6cf66e/tests/Dflydev/DotAccessConfiguration/ConfigurationDataSourceTest.php
tests/Dflydev/DotAccessConfiguration/ConfigurationDataSourceTest.php
<?php /* * This file is a part of dflydev/dot-access-configuration. * * (c) Dragonfly Development Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Dflydev\DotAccessConfiguration; use PHPUnit\Framework\TestCase; class ConfigurationDataSourceTest extends TestCase { public function test() { $configuration = $this->getMockBuilder(\Dflydev\DotAccessConfiguration\Configuration::class)->getMock(); $configuration ->expects($this->any()) ->method('getRaw') ->will($this->returnValueMap(array( array('foo', 'bar'), array('foo', null, true), array('foo', 'bar', false), ))) ; $dataSource = new ConfigurationDataSource($configuration); $this->assertEquals('bar', $dataSource->get('foo')); $this->assertTrue($dataSource->exists('foo')); $this->assertEquals('bar', $dataSource->get('foo', false)); $this->assertTrue($dataSource->exists('foo', false)); $this->assertNull($dataSource->get('foo', true)); $this->assertFalse($dataSource->exists('foo', true)); } }
php
MIT
cfa0382461ef3ab411354323fbe92b078f6cf66e
2026-01-05T05:11:16.185437Z
false
dflydev/dflydev-dot-access-configuration
https://github.com/dflydev/dflydev-dot-access-configuration/blob/cfa0382461ef3ab411354323fbe92b078f6cf66e/tests/Dflydev/DotAccessConfiguration/ConfigurationTest.php
tests/Dflydev/DotAccessConfiguration/ConfigurationTest.php
<?php /* * This file is a part of dflydev/dot-access-configuration. * * (c) Dragonfly Development Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Dflydev\DotAccessConfiguration; use PHPUnit\Framework\TestCase; class ConfigurationTest extends TestCase { protected function getTestData() { $configurationTestObjectClass = new class (null){ public $key; public function __construct($key) { $this->key = $key; } }; return array( 'a' => array( 'b' => array( 'c' => 'ABC', ), ), 'abc' => '%a.b.c%', 'abcd' => '%a.b.c.d%', 'some' => array( 'object' => new $configurationTestObjectClass('some.object'), 'other' => array( 'object' => new $configurationTestObjectClass('some.other.object'), ), ), 'object' => new $configurationTestObjectClass('object'), 'an_array' => array('hello'), ); } protected function runBasicTests($configuration) { $this->assertEquals('ABC', $configuration->get('a.b.c'), 'Direct access by dot notation'); $this->assertEquals('ABC', $configuration->get('abc'), 'Resolved access'); $this->assertEquals('%a.b.c.d%', $configuration->get('abcd'), 'Unresolved access'); $this->assertEquals('object', $configuration->get('object')->key); $this->assertEquals('some.object', $configuration->get('some.object')->key); $this->assertEquals('some.other.object', $configuration->get('some.other.object')->key); $this->assertEquals(array('hello'), $configuration->get('an_array')); $this->assertEquals('This is ABC', $configuration->resolve('This is %a.b.c%')); $this->assertNull($configuration->resolve()); } public function testGet() { $configuration = new Configuration($this->getTestData()); $this->runBasicTests($configuration); } public function testAppend() { $configuration = new Configuration($this->getTestData()); $configuration->append('a.b.c', 'abc'); $configuration->append('an_array', 'world'); $this->assertEquals(array('ABC', 'abc'), $configuration->get('a.b.c')); $this->assertEquals(array('hello', 'world'), $configuration->get('an_array')); } public function testExportRaw() { $configuration = new Configuration($this->getTestData()); // Start with "known" expected value. $expected = $this->getTestData(); $this->assertEquals($expected, $configuration->exportRaw()); // Simulate change on an object to ensure that objects // are being handled correctly. $expected['object']->key = 'object (modified)'; // Make the same change in the object that the // configuration is managing. $configuration->get('object')->key = 'object (modified)'; $this->assertEquals($expected, $configuration->exportRaw()); } public function testExport() { $configuration = new Configuration($this->getTestData()); // Start with "known" expected value. $expected = $this->getTestData(); // We have one replacement that is expected to happen. // It should be represented in the export as the // resolved value! $expected['abc'] = 'ABC'; $this->assertEquals($expected, $configuration->export()); // Simulate change on an object to ensure that objects // are being handled correctly. $expected['object']->key = 'object (modified)'; // Make the same change in the object that the // configuration is managing. $configuration->get('object')->key = 'object (modified)'; $this->assertEquals($expected, $configuration->export()); // Test to make sure that set will result in setting // a new value and also that export will show this new // value. (tests "export is dirty" functionality) $configuration->set('abc', 'ABCD'); $expected['abc'] = 'ABCD'; $this->assertEquals($expected, $configuration->export()); } public function testExportData() { $configuration = new Configuration($this->getTestData()); $data = $configuration->exportData(); // The exportData call should return data filled with // resolved data. $this->assertEquals('ABC', $data->get('abc')); } public function testImportRaw() { $configuration = new Configuration(); $configuration->importRaw($this->getTestData()); $this->runBasicTests($configuration); } public function testImport() { $configuration = new Configuration(); $configuration->import(new Configuration($this->getTestData())); $this->runBasicTests($configuration); } public function testSetPlaceholderResolver() { $placeholderResolver = $this->getMockBuilder(\Dflydev\PlaceholderResolver\PlaceholderResolverInterface::class)->getMock(); $placeholderResolver ->expects($this->once()) ->method('resolvePlaceholder') ->with($this->equalTo('foo')) ->will($this->returnValue('bar')) ; $configuration = new Configuration(); $configuration->setPlaceholderResolver($placeholderResolver); $this->assertEquals('bar', $configuration->resolve('foo')); } }
php
MIT
cfa0382461ef3ab411354323fbe92b078f6cf66e
2026-01-05T05:11:16.185437Z
false
dflydev/dflydev-dot-access-configuration
https://github.com/dflydev/dflydev-dot-access-configuration/blob/cfa0382461ef3ab411354323fbe92b078f6cf66e/tests/Dflydev/DotAccessConfiguration/AbstractConfigurationBuilderTest.php
tests/Dflydev/DotAccessConfiguration/AbstractConfigurationBuilderTest.php
<?php /* * This file is a part of dflydev/dot-access-configuration. * * (c) Dragonfly Development Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Dflydev\DotAccessConfiguration; use PHPUnit\Framework\TestCase; class AbstractConfigurationBuilderTest extends TestCase { public function testPlaceholderResolver() { $placeholderResolver = $this->getMockBuilder(\Dflydev\PlaceholderResolver\PlaceholderResolverInterface::class)->getMock(); $placeholderResolverFactory = $this->getMockBuilder(\Dflydev\DotAccessConfiguration\PlaceholderResolverFactoryInterface::class)->getMock(); $placeholderResolverFactory ->expects($this->once()) ->method('create') ->will($this->returnValue($placeholderResolver)) ; $configurationBuilder = $this->getMockForAbstractClass(\Dflydev\DotAccessConfiguration\AbstractConfigurationBuilder::class); $configurationBuilder ->expects($this->once()) ->method('internalBuild'); $configurationBuilder->setPlaceholderResolverFactory($placeholderResolverFactory); $configurationBuilder->build(); } public function testReconfigure() { $configuration000 = $this->getMockBuilder(\Dflydev\DotAccessConfiguration\ConfigurationInterface::class)->getMock(); $configuration000 ->expects($this->exactly(2)) ->method('get') ->with($this->equalTo('foo')) ->will($this->returnValue('FOO')) ; $configuration001 = $this->getMockBuilder(\Dflydev\DotAccessConfiguration\ConfigurationInterface::class)->getMock(); $configuration001 ->expects($this->exactly(2)) ->method('get') ->with($this->equalTo('bar')) ->will($this->returnValue('BAR')) ; $placeholderResolver = $this->getMockBuilder(\Dflydev\PlaceholderResolver\PlaceholderResolverInterface::class)->getMock(); $placeholderResolverFactory = $this->getMockBuilder(\Dflydev\DotAccessConfiguration\PlaceholderResolverFactoryInterface::class)->getMock(); $placeholderResolverFactory ->expects($this->exactly(2)) ->method('create') ->will($this->returnValue($placeholderResolver)) ; $configurationFactory = $this->getMockBuilder(\Dflydev\DotAccessConfiguration\ConfigurationFactoryInterface::class)->getMock(); $configurationFactory ->expects($this->exactly(2)) ->method('create') ->will($this->onConsecutiveCalls($configuration000, $configuration001)); ; $configurationBuilder = $this->getMockForAbstractClass('Dflydev\DotAccessConfiguration\AbstractConfigurationBuilder'); $configurationBuilder->setPlaceholderResolverFactory($placeholderResolverFactory); $configurationBuilder->setConfigurationFactory($configurationFactory); $reconfiguredConfigurationBuilder = $this->getMockForAbstractClass('Dflydev\DotAccessConfiguration\AbstractConfigurationBuilder'); $configurationBuilder->reconfigure($reconfiguredConfigurationBuilder); $configurationTest000 = $configurationBuilder->build(); $configurationTest001 = $reconfiguredConfigurationBuilder->build(); $this->assertEquals('FOO', $configuration000->get('foo')); $this->assertEquals('FOO', $configurationTest000->get('foo')); $this->assertEquals('BAR', $configuration001->get('bar')); $this->assertEquals('BAR', $configurationTest001->get('bar')); } }
php
MIT
cfa0382461ef3ab411354323fbe92b078f6cf66e
2026-01-05T05:11:16.185437Z
false
dflydev/dflydev-dot-access-configuration
https://github.com/dflydev/dflydev-dot-access-configuration/blob/cfa0382461ef3ab411354323fbe92b078f6cf66e/tests/Dflydev/DotAccessConfiguration/ConfigurationFactoryTest.php
tests/Dflydev/DotAccessConfiguration/ConfigurationFactoryTest.php
<?php /* * This file is a part of dflydev/dot-access-configuration. * * (c) Dragonfly Development Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Dflydev\DotAccessConfiguration; use PHPUnit\Framework\TestCase; class ConfigurationFactoryTest extends TestCase { public function testCreate() { $configurationFactory = new ConfigurationFactory(); $configuration = $configurationFactory->create(); $this->assertNotNull($configuration); } }
php
MIT
cfa0382461ef3ab411354323fbe92b078f6cf66e
2026-01-05T05:11:16.185437Z
false
dflydev/dflydev-dot-access-configuration
https://github.com/dflydev/dflydev-dot-access-configuration/blob/cfa0382461ef3ab411354323fbe92b078f6cf66e/tests/Dflydev/DotAccessConfiguration/YamlConfigurationBuilderTest.php
tests/Dflydev/DotAccessConfiguration/YamlConfigurationBuilderTest.php
<?php /* * This file is a part of dflydev/dot-access-configuration. * * (c) Dragonfly Development Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Dflydev\DotAccessConfiguration; use PHPUnit\Framework\TestCase; class YamlConfigurationBuilderTest extends TestCase { public function testBuild() { if (!class_exists('Symfony\Component\Yaml\Yaml')) { $this->markTestSkipped('The Symfony2 YAML library is not available'); } $configurationBuilder = new YamlConfigurationBuilder(); $configuration = $configurationBuilder->build(); $this->assertNotNull($configuration); } public function testBuildWithData() { if (!class_exists('Symfony\Component\Yaml\Yaml')) { $this->markTestSkipped('The Symfony2 YAML library is not available'); } $configurationBuilder = new YamlConfigurationBuilder('foo: bar'); $configuration = $configurationBuilder->build(); $this->assertNotNull($configuration); } }
php
MIT
cfa0382461ef3ab411354323fbe92b078f6cf66e
2026-01-05T05:11:16.185437Z
false
dflydev/dflydev-dot-access-configuration
https://github.com/dflydev/dflydev-dot-access-configuration/blob/cfa0382461ef3ab411354323fbe92b078f6cf66e/tests/Dflydev/DotAccessConfiguration/YamlFileConfigurationBuilderTest.php
tests/Dflydev/DotAccessConfiguration/YamlFileConfigurationBuilderTest.php
<?php /* * This file is a part of dflydev/dot-access-configuration. * * (c) Dragonfly Development Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Dflydev\DotAccessConfiguration; use PHPUnit\Framework\TestCase; class YamlFileConfigurationBuilderTest extends TestCase { public function testBuilder() { if (!class_exists('Symfony\Component\Yaml\Yaml')) { $this->markTestSkipped('The Symfony2 YAML library is not available'); } $configurationBuilder = new YamlFileConfigurationBuilder(array(__DIR__ . '/fixtures/yamlFileConfigurationBuilderTest-testBuilder.yml')); $configuration = $configurationBuilder->build(); $this->assertEquals('C', $configuration->get('a.b.c')); $this->assertEquals('C0', $configuration->get('a0.b0.c0')); $this->assertEquals('C1', $configuration->get('a1.b1.c1')); $this->assertEquals(array( 'yamlFileConfigurationBuilderTest-testBuilder-import-level0.yml', '/tmp/testing-this-file-should-not-exist.yml', 'yamlFileConfigurationBuilderTest-testBuilder-import-level1.yml', ), $configuration->get('imports')); } }
php
MIT
cfa0382461ef3ab411354323fbe92b078f6cf66e
2026-01-05T05:11:16.185437Z
false
giekaton/php-metamask-user-login
https://github.com/giekaton/php-metamask-user-login/blob/97685bc041bc0df2bea5226e92a7bf07a7cf14db/backend/server.php
backend/server.php
<?php require_once "lib/Keccak/Keccak.php"; require_once "lib/Elliptic/EC.php"; require_once "lib/Elliptic/Curves.php"; require_once "lib/JWT/jwt_helper.php"; $GLOBALS['JWT_secret'] = '4Eac8AS2cw84easd65araADX'; use Elliptic\EC; use kornrunner\Keccak; require_once('config.php'); $data = json_decode(file_get_contents("php://input")); $request = $data->request; // Create a standard of eth address by lowercasing them // Some wallets send address with upper and lower case characters if (!empty($data->address)) { $data->address = strtolower($data->address); } if ($request == "login") { $address = $data->address; // Prepared statement to protect against SQL injections $stmt = $conn->prepare("SELECT nonce FROM $tablename WHERE address = ?"); $stmt->bindParam(1, $address); $stmt->execute(); $nonce = $stmt->fetchColumn(); if ($nonce) { // If user exists, return message to sign echo("Sign this message to validate that you are the owner of the account. Random string: " . $nonce); } else { // If user doesn't exist, register new user with generated nonce, then return message to sign $nonce = uniqid(); // Prepared statement to protect against SQL injections $stmt = $conn->prepare("INSERT INTO $tablename (address, nonce) VALUES (?, ?)"); $stmt->bindParam(1, $address); $stmt->bindParam(2, $nonce); if ($stmt->execute() === TRUE) { echo ("Sign this message to validate that you are the owner of the account. Random string: " . $nonce); } else { echo "Error" . $stmt->error; } $conn = null; } exit; } if ($request == "auth") { $address = $data->address; $signature = $data->signature; // Prepared statement to protect against SQL injections if($stmt = $conn->prepare("SELECT nonce FROM $tablename WHERE address = ?")) { $stmt->bindParam(1, $address); $stmt->execute(); $nonce = $stmt->fetchColumn(); $message = "Sign this message to validate that you are the owner of the account. Random string: " . $nonce; } // Check if the message was signed with the same private key to which the public address belongs function pubKeyToAddress($pubkey) { return "0x" . substr(Keccak::hash(substr(hex2bin($pubkey->encode("hex")), 1), 256), 24); } function verifySignature($message, $signature, $address) { $msglen = strlen($message); $hash = Keccak::hash("\x19Ethereum Signed Message:\n{$msglen}{$message}", 256); $sign = ["r" => substr($signature, 2, 64), "s" => substr($signature, 66, 64)]; $recid = ord(hex2bin(substr($signature, 130, 2))) - 27; if ($recid != ($recid & 1)) return false; $ec = new EC('secp256k1'); $pubkey = $ec->recoverPubKey($hash, $sign, $recid); return $address == pubKeyToAddress($pubkey); } // If verification passed, authenticate user if (verifySignature($message, $signature, $address)) { $stmt = $conn->prepare("SELECT publicName FROM $tablename WHERE address = ?"); $stmt->bindParam(1, $address); $stmt->execute(); $publicName = $stmt->fetchColumn(); $publicName = htmlspecialchars($publicName, ENT_QUOTES, 'UTF-8'); // Create a new random nonce for the next login $nonce = uniqid(); $sql = "UPDATE $tablename SET nonce = '".$nonce."' WHERE address = '".$address."'"; $conn->query($sql); // Create JWT Token $token = array(); $token['address'] = $address; $JWT = JWT::encode($token, $GLOBALS['JWT_secret']); echo(json_encode(["Success", $publicName, $JWT])); } else { echo "Fail"; } $conn = null; exit; } if ($request == "updatePublicName") { $publicName = $data->publicName; $address = $data->address; // Check if the user is logged in try { $JWT = JWT::decode($data->JWT, $GLOBALS['JWT_secret']); } catch (\Exception $e) { echo 'Authentication error'; exit; } // Prepared statement to protect against SQL injections $stmt = $conn->prepare("UPDATE $tablename SET publicName = ? WHERE address = '".$address."'"); $stmt->bindParam(1, $publicName); if ($stmt->execute() === TRUE) { echo "Public name for $address updated to $publicName"; } $conn = null; exit; } ?>
php
MIT
97685bc041bc0df2bea5226e92a7bf07a7cf14db
2026-01-05T05:11:27.721791Z
false
giekaton/php-metamask-user-login
https://github.com/giekaton/php-metamask-user-login/blob/97685bc041bc0df2bea5226e92a7bf07a7cf14db/backend/create_db_table.php
backend/create_db_table.php
<?php include_once "config.php"; try { if ($servertype == "pgsql") { $sql = "CREATE TABLE IF NOT EXISTS $tablename( ID SERIAL PRIMARY KEY, address VARCHAR(42) NOT NULL, publicName VARCHAR(250) DEFAULT NULL, nonce VARCHAR(250) DEFAULT NULL, created TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP);"; } elseif ($servertype == "mysql") { $sql = "CREATE TABLE IF NOT EXISTS $tablename ( ID INT(11) NOT NULL AUTO_INCREMENT, address VARCHAR(42) NOT NULL UNIQUE, publicName TINYTEXT DEFAULT NULL, nonce TINYTEXT DEFAULT NULL, created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (ID)) ENGINE=MyISAM DEFAULT CHARSET=latin1"; }else{ die('DB Config Error'); } $conn->exec($sql); print("Created $tablename Table.\n"); $conn = null; } catch(PDOException $e) { echo $e->getMessage(); } ?>
php
MIT
97685bc041bc0df2bea5226e92a7bf07a7cf14db
2026-01-05T05:11:27.721791Z
false
giekaton/php-metamask-user-login
https://github.com/giekaton/php-metamask-user-login/blob/97685bc041bc0df2bea5226e92a7bf07a7cf14db/backend/lib/JWT/jwt_helper.php
backend/lib/JWT/jwt_helper.php
<?php /** * JSON Web Token implementation, based on this spec: * http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-06 * * PHP version 5 * * @category Authentication * @package Authentication_JWT * @author Neuman Vong <neuman@twilio.com> * @author Anant Narayanan <anant@php.net> * @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD * @link https://github.com/firebase/php-jwt */ class JWT { /** * Decodes a JWT string into a PHP object. * * @param string $jwt The JWT * @param string|null $key The secret key * @param bool $verify Don't skip verification process * * @return object The JWT's payload as a PHP object * @throws UnexpectedValueException Provided JWT was invalid * @throws DomainException Algorithm was not provided * * @uses jsonDecode * @uses urlsafeB64Decode */ public static function decode($jwt, $key = null, $verify = true) { $tks = explode('.', $jwt); if (count($tks) != 3) { throw new UnexpectedValueException('Wrong number of segments'); } list($headb64, $bodyb64, $cryptob64) = $tks; if (null === ($header = JWT::jsonDecode(JWT::urlsafeB64Decode($headb64)))) { throw new UnexpectedValueException('Invalid segment encoding'); } if (null === $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64))) { throw new UnexpectedValueException('Invalid segment encoding'); } $sig = JWT::urlsafeB64Decode($cryptob64); if ($verify) { if (empty($header->alg)) { throw new DomainException('Empty algorithm'); } if ($sig != JWT::sign("$headb64.$bodyb64", $key, $header->alg)) { throw new UnexpectedValueException('Signature verification failed'); } } return $payload; } /** * Converts and signs a PHP object or array into a JWT string. * * @param object|array $payload PHP object or array * @param string $key The secret key * @param string $algo The signing algorithm. Supported * algorithms are 'HS256', 'HS384' and 'HS512' * * @return string A signed JWT * @uses jsonEncode * @uses urlsafeB64Encode */ public static function encode($payload, $key, $algo = 'HS256') { $header = array('typ' => 'JWT', 'alg' => $algo); $segments = array(); $segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($header)); $segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($payload)); $signing_input = implode('.', $segments); $signature = JWT::sign($signing_input, $key, $algo); $segments[] = JWT::urlsafeB64Encode($signature); return implode('.', $segments); } /** * Sign a string with a given key and algorithm. * * @param string $msg The message to sign * @param string $key The secret key * @param string $method The signing algorithm. Supported * algorithms are 'HS256', 'HS384' and 'HS512' * * @return string An encrypted message * @throws DomainException Unsupported algorithm was specified */ public static function sign($msg, $key, $method = 'HS256') { $methods = array( 'HS256' => 'sha256', 'HS384' => 'sha384', 'HS512' => 'sha512', ); if (empty($methods[$method])) { throw new DomainException('Algorithm not supported'); } return hash_hmac($methods[$method], $msg, $key, true); } /** * Decode a JSON string into a PHP object. * * @param string $input JSON string * * @return object Object representation of JSON string * @throws DomainException Provided string was invalid JSON */ public static function jsonDecode($input) { $obj = json_decode($input); if (function_exists('json_last_error') && $errno = json_last_error()) { JWT::_handleJsonError($errno); } else if ($obj === null && $input !== 'null') { throw new DomainException('Null result with non-null input'); } return $obj; } /** * Encode a PHP object into a JSON string. * * @param object|array $input A PHP object or array * * @return string JSON representation of the PHP object or array * @throws DomainException Provided object could not be encoded to valid JSON */ public static function jsonEncode($input) { $json = json_encode($input); if (function_exists('json_last_error') && $errno = json_last_error()) { JWT::_handleJsonError($errno); } else if ($json === 'null' && $input !== null) { throw new DomainException('Null result with non-null input'); } return $json; } /** * Decode a string with URL-safe Base64. * * @param string $input A Base64 encoded string * * @return string A decoded string */ public static function urlsafeB64Decode($input) { $remainder = strlen($input) % 4; if ($remainder) { $padlen = 4 - $remainder; $input .= str_repeat('=', $padlen); } return base64_decode(strtr($input, '-_', '+/')); } /** * Encode a string with URL-safe Base64. * * @param string $input The string you want encoded * * @return string The base64 encode of what you passed in */ public static function urlsafeB64Encode($input) { return str_replace('=', '', strtr(base64_encode($input), '+/', '-_')); } /** * Helper method to create a JSON error. * * @param int $errno An error number from json_last_error() * * @return void */ private static function _handleJsonError($errno) { $messages = array( JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON' ); throw new DomainException( isset($messages[$errno]) ? $messages[$errno] : 'Unknown JSON error: ' . $errno ); } }
php
MIT
97685bc041bc0df2bea5226e92a7bf07a7cf14db
2026-01-05T05:11:27.721791Z
false
giekaton/php-metamask-user-login
https://github.com/giekaton/php-metamask-user-login/blob/97685bc041bc0df2bea5226e92a7bf07a7cf14db/backend/lib/Keccak/Keccak.php
backend/lib/Keccak/Keccak.php
<?php namespace kornrunner; use Exception; use function mb_strlen; use function mb_substr; final class Keccak { private const KECCAK_ROUNDS = 24; private const LFSR = 0x01; private const ENCODING = '8bit'; private static $keccakf_rotc = [1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 2, 14, 27, 41, 56, 8, 25, 43, 62, 18, 39, 61, 20, 44]; private static $keccakf_piln = [10, 7, 11, 17, 18, 3, 5, 16, 8, 21, 24, 4, 15, 23, 19, 13, 12,2, 20, 14, 22, 9, 6, 1]; private static $x64 = (PHP_INT_SIZE === 8); private static function keccakf64(&$st, $rounds): void { $keccakf_rndc = [ [0x00000000, 0x00000001], [0x00000000, 0x00008082], [0x80000000, 0x0000808a], [0x80000000, 0x80008000], [0x00000000, 0x0000808b], [0x00000000, 0x80000001], [0x80000000, 0x80008081], [0x80000000, 0x00008009], [0x00000000, 0x0000008a], [0x00000000, 0x00000088], [0x00000000, 0x80008009], [0x00000000, 0x8000000a], [0x00000000, 0x8000808b], [0x80000000, 0x0000008b], [0x80000000, 0x00008089], [0x80000000, 0x00008003], [0x80000000, 0x00008002], [0x80000000, 0x00000080], [0x00000000, 0x0000800a], [0x80000000, 0x8000000a], [0x80000000, 0x80008081], [0x80000000, 0x00008080], [0x00000000, 0x80000001], [0x80000000, 0x80008008] ]; $bc = []; for ($round = 0; $round < $rounds; $round++) { // Theta for ($i = 0; $i < 5; $i++) { $bc[$i] = [ $st[$i][0] ^ $st[$i + 5][0] ^ $st[$i + 10][0] ^ $st[$i + 15][0] ^ $st[$i + 20][0], $st[$i][1] ^ $st[$i + 5][1] ^ $st[$i + 10][1] ^ $st[$i + 15][1] ^ $st[$i + 20][1] ]; } for ($i = 0; $i < 5; $i++) { $t = [ $bc[($i + 4) % 5][0] ^ (($bc[($i + 1) % 5][0] << 1) | ($bc[($i + 1) % 5][1] >> 31)) & (0xFFFFFFFF), $bc[($i + 4) % 5][1] ^ (($bc[($i + 1) % 5][1] << 1) | ($bc[($i + 1) % 5][0] >> 31)) & (0xFFFFFFFF) ]; for ($j = 0; $j < 25; $j += 5) { $st[$j + $i] = [ $st[$j + $i][0] ^ $t[0], $st[$j + $i][1] ^ $t[1] ]; } } // Rho Pi $t = $st[1]; for ($i = 0; $i < 24; $i++) { $j = self::$keccakf_piln[$i]; $bc[0] = $st[$j]; $n = self::$keccakf_rotc[$i]; $hi = $t[0]; $lo = $t[1]; if ($n >= 32) { $n -= 32; $hi = $t[1]; $lo = $t[0]; } $st[$j] =[ (($hi << $n) | ($lo >> (32 - $n))) & (0xFFFFFFFF), (($lo << $n) | ($hi >> (32 - $n))) & (0xFFFFFFFF) ]; $t = $bc[0]; } // Chi for ($j = 0; $j < 25; $j += 5) { for ($i = 0; $i < 5; $i++) { $bc[$i] = $st[$j + $i]; } for ($i = 0; $i < 5; $i++) { $st[$j + $i] = [ $st[$j + $i][0] ^ ~$bc[($i + 1) % 5][0] & $bc[($i + 2) % 5][0], $st[$j + $i][1] ^ ~$bc[($i + 1) % 5][1] & $bc[($i + 2) % 5][1] ]; } } // Iota $st[0] = [ $st[0][0] ^ $keccakf_rndc[$round][0], $st[0][1] ^ $keccakf_rndc[$round][1] ]; } } private static function keccak64($in_raw, int $capacity, int $outputlength, $suffix, bool $raw_output): string { $capacity /= 8; $inlen = mb_strlen($in_raw, self::ENCODING); $rsiz = 200 - 2 * $capacity; $rsizw = $rsiz / 8; $st = []; for ($i = 0; $i < 25; $i++) { $st[] = [0, 0]; } for ($in_t = 0; $inlen >= $rsiz; $inlen -= $rsiz, $in_t += $rsiz) { for ($i = 0; $i < $rsizw; $i++) { $t = unpack('V*', mb_substr($in_raw, $i * 8 + $in_t, 8, self::ENCODING)); $st[$i] = [ $st[$i][0] ^ $t[2], $st[$i][1] ^ $t[1] ]; } self::keccakf64($st, self::KECCAK_ROUNDS); } $temp = mb_substr($in_raw, $in_t, $inlen, self::ENCODING); $temp = str_pad($temp, $rsiz, "\x0", STR_PAD_RIGHT); $temp[$inlen] = chr($suffix); $temp[$rsiz - 1] = chr(ord($temp[$rsiz - 1]) | 0x80); for ($i = 0; $i < $rsizw; $i++) { $t = unpack('V*', mb_substr($temp, $i * 8, 8, self::ENCODING)); $st[$i] = [ $st[$i][0] ^ $t[2], $st[$i][1] ^ $t[1] ]; } self::keccakf64($st, self::KECCAK_ROUNDS); $out = ''; for ($i = 0; $i < 25; $i++) { $out .= $t = pack('V*', $st[$i][1], $st[$i][0]); } $r = mb_substr($out, 0, $outputlength / 8, self::ENCODING); return $raw_output ? $r : bin2hex($r); } private static function keccakf32(&$st, $rounds): void { $keccakf_rndc = [ [0x0000, 0x0000, 0x0000, 0x0001], [0x0000, 0x0000, 0x0000, 0x8082], [0x8000, 0x0000, 0x0000, 0x0808a], [0x8000, 0x0000, 0x8000, 0x8000], [0x0000, 0x0000, 0x0000, 0x808b], [0x0000, 0x0000, 0x8000, 0x0001], [0x8000, 0x0000, 0x8000, 0x08081], [0x8000, 0x0000, 0x0000, 0x8009], [0x0000, 0x0000, 0x0000, 0x008a], [0x0000, 0x0000, 0x0000, 0x0088], [0x0000, 0x0000, 0x8000, 0x08009], [0x0000, 0x0000, 0x8000, 0x000a], [0x0000, 0x0000, 0x8000, 0x808b], [0x8000, 0x0000, 0x0000, 0x008b], [0x8000, 0x0000, 0x0000, 0x08089], [0x8000, 0x0000, 0x0000, 0x8003], [0x8000, 0x0000, 0x0000, 0x8002], [0x8000, 0x0000, 0x0000, 0x0080], [0x0000, 0x0000, 0x0000, 0x0800a], [0x8000, 0x0000, 0x8000, 0x000a], [0x8000, 0x0000, 0x8000, 0x8081], [0x8000, 0x0000, 0x0000, 0x8080], [0x0000, 0x0000, 0x8000, 0x00001], [0x8000, 0x0000, 0x8000, 0x8008] ]; $bc = []; for ($round = 0; $round < $rounds; $round++) { // Theta for ($i = 0; $i < 5; $i++) { $bc[$i] = [ $st[$i][0] ^ $st[$i + 5][0] ^ $st[$i + 10][0] ^ $st[$i + 15][0] ^ $st[$i + 20][0], $st[$i][1] ^ $st[$i + 5][1] ^ $st[$i + 10][1] ^ $st[$i + 15][1] ^ $st[$i + 20][1], $st[$i][2] ^ $st[$i + 5][2] ^ $st[$i + 10][2] ^ $st[$i + 15][2] ^ $st[$i + 20][2], $st[$i][3] ^ $st[$i + 5][3] ^ $st[$i + 10][3] ^ $st[$i + 15][3] ^ $st[$i + 20][3] ]; } for ($i = 0; $i < 5; $i++) { $t = [ $bc[($i + 4) % 5][0] ^ ((($bc[($i + 1) % 5][0] << 1) | ($bc[($i + 1) % 5][1] >> 15)) & (0xFFFF)), $bc[($i + 4) % 5][1] ^ ((($bc[($i + 1) % 5][1] << 1) | ($bc[($i + 1) % 5][2] >> 15)) & (0xFFFF)), $bc[($i + 4) % 5][2] ^ ((($bc[($i + 1) % 5][2] << 1) | ($bc[($i + 1) % 5][3] >> 15)) & (0xFFFF)), $bc[($i + 4) % 5][3] ^ ((($bc[($i + 1) % 5][3] << 1) | ($bc[($i + 1) % 5][0] >> 15)) & (0xFFFF)) ]; for ($j = 0; $j < 25; $j += 5) { $st[$j + $i] = [ $st[$j + $i][0] ^ $t[0], $st[$j + $i][1] ^ $t[1], $st[$j + $i][2] ^ $t[2], $st[$j + $i][3] ^ $t[3] ]; } } // Rho Pi $t = $st[1]; for ($i = 0; $i < 24; $i++) { $j = self::$keccakf_piln[$i]; $bc[0] = $st[$j]; $n = self::$keccakf_rotc[$i] >> 4; $m = self::$keccakf_rotc[$i] % 16; $st[$j] = [ ((($t[(0+$n) %4] << $m) | ($t[(1+$n) %4] >> (16-$m))) & (0xFFFF)), ((($t[(1+$n) %4] << $m) | ($t[(2+$n) %4] >> (16-$m))) & (0xFFFF)), ((($t[(2+$n) %4] << $m) | ($t[(3+$n) %4] >> (16-$m))) & (0xFFFF)), ((($t[(3+$n) %4] << $m) | ($t[(0+$n) %4] >> (16-$m))) & (0xFFFF)) ]; $t = $bc[0]; } // Chi for ($j = 0; $j < 25; $j += 5) { for ($i = 0; $i < 5; $i++) { $bc[$i] = $st[$j + $i]; } for ($i = 0; $i < 5; $i++) { $st[$j + $i] = [ $st[$j + $i][0] ^ ~$bc[($i + 1) % 5][0] & $bc[($i + 2) % 5][0], $st[$j + $i][1] ^ ~$bc[($i + 1) % 5][1] & $bc[($i + 2) % 5][1], $st[$j + $i][2] ^ ~$bc[($i + 1) % 5][2] & $bc[($i + 2) % 5][2], $st[$j + $i][3] ^ ~$bc[($i + 1) % 5][3] & $bc[($i + 2) % 5][3] ]; } } // Iota $st[0] = [ $st[0][0] ^ $keccakf_rndc[$round][0], $st[0][1] ^ $keccakf_rndc[$round][1], $st[0][2] ^ $keccakf_rndc[$round][2], $st[0][3] ^ $keccakf_rndc[$round][3] ]; } } private static function keccak32($in_raw, int $capacity, int $outputlength, $suffix, bool $raw_output): string { $capacity /= 8; $inlen = mb_strlen($in_raw, self::ENCODING); $rsiz = 200 - 2 * $capacity; $rsizw = $rsiz / 8; $st = []; for ($i = 0; $i < 25; $i++) { $st[] = [0, 0, 0, 0]; } for ($in_t = 0; $inlen >= $rsiz; $inlen -= $rsiz, $in_t += $rsiz) { for ($i = 0; $i < $rsizw; $i++) { $t = unpack('v*', mb_substr($in_raw, $i * 8 + $in_t, 8, self::ENCODING)); $st[$i] = [ $st[$i][0] ^ $t[4], $st[$i][1] ^ $t[3], $st[$i][2] ^ $t[2], $st[$i][3] ^ $t[1] ]; } self::keccakf32($st, self::KECCAK_ROUNDS); } $temp = mb_substr($in_raw, $in_t, $inlen, self::ENCODING); $temp = str_pad($temp, $rsiz, "\x0", STR_PAD_RIGHT); $temp[$inlen] = chr($suffix); $temp[$rsiz - 1] = chr((int) $temp[$rsiz - 1] | 0x80); for ($i = 0; $i < $rsizw; $i++) { $t = unpack('v*', mb_substr($temp, $i * 8, 8, self::ENCODING)); $st[$i] = [ $st[$i][0] ^ $t[4], $st[$i][1] ^ $t[3], $st[$i][2] ^ $t[2], $st[$i][3] ^ $t[1] ]; } self::keccakf32($st, self::KECCAK_ROUNDS); $out = ''; for ($i = 0; $i < 25; $i++) { $out .= $t = pack('v*', $st[$i][3],$st[$i][2], $st[$i][1], $st[$i][0]); } $r = mb_substr($out, 0, $outputlength / 8, self::ENCODING); return $raw_output ? $r: bin2hex($r); } private static function keccak($in_raw, int $capacity, int $outputlength, $suffix, bool $raw_output): string { return self::$x64 ? self::keccak64($in_raw, $capacity, $outputlength, $suffix, $raw_output) : self::keccak32($in_raw, $capacity, $outputlength, $suffix, $raw_output); } public static function hash($in, int $mdlen, bool $raw_output = false): string { if (!in_array($mdlen, [224, 256, 384, 512], true)) { throw new Exception('Unsupported Keccak Hash output size.'); } return self::keccak($in, $mdlen, $mdlen, self::LFSR, $raw_output); } public static function shake($in, int $security_level, int $outlen, bool $raw_output = false): string { if (!in_array($security_level, [128, 256], true)) { throw new Exception('Unsupported Keccak Shake security level.'); } return self::keccak($in, $security_level, $outlen, 0x1f, $raw_output); } }
php
MIT
97685bc041bc0df2bea5226e92a7bf07a7cf14db
2026-01-05T05:11:27.721791Z
false
giekaton/php-metamask-user-login
https://github.com/giekaton/php-metamask-user-login/blob/97685bc041bc0df2bea5226e92a7bf07a7cf14db/backend/lib/Elliptic/Curves.php
backend/lib/Elliptic/Curves.php
<?php namespace Elliptic; require_once "Curve/PresetCurve.php"; use Elliptic\Curve\PresetCurve; class Curves { private static $curves; public static function hasCurve($name) { return isset(self::$curves[$name]); } public static function getCurve($name) { if (!isset(self::$curves[$name])) { throw new \Exception('Unknown curve ' . $name); } return self::$curves[$name]; } public static function defineCurve($name, $options) { self::$curves[$name] = new PresetCurve($options); } } $sha256 = [ "blockSize" => 512, "outSize" => 256, "hmacStrength" => 192, "padLength" => 64, "algo" => 'sha256' ]; $sha224 = [ "blockSize" => 512, "outSize" => 224, "hmacStrength" => 192, "padLength" => 64, "algo" => 'sha224' ]; $sha512 = [ "blockSize" => 1024, "outSize" => 512, "hmacStrength" => 192, "padLength" => 128, "algo" => 'sha512' ]; $sha384 = [ "blockSize" => 1024, "outSize" => 384, "hmacStrength" => 192, "padLength" => 128, "algo" => 'sha384' ]; $sha1 = [ "blockSize" => 512, "outSize" => 160, "hmacStrength" => 80, "padLength" => 64, "algo" => 'sha1' ]; Curves::defineCurve("p192", array( "type" => "short", "prime" => "p192", "p" => "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff", "a" => "ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc", "b" => "64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1", "n" => "ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831", "hash" => $sha256, "gRed" => false, "g" => array( "188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012", "07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811" ) )); Curves::defineCurve("p224", array( "type" => "short", "prime" => "p224", "p" => "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001", "a" => "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe", "b" => "b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4", "n" => "ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d", "hash" => $sha256, "gRed" => false, "g" => array( "b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21", "bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34" ) )); Curves::defineCurve("p256", array( "type" => "short", "prime" => null, "p" => "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff", "a" => "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc", "b" => "5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b", "n" => "ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551", "hash" => $sha256, "gRed" => false, "g" => array( "6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296", "4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5" ) )); Curves::defineCurve("p384", array( "type" => "short", "prime" => null, "p" => "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff " . "fffffffe ffffffff 00000000 00000000 ffffffff", "a" => "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff " . "fffffffe ffffffff 00000000 00000000 fffffffc", "b" => "b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f " . "5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef", "n" => "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 " . "f4372ddf 581a0db2 48b0a77a ecec196a ccc52973", "hash" => $sha384, "gRed" => false, "g" => array( "aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 " . "5502f25d bf55296c 3a545e38 72760ab7", "3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 " . "0a60b1ce 1d7e819d 7a431d7c 90ea0e5f" ) )); Curves::defineCurve("p521", array( "type" => "short", "prime" => null, "p" => "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff " . "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff " . "ffffffff ffffffff ffffffff ffffffff ffffffff", "a" => "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff " . "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff " . "ffffffff ffffffff ffffffff ffffffff fffffffc", "b" => "00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b " . "99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd " . "3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00", "n" => "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff " . "ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 " . "f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409", "hash" => $sha512, "gRed" => false, "g" => array( "000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 " . "053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 " . "a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66", "00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 " . "579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 " . "3fad0761 353c7086 a272c240 88be9476 9fd16650" ) )); Curves::defineCurve("curve25519", array( "type" => "mont", "prime" => "p25519", "p" => "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", "a" => "76d06", "b" => "0", "n" => "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed", "hash" => $sha256, "gRed" => false, "g" => array( "9" ) )); Curves::defineCurve("ed25519", array( "type" => "edwards", "prime" => "p25519", "p" => "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", "a" => "-1", "c" => "1", // -121665 * (121666^(-1)) (mod P) "d" => "52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3", "n" => "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed", "hash" => $sha256, "gRed" => false, "g" => array( "216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a", // 4/5 "6666666666666666666666666666666666666666666666666666666666666658" ) )); $pre = array( "doubles" => array( "step" => 4, "points" => array( array( "e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a", "f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821" ), array( "8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508", "11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf" ), array( "175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739", "d3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695" ), array( "363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640", "4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9" ), array( "8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c", "4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36" ), array( "723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda", "96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f" ), array( "eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa", "5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999" ), array( "100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0", "cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09" ), array( "e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d", "9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d" ), array( "feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d", "e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088" ), array( "da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1", "9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d" ), array( "53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0", "5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8" ), array( "8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047", "10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a" ), array( "385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862", "283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453" ), array( "6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7", "7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160" ), array( "3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd", "56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0" ), array( "85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83", "7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6" ), array( "948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a", "53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589" ), array( "6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8", "bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17" ), array( "e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d", "4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda" ), array( "e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725", "7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd" ), array( "213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754", "4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2" ), array( "4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c", "17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6" ), array( "fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6", "6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f" ), array( "76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39", "c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01" ), array( "c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891", "893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3" ), array( "d895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b", "febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f" ), array( "b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03", "2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7" ), array( "e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d", "eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78" ), array( "a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070", "7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1" ), array( "90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4", "e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150" ), array( "8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da", "662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82" ), array( "e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11", "1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc" ), array( "8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e", "efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b" ), array( "e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41", "2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51" ), array( "b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef", "67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45" ), array( "d68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8", "db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120" ), array( "324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d", "648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84" ), array( "4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96", "35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d" ), array( "9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd", "ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d" ), array( "6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5", "9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8" ), array( "a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266", "40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8" ), array( "7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71", "34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac" ), array( "928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac", "c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f" ), array( "85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751", "1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962" ), array( "ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e", "493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907" ), array( "827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241", "c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec" ), array( "eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3", "be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d" ), array( "e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f", "4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414" ), array( "1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19", "aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd" ), array( "146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be", "b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0" ), array( "fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9", "6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811" ), array( "da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2", "8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1" ), array( "a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13", "7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c" ), array( "174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c", "ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73" ), array( "959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba", "2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd" ), array( "d2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151", "e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405" ), array( "64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073", "d99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589" ), array( "8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458", "38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e" ), array( "13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b", "69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27" ), array( "bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366", "d3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1" ), array( "8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa", "40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482" ), array( "8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0", "620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945" ), array( "dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787", "7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573" ), array( "f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e", "ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82" ) ) ), "naf" => array( "wnd" => 7, "points" => array( array( "f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9", "388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672" ), array( "2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4", "d8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6" ), array( "5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc", "6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da" ), array( "acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe", "cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37" ), array( "774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb", "d984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b" ), array( "f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8", "ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81" ), array( "d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e", "581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58" ), array( "defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34", "4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77" ), array( "2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c", "85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a" ), array( "352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5", "321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c" ), array( "2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f", "2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67" ), array( "9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714", "73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402" ), array( "daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729", "a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55" ), array( "c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db", "2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482" ), array( "6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4", "e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82" ), array( "1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5", "b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396" ), array( "605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479", "2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49" ), array( "62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d", "80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf" ), array( "80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f", "1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a" ), array( "7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb", "d0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7" ), array( "d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9", "eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933" ), array( "49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963", "758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a" ), array( "77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74", "958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6" ), array( "f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530", "e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37" ), array( "463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b", "5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e" ), array( "f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247", "cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6" ), array( "caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1", "cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476" ), array( "2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120", "4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40" ), array( "7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435", "91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61" ), array( "754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18", "673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683" ), array( "e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8", "59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5" ), array( "186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb", "3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b" ), array( "df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f", "55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417" ), array( "5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143", "efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868" ), array( "290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba", "e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a" ), array( "af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45", "f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6" ), array( "766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a", "744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996" ), array( "59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e", "c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e" ), array( "f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8", "e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d" ), array( "7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c", "30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2" ), array( "948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519", "e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e" ), array( "7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab", "100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437" ), array( "3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca", "ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311" ), array( "d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf", "8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4" ), array( "1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610", "68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575" ), array( "733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4", "f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d" ), array( "15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c", "d56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d" ), array( "a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940", "edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629" ), array( "e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980", "a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06" ), array( "311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3", "66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374" ), array( "34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf", "9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee" ), array( "f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63", "4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1" ), array( "d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448", "fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b" ), array( "32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf", "5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661" ), array( "7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5", "8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6" ), array( "ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6", "8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e" ), array( "16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5", "5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d" ), array( "eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99", "f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc" ), array( "78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51", "f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4" ), array( "494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5", "42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c" ), array( "a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5", "204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b" ), array( "c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997", "4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913" ), array( "841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881", "73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154" ), array( "5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5", "39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865" ), array( "36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66", "d2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc" ), array( "336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726", "ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224" ), array( "8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede", "6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e" ), array( "1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94", "60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6" ), array( "85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31", "3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511" ), array( "29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51", "b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b" ), array( "a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252", "ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2" ), array( "4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5",
php
MIT
97685bc041bc0df2bea5226e92a7bf07a7cf14db
2026-01-05T05:11:27.721791Z
true
giekaton/php-metamask-user-login
https://github.com/giekaton/php-metamask-user-login/blob/97685bc041bc0df2bea5226e92a7bf07a7cf14db/backend/lib/Elliptic/Signature.php
backend/lib/Elliptic/Signature.php
<?php namespace Elliptic\EC; require_once "Utils.php"; use Elliptic\Utils; use BN\BN; class Signature { public $r; public $s; public $recoveryParam; function __construct($options, $enc = false) { if ($options instanceof Signature) { $this->r = $options->r; $this->s = $options->s; $this->recoveryParam = $options->recoveryParam; return; } if (isset($options['r'])) { assert(isset($options["r"]) && isset($options["s"])); //, "Signature without r or s"); $this->r = new BN($options["r"], 16); $this->s = new BN($options["s"], 16); if( isset($options["recoveryParam"]) ) $this->recoveryParam = $options["recoveryParam"]; else $this->recoveryParam = null; return; } if (!$this->_importDER($options, $enc)) throw new \Exception('Unknown signature format'); } private static function getLength($buf, &$pos) { $initial = $buf[$pos++]; if( !($initial & 0x80) ) return $initial; $octetLen = $initial & 0xf; $val = 0; for($i = 0; $i < $octetLen; $i++) { $val = $val << 8; $val = $val | $buf[$pos]; $pos++; } return $val; } private static function rmPadding(&$buf) { $i = 0; $len = count($buf) - 1; while($i < $len && !$buf[$i] && !($buf[$i+1] & 0x80) ) $i++; if( $i === 0 ) return $buf; return array_slice($buf, $i); } private function _importDER($data, $enc) { $data = Utils::toArray($data, $enc); $dataLen = count($data); $place = 0; if( $data[$place++] !== 0x30) return false; $len = self::getLength($data, $place); if( ($len + $place) !== $dataLen ) return false; if( $data[$place++] !== 0x02 ) return false; $rlen = self::getLength($data, $place); $r = array_slice($data, $place, $rlen); $place += $rlen; if( $data[$place++] !== 0x02 ) return false; $slen = self::getLength($data, $place); if( $dataLen !== $slen + $place ) return false; $s = array_slice($data, $place, $slen); if( $r[0] === 0 && ($r[1] & 0x80 ) ) $r = array_slice($r, 1); if( $s[0] === 0 && ($s[1] & 0x80 ) ) $s = array_slice($s, 1); $this->r = new BN($r); $this->s = new BN($s); $this->recoveryParam = null; return true; } private static function constructLength(&$arr, $len) { if( $len < 0x80 ) { array_push($arr, $len); return; } $octets = 1 + (log($len) / M_LN2 >> 3); array_push($arr, $octets | 0x80); while(--$octets) array_push($arr, ($len >> ($octets << 3)) & 0xff); array_push($arr, $len); } public function toDER($enc = false) { $r = $this->r->toArray(); $s = $this->s->toArray(); //Pad values if( $r[0] & 0x80 ) array_unshift($r, 0); if( $s[0] & 0x80 ) array_unshift($s, 0); $r = self::rmPadding($r); $s = self::rmPadding($s); while(!$s[0] && !($s[1] & 0x80)) array_slice($s, 1); $arr = array(0x02); self::constructLength($arr, count($r)); $arr = array_merge($arr, $r, array(0x02)); self::constructLength($arr, count($s)); $backHalf = array_merge($arr, $s); $res = array(0x30); self::constructLength($res, count($backHalf)); $res = array_merge($res, $backHalf); return Utils::encode($res, $enc); } } ?>
php
MIT
97685bc041bc0df2bea5226e92a7bf07a7cf14db
2026-01-05T05:11:27.721791Z
false
giekaton/php-metamask-user-login
https://github.com/giekaton/php-metamask-user-login/blob/97685bc041bc0df2bea5226e92a7bf07a7cf14db/backend/lib/Elliptic/EC.php
backend/lib/Elliptic/EC.php
<?php namespace Elliptic; require_once "KeyPair.php"; require_once "Signature.php"; require_once "BN.php"; use Elliptic\Curve\PresetCurve; use Elliptic\EC\KeyPair; use Elliptic\EC\Signature; use BN\BN; class EC { public $curve; public $n; public $nh; public $g; public $hash; function __construct($options) { if( is_string($options) ) { $options = Curves::getCurve($options); } if( $options instanceof PresetCurve ) $options = array("curve" => $options); $this->curve = $options["curve"]->curve; $this->n = $this->curve->n; $this->nh = $this->n->ushrn(1); //Point on curve $this->g = $options["curve"]->g; $this->g->precompute($options["curve"]->n->bitLength() + 1); //Hash for function for DRBG if( isset($options["hash"]) ) $this->hash = $options["hash"]; else $this->hash = $options["curve"]->hash; } public function keyPair($options) { return new KeyPair($this, $options); } public function keyFromPrivate($priv, $enc = false) { return KeyPair::fromPrivate($this, $priv, $enc); } public function keyFromPublic($pub, $enc = false) { return KeyPair::fromPublic($this, $pub, $enc); } public function genKeyPair($options = null) { // Instantiate HmacDRBG $drbg = new HmacDRBG(array( "hash" => $this->hash, "pers" => isset($options["pers"]) ? $options["pers"] : "", "entropy" => isset($options["entropy"]) ? $options["entropy"] : Utils::randBytes($this->hash["hmacStrength"]), "nonce" => $this->n->toArray() )); $bytes = $this->n->byteLength(); $ns2 = $this->n->sub(new BN(2)); while(true) { $priv = new BN($drbg->generate($bytes)); if( $priv->cmp($ns2) > 0 ) continue; $priv->iaddn(1); return $this->keyFromPrivate($priv); } } private function _truncateToN($msg, $truncOnly = false) { $delta = intval(($msg->byteLength() * 8) - $this->n->bitLength()); if( $delta > 0 ) { $msg = $msg->ushrn($delta); } if( $truncOnly || $msg->cmp($this->n) < 0 ) return $msg; return $msg->sub($this->n); } public function sign($msg, $key, $enc = null, $options = null) { if( !is_string($enc) ) { $options = $enc; $enc = null; } $key = $this->keyFromPrivate($key, $enc); $msg = $this->_truncateToN(new BN($msg, 16)); // Zero-extend key to provide enough entropy $bytes = $this->n->byteLength(); $bkey = $key->getPrivate()->toArray("be", $bytes); // Zero-extend nonce to have the same byte size as N $nonce = $msg->toArray("be", $bytes); $kFunc = null; if( isset($options["k"]) ) $kFunc = $options["k"]; else { // Instatiate HmacDRBG $drbg = new HmacDRBG(array( "hash" => $this->hash, "entropy" => $bkey, "nonce" => $nonce, "pers" => isset($options["pers"]) ? $options["pers"] : "", "persEnc" => isset($options["persEnc"]) ? $options["persEnc"] : false )); $kFunc = function($iter) use ($drbg, $bytes) { return new BN($drbg->generate($bytes)); }; } // Number of bytes to generate $ns1 = $this->n->sub(new BN(1)); $canonical = isset($options["canonical"]) ? $options["canonical"] : false; for($iter = 0; true; $iter++) { $k = $kFunc($iter); $k = $this->_truncateToN($k, true); if( $k->cmpn(1) <= 0 || $k->cmp($ns1) >= 0 ) continue; $kp = $this->g->mul($k); if( $kp->isInfinity() ) continue; $kpX = $kp->getX(); $r = $kpX->umod($this->n); if( $r->isZero() ) continue; $s = $k->invm($this->n)->mul($r->mul($key->getPrivate())->iadd($msg)); $s = $s->umod($this->n); if( $s->isZero() ) continue; $recoveryParam = ($kp->getY()->isOdd() ? 1 : 0) | ($kpX->cmp($r) !== 0 ? 2 : 0); // Use complement of `s`, if it is > `n / 2` if( $canonical && $s->cmp($this->nh) > 0 ) { $s = $this->n->sub($s); $recoveryParam ^= 1; } return new Signature(array( "r" => $r, "s" => $s, "recoveryParam" => $recoveryParam )); } } public function verify($msg, $signature, $key, $enc = false) { $msg = $this->_truncateToN(new BN($msg, 16)); $key = $this->keyFromPublic($key, $enc); $signature = new Signature($signature, "hex"); // Perform primitive values validation $r = $signature->r; $s = $signature->s; if( $r->cmpn(1) < 0 || $r->cmp($this->n) >= 0 ) return false; if( $s->cmpn(1) < 0 || $s->cmp($this->n) >= 0 ) return false; // Validate signature $sinv = $s->invm($this->n); $u1 = $sinv->mul($msg)->umod($this->n); $u2 = $sinv->mul($r)->umod($this->n); if( !$this->curve->_maxwellTrick ) { $p = $this->g->mulAdd($u1, $key->getPublic(), $u2); if( $p->isInfinity() ) return false; return $p->getX()->umod($this->n)->cmp($r) === 0; } // NOTE: Greg Maxwell's trick, inspired by: // https://git.io/vad3K $p = $this->g->jmulAdd($u1, $key->getPublic(), $u2); if( $p->isInfinity() ) return false; // Compare `p.x` of Jacobian point with `r`, // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the // inverse of `p.z^2` return $p->eqXToP($r); } public function recoverPubKey($msg, $signature, $j, $enc = false) { assert((3 & $j) === $j); //, "The recovery param is more than two bits"); $signature = new Signature($signature, $enc); $e = new BN($msg, 16); $r = $signature->r; $s = $signature->s; // A set LSB signifies that the y-coordinate is odd $isYOdd = ($j & 1) == 1; $isSecondKey = $j >> 1; if ($r->cmp($this->curve->p->umod($this->curve->n)) >= 0 && $isSecondKey) throw new \Exception("Unable to find second key candinate"); // 1.1. Let x = r + jn. if( $isSecondKey ) $r = $this->curve->pointFromX($r->add($this->curve->n), $isYOdd); else $r = $this->curve->pointFromX($r, $isYOdd); $eNeg = $this->n->sub($e); // 1.6.1 Compute Q = r^-1 (sR - eG) // Q = r^-1 (sR + -eG) $rInv = $signature->r->invm($this->n); return $this->g->mulAdd($eNeg, $r, $s)->mul($rInv); } public function getKeyRecoveryParam($e, $signature, $Q, $enc = false) { $signature = new Signature($signature, $enc); if( $signature->recoveryParam != null ) return $signature->recoveryParam; for($i = 0; $i < 4; $i++) { $Qprime = null; try { $Qprime = $this->recoverPubKey($e, $signature, $i); } catch(\Exception $e) { continue; } if( $Qprime->eq($Q)) return $i; } throw new \Exception("Unable to find valid recovery factor"); } } ?>
php
MIT
97685bc041bc0df2bea5226e92a7bf07a7cf14db
2026-01-05T05:11:27.721791Z
false
giekaton/php-metamask-user-login
https://github.com/giekaton/php-metamask-user-login/blob/97685bc041bc0df2bea5226e92a7bf07a7cf14db/backend/lib/Elliptic/Utils.php
backend/lib/Elliptic/Utils.php
<?php namespace Elliptic; use \Exception; use BN\BN; class Utils { public static function toArray($msg, $enc = false) { if( is_array($msg) ) return array_slice($msg, 0); if( !$msg ) return array(); if( !is_string($msg) ) throw new Exception("Not implemented"); if( !$enc ) return array_slice(unpack("C*", $msg), 0); if( $enc === "hex" ) return array_slice(unpack("C*", hex2bin($msg)), 0); return $msg; } public static function toHex($msg) { if( is_string($msg) ) return bin2hex($msg); if( !is_array($msg) ) throw new Exception("Not implemented"); $binary = call_user_func_array("pack", array_merge(["C*"], $msg)); return bin2hex($binary); } public static function toBin($msg, $enc = false) { if( is_array($msg) ) return call_user_func_array("pack", array_merge(["C*"], $msg)); if( $enc === "hex" ) return hex2bin($msg); return $msg; } public static function encode($arr, $enc) { if( $enc === "hex" ) return self::toHex($arr); return $arr; } // Represent num in a w-NAF form public static function getNAF($num, $w) { $naf = array(); $ws = 1 << ($w + 1); $k = clone($num); while( $k->cmpn(1) >= 0 ) { if( !$k->isOdd() ) array_push($naf, 0); else { $mod = $k->andln($ws - 1); $z = $mod; if( $mod > (($ws >> 1) - 1)) $z = ($ws >> 1) - $mod; $k->isubn($z); array_push($naf, $z); } // Optimization, shift by word if possible $shift = (!$k->isZero() && $k->andln($ws - 1) === 0) ? ($w + 1) : 1; for($i = 1; $i < $shift; $i++) array_push($naf, 0); $k->iushrn($shift); } return $naf; } // Represent k1, k2 in a Joint Sparse Form public static function getJSF($k1, $k2) { $jsf = array( array(), array() ); $k1 = $k1->_clone(); $k2 = $k2->_clone(); $d1 = 0; $d2 = 0; while( $k1->cmpn(-$d1) > 0 || $k2->cmpn(-$d2) > 0 ) { // First phase $m14 = ($k1->andln(3) + $d1) & 3; $m24 = ($k2->andln(3) + $d2) & 3; if( $m14 === 3 ) $m14 = -1; if( $m24 === 3 ) $m24 = -1; $u1 = 0; if( ($m14 & 1) !== 0 ) { $m8 = ($k1->andln(7) + $d1) & 7; $u1 = ( ($m8 === 3 || $m8 === 5) && $m24 === 2 ) ? -$m14 : $m14; } array_push($jsf[0], $u1); $u2 = 0; if( ($m24 & 1) !== 0 ) { $m8 = ($k2->andln(7) + $d2) & 7; $u2 = ( ($m8 === 3 || $m8 === 5) && $m14 === 2 ) ? -$m24 : $m24; } array_push($jsf[1], $u2); // Second phase if( (2 * $d1) === ($u1 + 1) ) $d1 = 1 - $d1; if( (2 * $d2) === ($u2 + 1) ) $d2 = 1 - $d2; $k1->iushrn(1); $k2->iushrn(1); } return $jsf; } public static function intFromLE($bytes) { return new BN($bytes, 'hex', 'le'); } public static function parseBytes($bytes) { if (is_string($bytes)) return self::toArray($bytes, 'hex'); return $bytes; } public static function randBytes($count) { $res = ""; for($i = 0; $i < $count; $i++) $res .= chr(rand(0, 255)); return $res; } public static function optionAssert(&$array, $key, $value = false, $required = false) { if( isset($array[$key]) ) return; if( $required ) throw new Exception("Missing option " . $key); $array[$key] = $value; } } ?>
php
MIT
97685bc041bc0df2bea5226e92a7bf07a7cf14db
2026-01-05T05:11:27.721791Z
false
giekaton/php-metamask-user-login
https://github.com/giekaton/php-metamask-user-login/blob/97685bc041bc0df2bea5226e92a7bf07a7cf14db/backend/lib/Elliptic/KeyPair.php
backend/lib/Elliptic/KeyPair.php
<?php namespace Elliptic\EC; require_once "BN.php"; use BN\BN; class KeyPair { public $ec; public $pub; public $priv; function __construct($ec, $options) { $this->ec = $ec; $this->priv = null; $this->pub = null; if( isset($options["priv"]) ) $this->_importPrivate($options["priv"], $options["privEnc"]); if( isset($options["pub"]) ) $this->_importPublic($options["pub"], $options["pubEnc"]); } public static function fromPublic($ec, $pub, $enc) { if( $pub instanceof KeyPair ) return $pub; return new KeyPair($ec, array( "pub" => $pub, "pubEnc" => $enc )); } public static function fromPrivate($ec, $priv, $enc) { if( $priv instanceof KeyPair ) return $priv; return new KeyPair($ec, array( "priv" => $priv, "privEnc" => $enc )); } public function validate() { $pub = $this->getPublic(); if( $pub->isInfinity() ) return array( "result" => false, "reason" => "Invalid public key" ); if( !$pub->validate() ) return array( "result" => false, "reason" => "Public key is not a point" ); if( !$pub->mul($this->ec->curve->n)->isInfinity() ) return array( "result" => false, "reason" => "Public key * N != O" ); return array( "result" => true, "reason" => null ); } public function getPublic($compact = false, $enc = "") { //compact is optional argument if( is_string($compact) ) { $enc = $compact; $compact = false; } if( $this->pub === null ) $this->pub = $this->ec->g->mul($this->priv); if( !$enc ) return $this->pub; return $this->pub->encode($enc, $compact); } public function getPrivate($enc = false) { if( $enc === "hex" ) return $this->priv->toString(16, 2); return $this->priv; } private function _importPrivate($key, $enc) { $this->priv = new BN($key, (isset($enc) && $enc) ? $enc : 16); // Ensure that the priv won't be bigger than n, otherwise we may fail // in fixed multiplication method $this->priv = $this->priv->umod($this->ec->curve->n); } private function _importPublic($key, $enc) { $x = $y = null; if ( is_object($key) ) { $x = $key->x; $y = $key->y; } elseif ( is_array($key) ) { $x = isset($key["x"]) ? $key["x"] : null; $y = isset($key["y"]) ? $key["y"] : null; } if( $x != null || $y != null ) $this->pub = $this->ec->curve->point($x, $y); else $this->pub = $this->ec->curve->decodePoint($key, $enc); } //ECDH public function derive($pub) { return $pub->mul($this->priv)->getX(); } //ECDSA public function sign($msg, $enc = false, $options = false) { return $this->ec->sign($msg, $this, $enc, $options); } public function verify($msg, $signature) { return $this->ec->verify($msg, $signature, $this); } public function inspect() { return "<Key priv: " . (isset($this->priv) ? $this->priv->toString(16, 2) : "") . " pub: " . (isset($this->pub) ? $this->pub->inspect() : "") . ">"; } public function __debugInfo() { return ["priv" => $this->priv, "pub" => $this->pub]; } } ?>
php
MIT
97685bc041bc0df2bea5226e92a7bf07a7cf14db
2026-01-05T05:11:27.721791Z
false
giekaton/php-metamask-user-login
https://github.com/giekaton/php-metamask-user-login/blob/97685bc041bc0df2bea5226e92a7bf07a7cf14db/backend/lib/Elliptic/BN.php
backend/lib/Elliptic/BN.php
<?php namespace BN; require_once "BigInteger.php"; require_once "Red.php"; use \JsonSerializable; use \Exception; use \BI\BigInteger; class BN implements JsonSerializable { public $bi; public $red; function __construct($number, $base = 10, $endian = null) { if( $number instanceof BN ) { $this->bi = $number->bi; $this->red = $number->red; return; } // Reduction context $this->red = null; if ( $number instanceof BigInteger ) { $this->bi = $number; return; } if( is_array($number) ) { $number = call_user_func_array("pack", array_merge(array("C*"), $number)); $number = bin2hex($number); $base = 16; } if( $base == "hex" ) $base = 16; if ($endian == 'le') { if ($base != 16) throw new \Exception("Not implemented"); $number = bin2hex(strrev(hex2bin($number))); } $this->bi = new BigInteger($number, $base); } public function negative() { return $this->bi->sign() < 0 ? 1 : 0; } public static function isBN($num) { return ($num instanceof BN); } public static function max($left, $right) { return ( $left->cmp($right) > 0 ) ? $left : $right; } public static function min($left, $right) { return ( $left->cmp($right) < 0 ) ? $left : $right; } public function copy($dest) { $dest->bi = $this->bi; $dest->red = $this->red; } public function _clone() { return clone($this); } public function toString($base = 10, $padding = 0) { if( $base == "hex" ) $base = 16; $str = $this->bi->abs()->toString($base); if ($padding > 0) { $len = strlen($str); $mod = $len % $padding; if ($mod > 0) $len = $len + $padding - $mod; $str = str_pad($str, $len, "0", STR_PAD_LEFT); } if( $this->negative() ) return "-" . $str; return $str; } public function toNumber() { return $this->bi->toNumber(); } public function jsonSerialize() { return $this->toString(16); } public function toArray($endian = "be", $length = -1) { $hex = $this->toString(16); if( $hex[0] === "-" ) $hex = substr($hex, 1); if( strlen($hex) % 2 ) $hex = "0" . $hex; $bytes = array_map( function($v) { return hexdec($v); }, str_split($hex, 2) ); if( $length > 0 ) { $count = count($bytes); if( $count > $length ) throw new Exception("Byte array longer than desired length"); for($i = $count; $i < $length; $i++) array_unshift($bytes, 0); } if( $endian === "le" ) $bytes = array_reverse($bytes); return $bytes; } public function bitLength() { $bin = $this->toString(2); return strlen($bin) - ( $bin[0] === "-" ? 1 : 0 ); } public function zeroBits() { return $this->bi->scan1(0); } public function byteLength() { return ceil($this->bitLength() / 8); } //TODO toTwos, fromTwos public function isNeg() { return $this->negative() !== 0; } // Return negative clone of `this` public function neg() { return $this->_clone()->ineg(); } public function ineg() { $this->bi = $this->bi->neg(); return $this; } // Or `num` with `this` in-place public function iuor(BN $num) { $this->bi = $this->bi->binaryOr($num->bi); return $this; } public function ior(BN $num) { if (assert_options(ASSERT_ACTIVE)) assert(!$this->negative() && !$num->negative()); return $this->iuor($num); } // Or `num` with `this` public function _or(BN $num) { if( $this->ucmp($num) > 0 ) return $this->_clone()->ior($num); return $num->_clone()->ior($this); } public function uor(BN $num) { if( $this->ucmp($num) > 0 ) return $this->_clone()->iuor($num); return $num->_clone()->ior($this); } // And `num` with `this` in-place public function iuand(BN $num) { $this->bi = $this->bi->binaryAnd($num->bi); return $this; } public function iand(BN $num) { if (assert_options(ASSERT_ACTIVE)) assert(!$this->negative() && !$num->negative()); return $this->iuand($num); } // And `num` with `this` public function _and(BN $num) { if( $this->ucmp($num) > 0 ) return $this->_clone()->iand($num); return $num->_clone()->iand($this); } public function uand(BN $num) { if( $this->ucmp($num) > 0 ) return $this->_clone()->iuand($num); return $num->_clone()->iuand($this); } // Xor `num` with `this` in-place public function iuxor(BN $num) { $this->bi = $this->bi->binaryXor($num->bi); return $this; } public function ixor(BN $num) { if (assert_options(ASSERT_ACTIVE)) assert(!$this->negative() && !$num->negative()); return $this->iuxor($num); } // Xor `num` with `this` public function _xor(BN $num) { if( $this->ucmp($num) > 0 ) return $this->_clone()->ixor($num); return $num->_clone()->ixor($this); } public function uxor(BN $num) { if( $this->ucmp($num) > 0 ) return $this->_clone()->iuxor($num); return $num->_clone()->iuxor($this); } // Not ``this`` with ``width`` bitwidth public function inotn($width) { assert(is_integer($width) && $width >= 0); $neg = false; if( $this->isNeg() ) { $this->negi(); $neg = true; } for($i = 0; $i < $width; $i++) $this->bi = $this->bi->setbit($i, !$this->bi->testbit($i)); return $neg ? $this->negi() : $this; } public function notn($width) { return $this->_clone()->inotn($width); } // Set `bit` of `this` public function setn($bit, $val) { assert(is_integer($bit) && $bit > 0); $this->bi = $this->bi->setbit($bit, !!$val); return $this; } // Add `num` to `this` in-place public function iadd(BN $num) { $this->bi = $this->bi->add($num->bi); return $this; } // Add `num` to `this` public function add(BN $num) { return $this->_clone()->iadd($num); } // Subtract `num` from `this` in-place public function isub(BN $num) { $this->bi = $this->bi->sub($num->bi); return $this; } // Subtract `num` from `this` public function sub(BN $num) { return $this->_clone()->isub($num); } // Multiply `this` by `num` public function mul(BN $num) { return $this->_clone()->imul($num); } // In-place Multiplication public function imul(BN $num) { $this->bi = $this->bi->mul($num->bi); return $this; } public function imuln($num) { assert(is_numeric($num)); $int = intval($num); $res = $this->bi->mul($int); if( ($num - $int) > 0 ) { $mul = 10; $frac = ($num - $int) * $mul; $int = intval($frac); while( ($frac - $int) > 0 ) { $mul *= 10; $frac *= 10; $int = intval($frac); } $tmp = $this->bi->mul($int); $tmp = $tmp->div($mul); $res = $res->add($tmp); } $this->bi = $res; return $this; } public function muln($num) { return $this->_clone()->imuln($num); } // `this` * `this` public function sqr() { return $this->mul($this); } // `this` * `this` in-place public function isqr() { return $this->imul($this); } // Math.pow(`this`, `num`) public function pow(BN $num) { $res = clone($this); $res->bi = $res->bi->pow($num->bi); return $res; } // Shift-left in-place public function iushln($bits) { assert(is_integer($bits) && $bits >= 0); if ($bits < 54) { $this->bi = $this->bi->mul(1 << $bits); } else { $this->bi = $this->bi->mul((new BigInteger(2))->pow($bits)); } return $this; } public function ishln($bits) { if (assert_options(ASSERT_ACTIVE)) assert(!$this->negative()); return $this->iushln($bits); } // Shift-right in-place // NOTE: `hint` is a lowest bit before trailing zeroes // NOTE: if `extended` is present - it will be filled with destroyed bits public function iushrn($bits, $hint = 0, &$extended = null) { if( $hint != 0 ) throw new Exception("Not implemented"); assert(is_integer($bits) && $bits >= 0); if( $extended != null ) $extended = $this->maskn($bits); if ($bits < 54) { $this->bi = $this->bi->div(1 << $bits); } else { $this->bi = $this->bi->div((new BigInteger(2))->pow($bits)); } return $this; } public function ishrn($bits, $hint = null, $extended = null) { if (assert_options(ASSERT_ACTIVE)) assert(!$this->negative()); return $this->iushrn($bits, $hint, $extended); } // Shift-left public function shln($bits) { return $this->_clone()->ishln($bits); } public function ushln($bits) { return $this->_clone()->iushln($bits); } // Shift-right public function shrn($bits) { return $this->_clone()->ishrn($bits); } public function ushrn($bits) { return $this->_clone()->iushrn($bits); } // Test if n bit is set public function testn($bit) { assert(is_integer($bit) && $bit >= 0); return $this->bi->testbit($bit); } // Return only lowers bits of number (in-place) public function imaskn($bits) { assert(is_integer($bits) && $bits >= 0); if (assert_options(ASSERT_ACTIVE)) assert(!$this->negative()); $mask = ""; for($i = 0; $i < $bits; $i++) $mask .= "1"; return $this->iand(new BN($mask, 2)); } // Return only lowers bits of number public function maskn($bits) { return $this->_clone()->imaskn($bits); } // Add plain number `num` to `this` public function iaddn($num) { assert(is_numeric($num)); $this->bi = $this->bi->add(intval($num)); return $this; } // Subtract plain number `num` from `this` public function isubn($num) { assert(is_numeric($num)); $this->bi = $this->bi->sub(intval($num)); return $this; } public function addn($num) { return $this->_clone()->iaddn($num); } public function subn($num) { return $this->_clone()->isubn($num); } public function iabs() { if ($this->bi->sign() < 0) { $this->bi = $this->bi->abs(); } return $this; } public function abs() { $res = clone($this); if ($res->bi->sign() < 0) $res->bi = $res->bi->abs(); return $res; } // Find `this` / `num` public function div(BN $num) { if (assert_options(ASSERT_ACTIVE)) assert(!$num->isZero()); $res = clone($this); $res->bi = $res->bi->div($num->bi); return $res; } // Find `this` % `num` public function mod(BN $num) { if (assert_options(ASSERT_ACTIVE)) assert(!$num->isZero()); $res = clone($this); $res->bi = $res->bi->divR($num->bi); return $res; } public function umod(BN $num) { if (assert_options(ASSERT_ACTIVE)) assert(!$num->isZero()); $tmp = $num->bi->sign() < 0 ? $num->bi->abs() : $num->bi; $res = clone($this); $res->bi = $this->bi->mod($tmp); return $res; } // Find Round(`this` / `num`) public function divRound(BN $num) { if (assert_options(ASSERT_ACTIVE)) assert(!$num->isZero()); $negative = $this->negative() !== $num->negative(); $res = $this->_clone()->abs(); $arr = $res->bi->divQR($num->bi->abs()); $res->bi = $arr[0]; $tmp = $num->bi->sub($arr[1]->mul(2)); if( $tmp->cmp(0) <= 0 && (!$negative || $this->negative() === 0) ) $res->iaddn(1); return $negative ? $res->negi() : $res; } public function modn($num) { assert(is_numeric($num) && $num != 0); return $this->bi->divR(intval($num))->toNumber(); } // In-place division by number public function idivn($num) { assert(is_numeric($num) && $num != 0); $this->bi = $this->bi->div(intval($num)); return $this; } public function divn($num) { return $this->_clone()->idivn($num); } public function gcd(BN $num) { $res = clone($this); $res->bi = $this->bi->gcd($num->bi); return $res; } public function invm(BN $num) { $res = clone($this); $res->bi = $res->bi->modInverse($num->bi); return $res; } public function isEven() { return !$this->bi->testbit(0); } public function isOdd() { return $this->bi->testbit(0); } public function andln($num) { assert(is_numeric($num)); return $this->bi->binaryAnd($num)->toNumber(); } public function bincn($num) { $tmp = (new BN(1))->iushln($num); return $this->add($tmp); } public function isZero() { return $this->bi->sign() == 0; } public function cmpn($num) { assert(is_numeric($num)); return $this->bi->cmp($num); } // Compare two numbers and return: // 1 - if `this` > `num` // 0 - if `this` == `num` // -1 - if `this` < `num` public function cmp(BN $num) { return $this->bi->cmp($num->bi); } public function ucmp(BN $num) { return $this->bi->abs()->cmp($num->bi->abs()); } public function gtn($num) { return $this->cmpn($num) > 0; } public function gt(BN $num) { return $this->cmp($num) > 0; } public function gten($num) { return $this->cmpn($num) >= 0; } public function gte(BN $num) { return $this->cmp($num) >= 0; } public function ltn($num) { return $this->cmpn($num) < 0; } public function lt(BN $num) { return $this->cmp($num) < 0; } public function lten($num) { return $this->cmpn($num) <= 0; } public function lte(BN $num) { return $this->cmp($num) <= 0; } public function eqn($num) { return $this->cmpn($num) === 0; } public function eq(BN $num) { return $this->cmp($num) === 0; } public function toRed(Red &$ctx) { if( $this->red !== null ) throw new Exception("Already a number in reduction context"); if( $this->negative() !== 0 ) throw new Exception("red works only with positives"); return $ctx->convertTo($this)->_forceRed($ctx); } public function fromRed() { if( $this->red === null ) throw new Exception("fromRed works only with numbers in reduction context"); return $this->red->convertFrom($this); } public function _forceRed(Red &$ctx) { $this->red = $ctx; return $this; } public function forceRed(Red &$ctx) { if( $this->red !== null ) throw new Exception("Already a number in reduction context"); return $this->_forceRed($ctx); } public function redAdd(BN $num) { if( $this->red === null ) throw new Exception("redAdd works only with red numbers"); $res = clone($this); $res->bi = $res->bi->add($num->bi); if ($res->bi->cmp($this->red->m->bi) >= 0) $res->bi = $res->bi->sub($this->red->m->bi); return $res; // return $this->red->add($this, $num); } public function redIAdd(BN $num) { if( $this->red === null ) throw new Exception("redIAdd works only with red numbers"); $res = $this; $res->bi = $res->bi->add($num->bi); if ($res->bi->cmp($this->red->m->bi) >= 0) $res->bi = $res->bi->sub($this->red->m->bi); return $res; //return $this->red->iadd($this, $num); } public function redSub(BN $num) { if( $this->red === null ) throw new Exception("redSub works only with red numbers"); $res = clone($this); $res->bi = $this->bi->sub($num->bi); if ($res->bi->sign() < 0) $res->bi = $res->bi->add($this->red->m->bi); return $res; //return $this->red->sub($this, $num); } public function redISub(BN $num) { if( $this->red === null ) throw new Exception("redISub works only with red numbers"); $this->bi = $this->bi->sub($num->bi); if ($this->bi->sign() < 0) $this->bi = $this->bi->add($this->red->m->bi); return $this; // return $this->red->isub($this, $num); } public function redShl(BN $num) { if( $this->red === null ) throw new Exception("redShl works only with red numbers"); return $this->red->shl($this, $num); } public function redMul(BN $num) { if( $this->red === null ) throw new Exception("redMul works only with red numbers"); $res = clone($this); $res->bi = $this->bi->mul($num->bi)->mod($this->red->m->bi); return $res; /* return $this->red->mul($this, $num); */ } public function redIMul(BN $num) { if( $this->red === null ) throw new Exception("redIMul works only with red numbers"); $this->bi = $this->bi->mul($num->bi)->mod($this->red->m->bi); return $this; //return $this->red->imul($this, $num); } public function redSqr() { if( $this->red === null ) throw new Exception("redSqr works only with red numbers"); $res = clone($this); $res->bi = $this->bi->mul($this->bi)->mod($this->red->m->bi); return $res; /* $this->red->verify1($this); return $this->red->sqr($this); */ } public function redISqr() { if( $this->red === null ) throw new Exception("redISqr works only with red numbers"); $res = $this; $res->bi = $this->bi->mul($this->bi)->mod($this->red->m->bi); return $res; /* $this->red->verify1($this); return $this->red->isqr($this); */ } public function redSqrt() { if( $this->red === null ) throw new Exception("redSqrt works only with red numbers"); $this->red->verify1($this); return $this->red->sqrt($this); } public function redInvm() { if( $this->red === null ) throw new Exception("redInvm works only with red numbers"); $this->red->verify1($this); return $this->red->invm($this); } public function redNeg() { if( $this->red === null ) throw new Exception("redNeg works only with red numbers"); $this->red->verify1($this); return $this->red->neg($this); } public function redPow(BN $num) { $this->red->verify2($this, $num); return $this->red->pow($this, $num); } public static function red($num) { return new Red($num); } public static function mont($num) { return new Red($num); } public function inspect() { return ($this->red == null ? "<BN: " : "<BN-R: ") . $this->toString(16) . ">"; } public function __debugInfo() { if ($this->red != null) { return ["BN-R" => $this->toString(16)]; } else { return ["BN" => $this->toString(16)]; } } }
php
MIT
97685bc041bc0df2bea5226e92a7bf07a7cf14db
2026-01-05T05:11:27.721791Z
false
giekaton/php-metamask-user-login
https://github.com/giekaton/php-metamask-user-login/blob/97685bc041bc0df2bea5226e92a7bf07a7cf14db/backend/lib/Elliptic/BigInteger.php
backend/lib/Elliptic/BigInteger.php
<?php namespace BI; if (!defined("S_MATH_BIGINTEGER_MODE")) { if (extension_loaded("gmp")) { define("S_MATH_BIGINTEGER_MODE", "gmp"); } else if (extension_loaded("bcmath")) { define("S_MATH_BIGINTEGER_MODE", "bcmath"); } else { if (!defined("S_MATH_BIGINTEGER_QUIET")) { throw new \Exception("Cannot use BigInteger. Neither gmp nor bcmath module is loaded"); } } } if (S_MATH_BIGINTEGER_MODE == "gmp") { if (!extension_loaded("gmp")) { throw new \Exception("Extension gmp not loaded"); } class BigInteger { public $value; public function __construct($value = 0, $base = 10) { $this->value = $base === true ? $value : BigInteger::getGmp($value, $base); } public static function createSafe($value = 0, $base = 10) { try { return new BigInteger($value, $base); } catch (\Exception $e) { return false; } } public static function isGmp($var) { if (is_resource($var)) { return get_resource_type($var) == "GMP integer"; } if (class_exists("GMP") && $var instanceof \GMP) { return true; } return false; } public static function getGmp($value = 0, $base = 10) { if ($value instanceof BigInteger) { return $value->value; } if (BigInteger::isGmp($value)) { return $value; } $type = gettype($value); if ($type == "integer") { $gmp = gmp_init($value); if ($gmp === false) { throw new \Exception("Cannot initialize"); } return $gmp; } if ($type == "string") { if ($base != 2 && $base != 10 && $base != 16 && $base != 256) { throw new \Exception("Unsupported BigInteger base"); } if ($base == 256) { $value = bin2hex($value); $base = 16; } $level = error_reporting(); error_reporting(0); $gmp = gmp_init($value, $base); error_reporting($level); if ($gmp === false) { throw new \Exception("Cannot initialize"); } return $gmp; } throw new \Exception("Unsupported value, only string and integer are allowed, receive " . $type . ($type == "object" ? ", class: " . get_class($value) : "")); } public function toDec() { return gmp_strval($this->value, 10); } public function toHex() { $hex = gmp_strval($this->value, 16); return strlen($hex) % 2 == 1 ? "0". $hex : $hex; } public function toBytes() { return hex2bin($this->toHex()); } public function toBase($base) { if ($base < 2 || $base > 62) { throw new \Exception("Invalid base"); } return gmp_strval($this->value, $base); } public function toBits() { return gmp_strval($this->value, 2); } public function toString($base = 10) { if ($base == 2) { return $this->toBits(); } if ($base == 10) { return $this->toDec(); } if ($base == 16) { return $this->toHex(); } if ($base == 256) { return $this->toBytes(); } return $this->toBase($base); } public function __toString() { return $this->toString(); } public function toNumber() { return gmp_intval($this->value); } public function add($x) { return new BigInteger(gmp_add($this->value, BigInteger::getGmp($x)), true); } public function sub($x) { return new BigInteger(gmp_sub($this->value, BigInteger::getGmp($x)), true); } public function mul($x) { return new BigInteger(gmp_mul($this->value, BigInteger::getGmp($x)), true); } public function div($x) { return new BigInteger(gmp_div_q($this->value, BigInteger::getGmp($x)), true); } public function divR($x) { return new BigInteger(gmp_div_r($this->value, BigInteger::getGmp($x)), true); } public function divQR($x) { $res = gmp_div_qr($this->value, BigInteger::getGmp($x)); return array(new BigInteger($res[0], true), new BigInteger($res[1], true)); } public function mod($x) { return new BigInteger(gmp_mod($this->value, BigInteger::getGmp($x)), true); } public function gcd($x) { return new BigInteger(gmp_gcd($this->value, BigInteger::getGmp($x)), true); } public function modInverse($x) { $res = gmp_invert($this->value, BigInteger::getGmp($x)); return $res === false ? false : new BigInteger($res, true); } public function pow($x) { return new BigInteger(gmp_pow($this->value, (new BigInteger($x))->toNumber()), true); } public function powMod($x, $n) { return new BigInteger(gmp_powm($this->value, BigInteger::getGmp($x), BigInteger::getGmp($n)), true); } public function abs() { return new BigInteger(gmp_abs($this->value), true); } public function neg() { return new BigInteger(gmp_neg($this->value), true); } public function binaryAnd($x) { return new BigInteger(gmp_and($this->value, BigInteger::getGmp($x)), true); } public function binaryOr($x) { return new BigInteger(gmp_or($this->value, BigInteger::getGmp($x)), true); } public function binaryXor($x) { return new BigInteger(gmp_xor($this->value, BigInteger::getGmp($x)), true); } public function setbit($index, $bitOn = true) { $cpy = gmp_init(gmp_strval($this->value, 16), 16); gmp_setbit($cpy, $index, $bitOn); return new BigInteger($cpy, true); } public function testbit($index) { return gmp_testbit($this->value, $index); } public function scan0($start) { return gmp_scan0($this->value, $start); } public function scan1($start) { return gmp_scan1($this->value, $start); } public function cmp($x) { return gmp_cmp($this->value, BigInteger::getGmp($x)); } public function equals($x) { return $this->cmp($x) === 0; } public function sign() { return gmp_sign($this->value); } } } else if (S_MATH_BIGINTEGER_MODE == "bcmath") { if (!extension_loaded("bcmath")) { throw new \Exception("Extension bcmath not loaded"); } class BigInteger{ public static $chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv"; public $value; public function __construct($value = 0, $base = 10) { $this->value = $base === true ? $value : BigInteger::getBC($value, $base); } public static function createSafe($value = 0, $base = 10) { try { return new BigInteger($value, $base); } catch (\Exception $e) { return false; } } public static function checkBinary($str) { $len = strlen($str); for ($i = 0; $i < $len; $i++) { $c = ord($str[$i]); if (($i != 0 || $c != 45) && ($c < 48 || $c > 49)) { return false; } } return true; } public static function checkDecimal($str) { $len = strlen($str); for ($i = 0; $i < $len; $i++) { $c = ord($str[$i]); if (($i != 0 || $c != 45) && ($c < 48 || $c > 57)) { return false; } } return true; } public static function checkHex($str) { $len = strlen($str); for ($i = 0; $i < $len; $i++) { $c = ord($str[$i]); if (($i != 0 || $c != 45) && ($c < 48 || $c > 57) && ($c < 65 || $c > 70) && ($c < 97 || $c > 102)) { return false; } } return true; } public static function getBC($value = 0, $base = 10) { if ($value instanceof BigInteger) { return $value->value; } $type = gettype($value); if ($type == "integer") { return strval($value); } if ($type == "string") { if ($base == 2) { $value = str_replace(" ", "", $value); if (!BigInteger::checkBinary($value)) { throw new \Exception("Invalid characters"); } $minus = $value[0] == "-"; if ($minus) { $value = substr($value, 1); } $len = strlen($value); $m = 1; $res = "0"; for ($i = $len - 1; $i >= 0; $i -= 8) { $h = $i - 7 < 0 ? substr($value, 0, $i + 1) : substr($value, $i - 7, 8); $res = bcadd($res, bcmul(bindec($h), $m, 0), 0); $m = bcmul($m, "256", 0); } return ($minus ? "-" : "") . $res; } if ($base == 10) { $value = str_replace(" ", "", $value); if (!BigInteger::checkDecimal($value)) { throw new \Exception("Invalid characters"); } return $value; } if ($base == 16) { $value = str_replace(" ", "", $value); if (!BigInteger::checkHex($value)) { throw new \Exception("Invalid characters"); } $minus = $value[0] == "-"; if ($minus) { $value = substr($value, 1); } $len = strlen($value); $m = 1; $res = "0"; for ($i = $len - 1; $i >= 0; $i -= 2) { $h = $i == 0 ? "0" . substr($value, 0, 1) : substr($value, $i - 1, 2); $res = bcadd($res, bcmul(hexdec($h), $m, 0), 0); $m = bcmul($m, "256", 0); } return ($minus ? "-" : "") . $res; } if ($base == 256) { $len = strlen($value); $m = 1; $res = "0"; for ($i = $len - 1; $i >= 0; $i -= 6) { $h = $i - 5 < 0 ? substr($value, 0, $i + 1) : substr($value, $i - 5, 6); $res = bcadd($res, bcmul(base_convert(bin2hex($h), 16, 10), $m, 0), 0); $m = bcmul($m, "281474976710656", 0); } return $res; } throw new \Exception("Unsupported BigInteger base"); } throw new \Exception("Unsupported value, only string and integer are allowed, receive " . $type . ($type == "object" ? ", class: " . get_class($value) : "")); } public function toDec() { return $this->value; } public function toHex() { return bin2hex($this->toBytes()); } public function toBytes() { $value = ""; $current = $this->value; if ($current[0] == "-") { $current = substr($current, 1); } while (bccomp($current, "0", 0) > 0) { $temp = bcmod($current, "281474976710656"); $value = hex2bin(str_pad(base_convert($temp, 10, 16), 12, "0", STR_PAD_LEFT)) . $value; $current = bcdiv($current, "281474976710656", 0); } return ltrim($value, chr(0)); } public function toBase($base) { if ($base < 2 || $base > 62) { throw new \Exception("Invalid base"); } $value = ''; $current = $this->value; $base = BigInteger::getBC($base); if ($current[0] == '-') { $current = substr($current, 1); } while (bccomp($current, '0', 0) > 0) { $v = bcmod($current, $base); $value = BigInteger::$chars[$v] . $value; $current = bcdiv($current, $base, 0); } return $value; } public function toBits() { $bytes = $this->toBytes(); $res = ""; $len = strlen($bytes); for ($i = 0; $i < $len; $i++) { $b = decbin(ord($bytes[$i])); $res .= strlen($b) != 8 ? str_pad($b, 8, "0", STR_PAD_LEFT) : $b; } $res = ltrim($res, "0"); return strlen($res) == 0 ? "0" : $res; } public function toString($base = 10) { if ($base == 2) { return $this->toBits(); } if ($base == 10) { return $this->toDec(); } if ($base == 16) { return $this->toHex(); } if ($base == 256) { return $this->toBytes(); } return $this->toBase($base); } public function __toString() { return $this->toString(); } public function toNumber() { return intval($this->value); } public function add($x) { return new BigInteger(bcadd($this->value, BigInteger::getBC($x), 0), true); } public function sub($x) { return new BigInteger(bcsub($this->value, BigInteger::getBC($x), 0), true); } public function mul($x) { return new BigInteger(bcmul($this->value, BigInteger::getBC($x), 0), true); } public function div($x) { return new BigInteger(bcdiv($this->value, BigInteger::getBC($x), 0), true); } public function divR($x) { return new BigInteger(bcmod($this->value, BigInteger::getBC($x)), true); } public function divQR($x) { return array( $this->div($x), $this->divR($x) ); } public function mod($x) { $xv = BigInteger::getBC($x); $mod = bcmod($this->value, $xv); if ($mod[0] == "-") { $mod = bcadd($mod, $xv[0] == "-" ? substr($xv, 1) : $xv, 0); } return new BigInteger($mod, true); } public function extendedGcd($n) { $u = $this->value; $v = (new BigInteger($n))->abs()->value; $a = "1"; $b = "0"; $c = "0"; $d = "1"; while (bccomp($v, "0", 0) != 0) { $q = bcdiv($u, $v, 0); $temp = $u; $u = $v; $v = bcsub($temp, bcmul($v, $q, 0), 0); $temp = $a; $a = $c; $c = bcsub($temp, bcmul($a, $q, 0), 0); $temp = $b; $b = $d; $d = bcsub($temp, bcmul($b, $q, 0), 0); } return array( "gcd" => new BigInteger($u, true), "x" => new BigInteger($a, true), "y" => new BigInteger($b, true) ); } public function gcd($x) { return $this->extendedGcd($x)["gcd"]; } public function modInverse($n) { $n = (new BigInteger($n))->abs(); if ($this->sign() < 0) { $temp = $this->abs(); $temp = $temp->modInverse($n); return $n->sub($temp); } extract($this->extendedGcd($n)); if (!$gcd->equals(1)) { return false; } $x = $x->sign() < 0 ? $x->add($n) : $x; return $this->sign() < 0 ? $n->sub($x) : $x; } public function pow($x) { return new BigInteger(bcpow($this->value, BigInteger::getBC($x), 0), true); } public function powMod($x, $n) { return new BigInteger(bcpowmod($this->value, BigInteger::getBC($x), BigInteger::getBC($n), 0), true); } public function abs() { return new BigInteger($this->value[0] == "-" ? substr($this->value, 1) : $this->value, true); } public function neg() { return new BigInteger($this->value[0] == "-" ? substr($this->value, 1) : "-" . $this->value, true); } public function binaryAnd($x) { $left = $this->toBytes(); $right = (new BigInteger($x))->toBytes(); $length = max(strlen($left), strlen($right)); $left = str_pad($left, $length, chr(0), STR_PAD_LEFT); $right = str_pad($right, $length, chr(0), STR_PAD_LEFT); return new BigInteger($left & $right, 256); } public function binaryOr($x) { $left = $this->toBytes(); $right = (new BigInteger($x))->toBytes(); $length = max(strlen($left), strlen($right)); $left = str_pad($left, $length, chr(0), STR_PAD_LEFT); $right = str_pad($right, $length, chr(0), STR_PAD_LEFT); return new BigInteger($left | $right, 256); } public function binaryXor($x) { $left = $this->toBytes(); $right = (new BigInteger($x))->toBytes(); $length = max(strlen($left), strlen($right)); $left = str_pad($left, $length, chr(0), STR_PAD_LEFT); $right = str_pad($right, $length, chr(0), STR_PAD_LEFT); return new BigInteger($left ^ $right, 256); } public function setbit($index, $bitOn = true) { $bits = $this->toBits(); $bits[strlen($bits) - $index - 1] = $bitOn ? "1" : "0"; return new BigInteger($bits, 2); } public function testbit($index) { $bytes = $this->toBytes(); $bytesIndex = intval($index / 8); $len = strlen($bytes); $b = $bytesIndex >= $len ? 0 : ord($bytes[$len - $bytesIndex - 1]); $v = 1 << ($index % 8); return ($b & $v) === $v; } public function scan0($start) { $bits = $this->toBits(); $len = strlen($bits); if ($start < 0 || $start >= $len) { return -1; } $pos = strrpos($bits, "0", -1 - $start); return $pos === false ? -1 : $len - $pos - 1; } public function scan1($start) { $bits = $this->toBits(); $len = strlen($bits); if ($start < 0 || $start >= $len) { return -1; } $pos = strrpos($bits, "1", -1 - $start); return $pos === false ? -1 : $len - $pos - 1; } public function cmp($x) { return bccomp($this->value, BigInteger::getBC($x)); } public function equals($x) { return $this->value === BigInteger::getBC($x); } public function sign() { return $this->value[0] === "-" ? -1 : ($this->value === "0" ? 0 : 1); } } } else { if (!defined("S_MATH_BIGINTEGER_QUIET")) { throw new \Exception("Unsupported S_MATH_BIGINTEGER_MODE " . S_MATH_BIGINTEGER_MODE); } }
php
MIT
97685bc041bc0df2bea5226e92a7bf07a7cf14db
2026-01-05T05:11:27.721791Z
false
giekaton/php-metamask-user-login
https://github.com/giekaton/php-metamask-user-login/blob/97685bc041bc0df2bea5226e92a7bf07a7cf14db/backend/lib/Elliptic/Red.php
backend/lib/Elliptic/Red.php
<?php namespace BN; use \Exception; use \BI\BigInteger; class Red { public $m; function __construct($m) { if( is_string($m) ) $this->m = Red::primeByName($m); else $this->m = $m; if( !$this->m->gtn(1) ) throw new Exception("Modulus must be greater than 1"); } public static function primeByName($name) { switch($name) { case "k256": return new BN("ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f", 16); case "p224": return new BN("ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001", 16); case "p192": return new BN("ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff", 16); case "p25519": return new BN("7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", 16); default: throw new Exception("Unknown prime name " . $name); } } public function verify1(BN $num) { if (assert_options(ASSERT_ACTIVE)) assert(!$num->negative()); //,"red works only with positives"); assert($num->red); //, "red works only with red numbers"); } public function verify2(BN $a, BN $b) { if (assert_options(ASSERT_ACTIVE)) assert(!$a->negative() && !$b->negative()); //, "red works only with positives"); assert($a->red && ($a->red == $b->red)); //, "red works only with red numbers"); } public function imod(BN &$a) { return $a->umod($this->m)->_forceRed($this); } public function neg(BN $a) { if( $a->isZero() ) return $a->_clone(); return $this->m->sub($a)->_forceRed($this); } public function add(BN $a, BN $b) { $this->verify2($a, $b); $res = $a->add($b); if( $res->cmp($this->m) >= 0 ) $res->isub($this->m); return $res->_forceRed($this); } public function iadd(BN &$a, BN $b) { $this->verify2($a, $b); $a->iadd($b); if( $a->cmp($this->m) >= 0 ) $a->isub($this->m); return $a; } public function sub(BN $a, BN $b) { $this->verify2($a, $b); $res = $a->sub($b); if( $res->negative() ) $res->iadd($this->m); return $res->_forceRed($this); } public function isub(BN &$a, $b) { $this->verify2($a, $b); $a->isub($b); if( $a->negative() ) $a->iadd($this->m); return $a; } public function shl(BN $a, $num) { $this->verify1($a); return $this->imod($a->ushln($num)); } public function imul(BN &$a, BN $b) { $this->verify2($a, $b); $res = $a->imul($b); return $this->imod($res); } public function mul(BN $a, BN $b) { $this->verify2($a, $b); $res = $a->mul($b); return $this->imod($res); } public function sqr(BN $a) { $res = $a->_clone(); return $this->imul($res, $a); } public function isqr(BN &$a) { return $this->imul($a, $a); } public function sqrt(BN $a) { if ($a->isZero()) return $a->_clone(); $mod3 = $this->m->andln(3); assert($mod3 % 2 == 1); // Fast case if ($mod3 == 3) { $pow = $this->m->add(new BN(1))->iushrn(2); return $this->pow($a, $pow); } // Tonelli-Shanks algorithm (Totally unoptimized and slow) // // Find Q and S, that Q * 2 ^ S = (P - 1) $q = $this->m->subn(1); $s = 0; while (!$q->isZero() && $q->andln(1) == 0) { $s++; $q->iushrn(1); } if (assert_options(ASSERT_ACTIVE)) assert(!$q->isZero()); $one = (new BN(1))->toRed($this); $nOne = $one->redNeg(); // Find quadratic non-residue // NOTE: Max is such because of generalized Riemann hypothesis. $lpow = $this->m->subn(1)->iushrn(1); $z = $this->m->bitLength(); $z = (new BN(2 * $z * $z))->toRed($this); while ($this->pow($z, $lpow)->cmp($nOne) != 0) { $z->redIAdd($nOne); } $c = $this->pow($z, $q); $r = $this->pow($a, $q->addn(1)->iushrn(1)); $t = $this->pow($a, $q); $m = $s; while ($t->cmp($one) != 0) { $tmp = $t; for ($i = 0; $tmp->cmp($one) != 0; $i++) { $tmp = $tmp->redSqr(); } if ($i >= $m) { throw new \Exception("Assertion failed"); } if ($m - $i - 1 > 54) { $b = $this->pow($c, (new BN(1))->iushln($m - $i - 1)); } else { $b = clone($c); $b->bi = $c->bi->powMod(1 << ($m - $i - 1), $this->m->bi); } $r = $r->redMul($b); $c = $b->redSqr(); $t = $t->redMul($c); $m = $i; } return $r; } public function invm(BN &$a) { $res = $a->invm($this->m); return $this->imod($res); } public function pow(BN $a, BN $num) { $r = clone($a); $r->bi = $a->bi->powMod($num->bi, $this->m->bi); return $r; } public function convertTo(BN $num) { $r = $num->umod($this->m); return $r === $num ? $r->_clone() : $r; } public function convertFrom(BN $num) { $res = $num->_clone(); $res->red = null; return $res; } } ?>
php
MIT
97685bc041bc0df2bea5226e92a7bf07a7cf14db
2026-01-05T05:11:27.721791Z
false
giekaton/php-metamask-user-login
https://github.com/giekaton/php-metamask-user-login/blob/97685bc041bc0df2bea5226e92a7bf07a7cf14db/backend/lib/Elliptic/Curve/EdwardsCurve.php
backend/lib/Elliptic/Curve/EdwardsCurve.php
<?php namespace Elliptic\Curve; require_once "EdwardsCurve/Point.php"; use Elliptic\Curve\EdwardsCurve\Point; use BN\BN; class EdwardsCurve extends BaseCurve { public $twisted; public $mOneA; public $extended; public $a; public $c; public $c2; public $d; public $d2; public $dd; public $oneC; function __construct($conf) { // NOTE: Important as we are creating point in Base.call() $this->twisted = ($conf["a"] | 0) != 1; $this->mOneA = $this->twisted && ($conf["a"] | 0) == -1; $this->extended = $this->mOneA; parent::__construct("edward", $conf); $this->a = (new BN($conf["a"], 16))->umod($this->red->m); $this->a = $this->a->toRed($this->red); $this->c = (new BN($conf["c"], 16))->toRed($this->red); $this->c2 = $this->c->redSqr(); $this->d = (new BN($conf["d"], 16))->toRed($this->red); $this->dd = $this->d->redAdd($this->d); if (assert_options(ASSERT_ACTIVE)) { assert(!$this->twisted || $this->c->fromRed()->cmpn(1) == 0); } $this->oneC = ($conf["c"] | 0) == 1; } public function _mulA($num) { if ($this->mOneA) return $num->redNeg(); else return $this->a->redMul($num); } public function _mulC($num) { if ($this->oneC) return $num; else return $this->c->redMul($num); } // Just for compatibility with Short curve public function jpoint($x, $y, $z, $t = null) { return $this->point($x, $y, $z, $t); } public function pointFromX($x, $odd = false) { $x = new BN($x, 16); if (!$x->red) $x = $x->toRed($this->red); $x2 = $x->redSqr(); $rhs = $this->c2->redSub($this->a->redMul($x2)); $lhs = $this->one->redSub($this->c2->redMul($this->d)->redMul($x2)); $y2 = $rhs->redMul($lhs->redInvm()); $y = $y2->redSqrt(); if ($y->redSqr()->redSub($y2)->cmp($this->zero) != 0) throw new \Exception('invalid point'); $isOdd = $y->fromRed()->isOdd(); if ($odd && !$isOdd || !$odd && $isOdd) $y = $y->redNeg(); return $this->point($x, $y); } public function pointFromY($y, $odd = false) { $y = new BN($y, 16); if (!$y->red) $y = $y->toRed($this->red); // x^2 = (y^2 - 1) / (d y^2 + 1) $y2 = $y->redSqr(); $lhs = $y2->redSub($this->one); $rhs = $y2->redMul($this->d)->redAdd($this->one); $x2 = $lhs->redMul($rhs->redInvm()); if ($x2->cmp($this->zero) == 0) { if ($odd) throw new \Exception('invalid point'); else return $this->point($this->zero, $y); } $x = $x2->redSqrt(); if ($x->redSqr()->redSub($x2)->cmp($this->zero) != 0) throw new \Exception('invalid point'); if ($x->isOdd() != $odd) $x = $x->redNeg(); return $this->point($x, $y); } public function validate($point) { if ($point->isInfinity()) return true; // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2) $point->normalize(); $x2 = $point->x->redSqr(); $y2 = $point->y->redSqr(); $lhs = $x2->redMul($this->a)->redAdd($y2); $rhs = $this->c2->redMul($this->one->redAdd($this->d->redMul($x2)->redMul($y2))); return $lhs->cmp($rhs) == 0; } public function pointFromJSON($obj) { return Point::fromJSON($this, $obj); } public function point($x = null, $y = null, $z = null, $t = null) { return new Point($this, $x, $y, $z, $t); } }
php
MIT
97685bc041bc0df2bea5226e92a7bf07a7cf14db
2026-01-05T05:11:27.721791Z
false
giekaton/php-metamask-user-login
https://github.com/giekaton/php-metamask-user-login/blob/97685bc041bc0df2bea5226e92a7bf07a7cf14db/backend/lib/Elliptic/Curve/ShortCurve.php
backend/lib/Elliptic/Curve/ShortCurve.php
<?php namespace Elliptic\Curve; require_once "BaseCurve.php"; require_once "BaseCurve/Point.php"; require_once "ShortCurve/Point.php"; require_once "ShortCurve/JPoint.php"; use Elliptic\Curve\ShortCurve\Point; use Elliptic\Curve\ShortCurve\JPoint; use BN\BN; use \Exception; class ShortCurve extends BaseCurve { public $a; public $b; public $tinv; public $zeroA; public $threeA; public $endo; private $_endoWnafT1; private $_endoWnafT2; function __construct($conf) { parent::__construct("short", $conf); $this->a = (new BN($conf["a"], 16))->toRed($this->red); $this->b = (new BN($conf["b"], 16))->toRed($this->red); $this->tinv = $this->two->redInvm(); $this->zeroA = $this->a->fromRed()->isZero(); $this->threeA = $this->a->fromRed()->sub($this->p)->cmpn(-3) === 0; // If curve is endomorphic, precalculate beta and lambda $this->endo = $this->_getEndomorphism($conf); $this->_endoWnafT1 = array(0,0,0,0); $this->_endoWnafT2 = array(0,0,0,0); } private function _getEndomorphism($conf) { // No efficient endomorphism if( !$this->zeroA || !isset($this->g) || !isset($this->n) || $this->p->modn(3) != 1 ) return null; // Compute beta and lambda, that lambda * P = (beta * Px; Py) $beta = null; $lambda = null; if( isset($conf["beta"]) ) $beta = (new BN($conf["beta"], 16))->toRed($this->red); else { $betas = $this->_getEndoRoots($this->p); // Choose smallest beta $beta = $betas[0]->cmp($betas[1]) < 0 ? $betas[0] : $betas[1]; $beta = $beta->toRed($this->red); } if( isset($conf["lambda"]) ) $lambda = new BN($conf["lambda"], 16); else { // Choose the lambda that is matching selected beta $lambdas = $this->_getEndoRoots($this->n); if( $this->g->mul($lambdas[0])->x->cmp($this->g->x->redMul($beta)) == 0 ) $lambda = $lambdas[0]; else { $lambda = $lambdas[1]; if (assert_options(ASSERT_ACTIVE)) { assert($this->g->mul($lambda)->x->cmp($this->g->x->redMul($beta)) === 0); } } } // Get basis vectors, used for balanced length-two representation $basis = null; if( !isset($conf["basis"]) ) $basis = $this->_getEndoBasis($lambda); else { $callback = function($vector) { return array( "a" => new BN($vector["a"], 16), "b" => new BN($vector["b"], 16) ); }; $basis = array_map($callback, $conf["basis"]); } return array( "beta" => $beta, "lambda" => $lambda, "basis" => $basis ); } private function _getEndoRoots($num) { // Find roots of for x^2 + x + 1 in F // Root = (-1 +- Sqrt(-3)) / 2 // $red = $num === $this->p ? $this->red : BN::mont($num); $tinv = (new BN(2))->toRed($red)->redInvm(); $ntinv = $tinv->redNeg(); $s = (new BN(3))->toRed($red)->redNeg()->redSqrt()->redMul($tinv); return array( $ntinv->redAdd($s)->fromRed(), $ntinv->redSub($s)->fromRed() ); } private function _getEndoBasis($lambda) { // aprxSqrt >= sqrt(this.n) $aprxSqrt = $this->n->ushrn(intval($this->n->bitLength() / 2)); // 3.74 // Run EGCD, until r(L + 1) < aprxSqrt $u = $lambda; $v = $this->n->_clone(); $x1 = new BN(1); $y1 = new BN(0); $x2 = new BN(0); $y2 = new BN(1); // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n) $a0 = 0; $b0 = 0; // First vector $a1 = 0; $b1 = 0; // Second vector $a2 = 0; $b2 = 0; $prevR = 0; $i = 0; $r = 0; $x = 0; while( ! $u->isZero() ) { $q = $v->div($u); $r = $v->sub($q->mul($u)); $x = $x2->sub($q->mul($x1)); $y = $y2->sub($q->mul($y2)); if( !$a1 && $r->cmp($aprxSqrt) < 0 ) { $a0 = $prevR->neg(); $b0 = $x1; $a1 = $r->neg(); $b1 = $x; } elseif($a1 && ++$i === 2) break; $prevR = $r; $v = $u; $u = $r; $x2 = $x1; $x1 = $x; $y2 = $y1; $y1 = $y; } $a2 = $r->neg(); $b2 = $x; $len1 = $a1->sqr()->add($b1->sqr()); $len2 = $a2->sqr()->add($b2->sqr()); if( $len2->cmp($len1) >= 0 ) { $a2 = $a0; $b2 = $b0; } // Normalize signs if( $a1->negative() ) { $a1 = $a1->neg(); $b1 = $b1->neg(); } if( $a2->negative() ) { $a2 = $a2->neg(); $b2 = $b2->neg(); } return array( array( "a" => $a1, "b" => $b1 ), array( "a" => $a2, "b" => $b2 ), ); } public function _endoSplit($k) { $basis = $this->endo["basis"]; $v1 = $basis[0]; $v2 = $basis[1]; $c1 = $v2["b"]->mul($k)->divRound($this->n); $c2 = $v1["b"]->neg()->mul($k)->divRound($this->n); $p1 = $c1->mul($v1["a"]); $p2 = $c2->mul($v2["a"]); $q1 = $c1->mul($v1["b"]); $q2 = $c2->mul($v2["b"]); //Calculate answer $k1 = $k->sub($p1)->sub($p2); $k2 = $q1->add($q2)->neg(); return array( "k1" => $k1, "k2" => $k2 ); } public function pointFromX($x, $odd) { $x = new BN($x, 16); if( !$x->red ) $x = $x->toRed($this->red); $y2 = $x->redSqr()->redMul($x)->redIAdd($x->redMul($this->a))->redIAdd($this->b); $y = $y2->redSqrt(); if( $y->redSqr()->redSub($y2)->cmp($this->zero) !== 0 ) throw new Exception("Invalid point"); // XXX Is there any way to tell if the number is odd without converting it // to non-red form? $isOdd = $y->fromRed()->isOdd(); if( $odd != $isOdd ) $y = $y->redNeg(); return $this->point($x, $y); } public function validate($point) { if( $point->inf ) return true; $x = $point->x; $y = $point->y; $ax = $this->a->redMul($x); $rhs = $x->redSqr()->redMul($x)->redIAdd($ax)->redIAdd($this->b); return $y->redSqr()->redISub($rhs)->isZero(); } public function _endoWnafMulAdd($points, $coeffs, $jacobianResult = false) { $npoints = &$this->_endoWnafT1; $ncoeffs = &$this->_endoWnafT2; for($i = 0; $i < count($points); $i++) { $split = $this->_endoSplit($coeffs[$i]); $p = $points[$i]; $beta = $p->_getBeta(); if( $split["k1"]->negative() ) { $split["k1"]->ineg(); $p = $p->neg(true); } if( $split["k2"]->negative() ) { $split["k2"]->ineg(); $beta = $beta->neg(true); } $npoints[$i * 2] = $p; $npoints[$i * 2 + 1] = $beta; $ncoeffs[$i * 2] = $split["k1"]; $ncoeffs[$i * 2 + 1] = $split["k2"]; } $res = $this->_wnafMulAdd(1, $npoints, $ncoeffs, $i * 2, $jacobianResult); // Clean-up references to points and coefficients for($j = 0; $j < 2 * $i; $j++) { $npoints[$j] = null; $ncoeffs[$j] = null; } return $res; } public function point($x, $y, $isRed = false) { return new Point($this, $x, $y, $isRed); } public function pointFromJSON($obj, $red) { return Point::fromJSON($this, $obj, $red); } public function jpoint($x, $y, $z) { return new JPoint($this, $x, $y, $z); } } ?>
php
MIT
97685bc041bc0df2bea5226e92a7bf07a7cf14db
2026-01-05T05:11:27.721791Z
false
giekaton/php-metamask-user-login
https://github.com/giekaton/php-metamask-user-login/blob/97685bc041bc0df2bea5226e92a7bf07a7cf14db/backend/lib/Elliptic/Curve/PresetCurve.php
backend/lib/Elliptic/Curve/PresetCurve.php
<?php namespace Elliptic\Curve; require_once "ShortCurve.php"; require_once "MontCurve.php"; require_once "EdwardsCurve.php"; class PresetCurve { public $curve; public $g; public $n; public $hash; function __construct($options) { if ( $options["type"] === "short" ) $this->curve = new ShortCurve($options); elseif ( $options["type"] === "edwards" ) $this->curve = new EdwardsCurve($options); else $this->curve = new MontCurve($options); $this->g = $this->curve->g; $this->n = $this->curve->n; $this->hash = isset($options["hash"]) ? $options["hash"] : null; } } ?>
php
MIT
97685bc041bc0df2bea5226e92a7bf07a7cf14db
2026-01-05T05:11:27.721791Z
false
giekaton/php-metamask-user-login
https://github.com/giekaton/php-metamask-user-login/blob/97685bc041bc0df2bea5226e92a7bf07a7cf14db/backend/lib/Elliptic/Curve/BaseCurve.php
backend/lib/Elliptic/Curve/BaseCurve.php
<?php namespace Elliptic\Curve; require_once __DIR__ . "/../BN.php"; use Elliptic\Utils; use \Exception; use BN\BN; abstract class BaseCurve { public $type; public $p; public $red; public $zero; public $one; public $two; public $n; public $g; protected $_wnafT1; protected $_wnafT2; protected $_wnafT3; protected $_wnafT4; public $redN; public $_maxwellTrick; function __construct($type, $conf) { $this->type = $type; $this->p = new BN($conf["p"], 16); //Use Montgomery, when there is no fast reduction for the prime $this->red = isset($conf["prime"]) ? BN::red($conf["prime"]) : BN::mont($this->p); //Useful for many curves $this->zero = (new BN(0))->toRed($this->red); $this->one = (new BN(1))->toRed($this->red); $this->two = (new BN(2))->toRed($this->red); //Curve configuration, optional $this->n = isset($conf["n"]) ? new BN($conf["n"], 16) : null; $this->g = isset($conf["g"]) ? $this->pointFromJSON($conf["g"], isset($conf["gRed"]) ? $conf["gRed"] : null) : null; //Temporary arrays $this->_wnafT1 = array(0,0,0,0); $this->_wnafT2 = array(0,0,0,0); $this->_wnafT3 = array(0,0,0,0); $this->_wnafT4 = array(0,0,0,0); //Generalized Greg Maxwell's trick $adjustCount = $this->n != null ? $this->p->div($this->n) : null; if( $adjustCount == null || $adjustCount->cmpn(100) > 0 ) { $this->redN = null; $this->_maxwellTrick = false; } else { $this->redN = $this->n->toRed($this->red); $this->_maxwellTrick = true; } } abstract public function point($x, $z); abstract public function validate($point); public function _fixedNafMul($p, $k) { assert(isset($p->precomputed)); $doubles = $p->_getDoubles(); $naf = Utils::getNAF($k, 1); $I = (1 << ($doubles["step"] + 1)) - ($doubles["step"] % 2 == 0 ? 2 : 1); $I = $I / 3; //Translate to more windowed form $repr = array(); for($j = 0; $j < count($naf); $j += $doubles["step"]) { $nafW = 0; for($k = $j + $doubles["step"] - 1; $k >= $j; $k--) $nafW = ($nafW << 1) + (isset($naf[$k]) ? $naf[$k] : 0); array_push($repr, $nafW); } $a = $this->jpoint(null, null, null); $b = $this->jpoint(null, null, null); for($i = $I; $i > 0; $i--) { for($j = 0; $j < count($repr); $j++) { $nafW = $repr[$j]; if ($nafW == $i) { $b = $b->mixedAdd($doubles["points"][$j]); } else if($nafW == -$i) { $b = $b->mixedAdd($doubles["points"][$j]->neg()); } } $a = $a->add($b); } return $a->toP(); } public function _wnafMul($p, $k) { $w = 4; //Precompute window $nafPoints = $p->_getNAFPoints($w); $w = $nafPoints["wnd"]; $wnd = $nafPoints["points"]; //Get NAF form $naf = Utils::getNAF($k, $w); //Add `this`*(N+1) for every w-NAF index $acc = $this->jpoint(null, null, null); for($i = count($naf) - 1; $i >= 0; $i--) { //Count zeros for($k = 0; $i >= 0 && $naf[$i] == 0; $i--) $k++; if($i >= 0) $k++; $acc = $acc->dblp($k); if($i < 0) break; $z = $naf[$i]; assert($z != 0); if( $p->type == "affine" ) { //J +- P if( $z > 0 ) $acc = $acc->mixedAdd($wnd[($z - 1) >> 1]); else $acc = $acc->mixedAdd($wnd[(-$z - 1) >> 1]->neg()); } else { //J +- J if( $z > 0 ) $acc = $acc->add($wnd[($z - 1) >> 1]); else $acc = $acc->add($wnd[(-$z - 1) >> 1]->neg()); } } return $p->type == "affine" ? $acc->toP() : $acc; } public function _wnafMulAdd($defW, $points, $coeffs, $len, $jacobianResult = false) { $wndWidth = &$this->_wnafT1; $wnd = &$this->_wnafT2; $naf = &$this->_wnafT3; //Fill all arrays $max = 0; for($i = 0; $i < $len; $i++) { $p = $points[$i]; $nafPoints = $p->_getNAFPoints($defW); $wndWidth[$i] = $nafPoints["wnd"]; $wnd[$i] = $nafPoints["points"]; } //Comb all window NAFs for($i = $len - 1; $i >= 1; $i -= 2) { $a = $i - 1; $b = $i; if( $wndWidth[$a] != 1 || $wndWidth[$b] != 1 ) { $naf[$a] = Utils::getNAF($coeffs[$a], $wndWidth[$a]); $naf[$b] = Utils::getNAF($coeffs[$b], $wndWidth[$b]); $max = max(count($naf[$a]), $max); $max = max(count($naf[$b]), $max); continue; } $comb = array( $points[$a], /* 1 */ null, /* 3 */ null, /* 5 */ $points[$b] /* 7 */ ); //Try to avoid Projective points, if possible if( $points[$a]->y->cmp($points[$b]->y) == 0 ) { $comb[1] = $points[$a]->add($points[$b]); $comb[2] = $points[$a]->toJ()->mixedAdd($points[$b]->neg()); } elseif( $points[$a]->y->cmp($points[$b]->y->redNeg()) == 0 ) { $comb[1] = $points[$a]->toJ()->mixedAdd($points[$b]); $comb[2] = $points[$a]->add($points[$b]->neg()); } else { $comb[1] = $points[$a]->toJ()->mixedAdd($points[$b]); $comb[2] = $points[$a]->toJ()->mixedAdd($points[$b]->neg()); } $index = array( -3, /* -1 -1 */ -1, /* -1 0 */ -5, /* -1 1 */ -7, /* 0 -1 */ 0, /* 0 0 */ 7, /* 0 1 */ 5, /* 1 -1 */ 1, /* 1 0 */ 3 /* 1 1 */ ); $jsf = Utils::getJSF($coeffs[$a], $coeffs[$b]); $max = max(count($jsf[0]), $max); if ($max > 0) { $naf[$a] = array_fill(0, $max, 0); $naf[$b] = array_fill(0, $max, 0); } else { $naf[$a] = []; $naf[$b] = []; } for($j = 0; $j < $max; $j++) { $ja = isset($jsf[0][$j]) ? $jsf[0][$j] : 0; $jb = isset($jsf[1][$j]) ? $jsf[1][$j] : 0; $naf[$a][$j] = $index[($ja + 1) * 3 + ($jb + 1)]; $naf[$b][$j] = 0; $wnd[$a] = $comb; } } $acc = $this->jpoint(null, null, null); $tmp = &$this->_wnafT4; for($i = $max; $i >= 0; $i--) { $k = 0; while($i >= 0) { $zero = true; for($j = 0; $j < $len; $j++) { $tmp[$j] = isset($naf[$j][$i]) ? $naf[$j][$i] : 0; if( $tmp[$j] != 0 ) $zero = false; } if( !$zero ) break; $k++; $i--; } if( $i >=0 ) $k++; $acc = $acc->dblp($k); if( $i < 0 ) break; for($j = 0; $j < $len; $j++) { $z = $tmp[$j]; $p = null; if( $z == 0 ) continue; elseif( $z > 0 ) $p = $wnd[$j][($z - 1) >> 1]; elseif( $z < 0 ) $p = $wnd[$j][(-$z - 1) >> 1]->neg(); if( $p->type == "affine" ) $acc = $acc->mixedAdd($p); else $acc = $acc->add($p); } } //Zeroify references for($i = 0; $i < $len; $i++) $wnd[$i] = null; if( $jacobianResult ) return $acc; else return $acc->toP(); } public function decodePoint($bytes, $enc = false) { $bytes = Utils::toArray($bytes, $enc); $len = $this->p->byteLength(); $count = count($bytes); //uncompressed, hybrid-odd, hybrid-even if(($bytes[0] == 0x04 || $bytes[0] == 0x06 || $bytes[0] == 0x07) && ($count - 1) == (2 * $len) ) { if( $bytes[0] == 0x06 ) assert($bytes[$count - 1] % 2 == 0); elseif( $bytes[0] == 0x07 ) assert($bytes[$count - 1] % 2 == 1); return $this->point(array_slice($bytes, 1, $len), array_slice($bytes, 1 + $len, $len)); } if( ($bytes[0] == 0x02 || $bytes[0] == 0x03) && ($count - 1) == $len ) return $this->pointFromX(array_slice($bytes, 1, $len), $bytes[0] == 0x03); throw new Exception("Unknown point format"); } } ?>
php
MIT
97685bc041bc0df2bea5226e92a7bf07a7cf14db
2026-01-05T05:11:27.721791Z
false
giekaton/php-metamask-user-login
https://github.com/giekaton/php-metamask-user-login/blob/97685bc041bc0df2bea5226e92a7bf07a7cf14db/backend/lib/Elliptic/Curve/MontCurve.php
backend/lib/Elliptic/Curve/MontCurve.php
<?php namespace Elliptic\Curve; require_once "MontCurve/Point.php"; use Elliptic\Curve\MontCurve\Point; use Elliptic\Utils; use BN\BN; class MontCurve extends BaseCurve { public $a; public $b; public $i4; public $a24; function __construct($conf) { parent::__construct("mont", $conf); $this->a = (new BN($conf["a"], 16))->toRed($this->red); $this->b = (new BN($conf["b"], 16))->toRed($this->red); $this->i4 = (new BN(4))->toRed($this->red)->redInvm(); $this->a24 = $this->i4->redMul($this->a->redAdd($this->two)); } public function validate($point) { $x = $point->normalize()->x; $x2 = $x->redSqr(); $rhs = $x2->redMul($x)->redAdd($x2->redMul($this->a))->redAdd($x); $y = $rhs->redSqr(); return $y->redSqr()->cmp($rhs) ===0; } public function decodePoint($bytes, $enc = false) { return $this->point(Utils::toArray($bytes, $enc), 1); } public function point($x, $z) { return new Point($this, $x, $z); } public function pointFromJSON($obj) { return Point::fromJSON($this, $obj); } } ?>
php
MIT
97685bc041bc0df2bea5226e92a7bf07a7cf14db
2026-01-05T05:11:27.721791Z
false
giekaton/php-metamask-user-login
https://github.com/giekaton/php-metamask-user-login/blob/97685bc041bc0df2bea5226e92a7bf07a7cf14db/backend/lib/Elliptic/Curve/EdwardsCurve/Point.php
backend/lib/Elliptic/Curve/EdwardsCurve/Point.php
<?php namespace Elliptic\Curve\EdwardsCurve; use BN\BN; class Point extends \Elliptic\Curve\BaseCurve\Point { public $x; public $y; public $z; public $t; public $zOne; function __construct($curve, $x = null, $y = null, $z = null, $t = null) { parent::__construct($curve, 'projective'); if ($x == null && $y == null && $z == null) { $this->x = $this->curve->zero; $this->y = $this->curve->one; $this->z = $this->curve->one; $this->t = $this->curve->zero; $this->zOne = true; } else { $this->x = new BN($x, 16); $this->y = new BN($y, 16); $this->z = $z ? new BN($z, 16) : $this->curve->one; $this->t = $t ? new BN($t, 16) : null; if (!$this->x->red) $this->x = $this->x->toRed($this->curve->red); if (!$this->y->red) $this->y = $this->y->toRed($this->curve->red); if (!$this->z->red) $this->z = $this->z->toRed($this->curve->red); if ($this->t && !$this->t->red) $this->t = $this->t->toRed($this->curve->red); $this->zOne = $this->z == $this->curve->one; // Use extended coordinates if ($this->curve->extended && !$this->t) { $this->t = $this->x->redMul($this->y); if (!$this->zOne) $this->t = $this->t->redMul($this->z->redInvm()); } } } public static function fromJSON($curve, $obj) { return new Point($curve, isset($obj[0]) ? $obj[0] : null, isset($obj[1]) ? $obj[1] : null, isset($obj[2]) ? $obj[2] : null ); } public function inspect() { if ($this->isInfinity()) return '<EC Point Infinity>'; return '<EC Point x: ' . $this->x->fromRed()->toString(16, 2) . ' y: ' . $this->y->fromRed()->toString(16, 2) . ' z: ' . $this->z->fromRed()->toString(16, 2) . '>'; } public function isInfinity() { // XXX This code assumes that zero is always zero in red return $this->x->cmpn(0) == 0 && $this->y->cmp($this->z) == 0; } public function _extDbl() { // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html // #doubling-dbl-2008-hwcd // 4M + 4S // A = X1^2 $a = $this->x->redSqr(); // B = Y1^2 $b = $this->y->redSqr(); // C = 2 * Z1^2 $c = $this->z->redSqr(); $c = $c->redIAdd($c); // D = a * A $d = $this->curve->_mulA($a); // E = (X1 + Y1)^2 - A - B $e = $this->x->redAdd($this->y)->redSqr()->redISub($a)->redISub($b); // G = D + B $g = $d->redAdd($b); // F = G - C $f = $g->redSub($c); // H = D - B $h = $d->redSub($b); // X3 = E * F $nx = $e->redMul($f); // Y3 = G * H $ny = $g->redMul($h); // T3 = E * H $nt = $e->redMul($h); // Z3 = F * G $nz = $f->redMul($g); return $this->curve->point($nx, $ny, $nz, $nt); } public function _projDbl() { // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html // #doubling-dbl-2008-bbjlp // #doubling-dbl-2007-bl // and others // Generally 3M + 4S or 2M + 4S // B = (X1 + Y1)^2 $b = $this->x->redAdd($this->y)->redSqr(); // C = X1^2 $c = $this->x->redSqr(); // D = Y1^2 $d = $this->y->redSqr(); if ($this->curve->twisted) { // E = a * C $e = $this->curve->_mulA($c); // F = E + D $f = $e->redAdd($d); if ($this->zOne) { // X3 = (B - C - D) * (F - 2) $nx = $b->redSub($c)->redSub($d)->redMul($f->redSub($this->curve->two)); // Y3 = F * (E - D) $ny = $f->redMul($e->redSub($d)); // Z3 = F^2 - 2 * F $nz = $f->redSqr()->redSub($f)->redSub($f); } else { // H = Z1^2 $h = $this->z->redSqr(); // J = F - 2 * H $j = $f->redSub($h)->redISub($h); // X3 = (B-C-D)*J $nx = $b->redSub($c)->redISub($d)->redMul($j); // Y3 = F * (E - D) $ny = $f->redMul($e->redSub($d)); // Z3 = F * J $nz = $f->redMul($j); } } else { // E = C + D $e = $c->redAdd($d); // H = (c * Z1)^2 $h = $this->curve->_mulC($this->c->redMul($this->z))->redSqr(); // J = E - 2 * H $j = $e->redSub($h)->redSub($h); // X3 = c * (B - E) * J $nx = $this->curve->_mulC($b->redISub($e))->redMul($j); // Y3 = c * E * (C - D) $ny = $this->curve->_mulC($e)->redMul($c->redISub($d)); // Z3 = E * J $nz = $e->redMul($j); } return $this->curve->point($nx, $ny, $nz); } public function dbl() { if ($this->isInfinity()) return $this; // Double in extended coordinates if ($this->curve->extended) return $this->_extDbl(); else return $this->_projDbl(); } public function _extAdd($p) { // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html // #addition-add-2008-hwcd-3 // 8M // A = (Y1 - X1) * (Y2 - X2) $a = $this->y->redSub($this->x)->redMul($p->y->redSub($p->x)); // B = (Y1 + X1) * (Y2 + X2) $b = $this->y->redAdd($this->x)->redMul($p->y->redAdd($p->x)); // C = T1 * k * T2 $c = $this->t->redMul($this->curve->dd)->redMul($p->t); // D = Z1 * 2 * Z2 $d = $this->z->redMul($p->z->redAdd($p->z)); // E = B - A $e = $b->redSub($a); // F = D - C $f = $d->redSub($c); // G = D + C $g = $d->redAdd($c); // H = B + A $h = $b->redAdd($a); // X3 = E * F $nx = $e->redMul($f); // Y3 = G * H $ny = $g->redMul($h); // T3 = E * H $nt = $e->redMul($h); // Z3 = F * G $nz = $f->redMul($g); return $this->curve->point($nx, $ny, $nz, $nt); } public function _projAdd($p) { // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html // #addition-add-2008-bbjlp // #addition-add-2007-bl // 10M + 1S // A = Z1 * Z2 $a = $this->z->redMul($p->z); // B = A^2 $b = $a->redSqr(); // C = X1 * X2 $c = $this->x->redMul($p->x); // D = Y1 * Y2 $d = $this->y->redMul($p->y); // E = d * C * D $e = $this->curve->d->redMul($c)->redMul($d); // F = B - E $f = $b->redSub($e); // G = B + E $g = $b->redAdd($e); // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D) $tmp = $this->x->redAdd($this->y)->redMul($p->x->redAdd($p->y))->redISub($c)->redISub($d); $nx = $a->redMul($f)->redMul($tmp); if ($this->curve->twisted) { // Y3 = A * G * (D - a * C) $ny = $a->redMul($g)->redMul($d->redSub($this->curve->_mulA($c))); // Z3 = F * G $nz = $f->redMul($g); } else { // Y3 = A * G * (D - C) $ny = $a->redMul($g)->redMul($d->redSub($c)); // Z3 = c * F * G $nz = $this->curve->_mulC($f)->redMul($g); } return $this->curve->point($nx, $ny, $nz); } public function add($p) { if ($this->isInfinity()) return $p; if ($p->isInfinity()) return $this; if ($this->curve->extended) return $this->_extAdd($p); else return $this->_projAdd($p); } public function mul($k) { if ($this->_hasDoubles($k)) return $this->curve->_fixedNafMul($this, $k); else return $this->curve->_wnafMul($this, $k); } public function mulAdd($k1, $p, $k2) { return $this->curve->_wnafMulAdd(1, [ $this, $p ], [ $k1, $k2 ], 2, false); } public function jmulAdd($k1, $p, $k2) { return $this->curve->_wnafMulAdd(1, [ $this, $p ], [ $k1, $k2 ], 2, true); } public function normalize() { if ($this->zOne) return $this; // Normalize coordinates $zi = $this->z->redInvm(); $this->x = $this->x->redMul($zi); $this->y = $this->y->redMul($zi); if ($this->t) $this->t = $this->t->redMul($zi); $this->z = $this->curve->one; $this->zOne = true; return $this; } public function neg() { return $this->curve->point($this->x->redNeg(), $this->y, $this->z, ($this->t != null) ? $this->t->redNeg() : null); } public function getX() { $this->normalize(); return $this->x->fromRed(); } public function getY() { $this->normalize(); return $this->y->fromRed(); } public function eq($other) { return $this == $other || $this->getX()->cmp($other->getX()) == 0 && $this->getY()->cmp($other->getY()) == 0; } public function eqXToP($x) { $rx = $x->toRed($this->curve->red)->redMul($this->z); if ($this->x->cmp($rx) == 0) return true; $xc = $x->_clone(); $t = $this->curve->redN->redMul($this->z); for (;;) { $xc->iadd($this->curve->n); if ($xc->cmp($this->curve->p) >= 0) return false; $rx->redIAdd($t); if ($this->x->cmp($rx) == 0) return true; } return false; } // Compatibility with BaseCurve public function toP() { return $this->normalize(); } public function mixedAdd($p) { return $this->add($p); } }
php
MIT
97685bc041bc0df2bea5226e92a7bf07a7cf14db
2026-01-05T05:11:27.721791Z
false
giekaton/php-metamask-user-login
https://github.com/giekaton/php-metamask-user-login/blob/97685bc041bc0df2bea5226e92a7bf07a7cf14db/backend/lib/Elliptic/Curve/ShortCurve/Point.php
backend/lib/Elliptic/Curve/ShortCurve/Point.php
<?php namespace Elliptic\Curve\ShortCurve; use JsonSerializable; use BN\BN; class Point extends \Elliptic\Curve\BaseCurve\Point implements JsonSerializable { public $x; public $y; public $inf; function __construct($curve, $x, $y, $isRed) { parent::__construct($curve, 'affine'); if( $x == null && $y == null ) { $this->x = null; $this->y = null; $this->inf = true; } else { $this->x = new BN($x, 16); $this->y = new BN($y, 16); // Force redgomery representation when loading from JSON if( $isRed ) { $this->x->forceRed($this->curve->red); $this->y->forceRed($this->curve->red); } if( !$this->x->red ) $this->x = $this->x->toRed($this->curve->red); if( !$this->y->red ) $this->y = $this->y->toRed($this->curve->red); $this->inf = false; } } public function _getBeta() { if( !isset($this->curve->endo) ) return null; if( isset($this->precomputed) && isset($this->precomputed["beta"]) ) return $this->precomputed["beta"]; $beta = $this->curve->point($this->x->redMul($this->curve->endo["beta"]), $this->y); if( isset($this->precomputed) ) { $endoMul = function($p) { return $this->curve->point($p->x->redMul($this->curve->endo["beta"]), $p->y); }; $beta->precomputed = array( "beta" => null, "naf" => null, "doubles" => null ); if( isset($this->precomputed["naf"]) ) { $beta->precomputed["naf"] = array( "wnd" => $this->precomputed["naf"]["wnd"], "points" => array_map($endoMul, $this->precomputed["naf"]["points"]) ); } if( isset($this->precomputed["doubles"]) ) { $beta->precomputed["doubles"] = array( "step" => $this->precomputed["doubles"]["step"], "points" => array_map($endoMul, $this->precomputed["doubles"]["points"]) ); } $this->precomputed["beta"] = $beta; } return $beta; } //toJSON() public function jsonSerialize() { $res = array($this->x, $this->y); if( !isset($this->precomputed) ) return $res; $pre = array(); $addPre = false; if( isset($this->precomputed["doubles"]) ) { $pre["doubles"] = array( "step" => $this->precomputed["doubles"]["step"], "points" => array_slice($this->precomputed["doubles"]["points"], 1) ); $addPre = true; } if( isset($this->precomputed["naf"]) ) { $pre["naf"] = array( "naf" => $this->precomputed["naf"]["wnd"], "points" => array_slice($this->precomputed["naf"]["points"], 1) ); $addPre = true; } if( $addPre ) array_push($res, $pre); return $res; } public static function fromJSON($curve, $obj, $red) { if( is_string($obj) ) $obj = json_decode($obj); $point = $curve->point($obj[0], $obj[1], $red); if( count($obj) === 2 ) return $point; $pre = $obj[2]; $point->precomputed = array("beta" => null); $obj2point = function($obj) use ($curve, $red) { return $curve->point($obj[0], $obj[1], $red); }; if( isset($pre["doubles"]) ) { $tmp = array_map($obj2point, $pre["doubles"]["points"]); array_unshift($tmp, $point); $point->precomputed["doubles"] = array( "step" => $pre["doubles"]["step"], "points" => $tmp ); } if( isset($pre["naf"]) ) { $tmp = array_map($obj2point, $pre["naf"]["points"]); array_unshift($tmp, $point); $point->precomputed["naf"] = array( "wnd" => $pre["naf"]["wnd"], "points" => $tmp ); } return $point; } public function inspect() { if( $this->isInfinity() ) return "<EC Point Infinity>"; return "<EC Point x: " . $this->x->fromRed()->toString(16, 2) . " y: " . $this->y->fromRed()->toString(16, 2) . ">"; } public function __debugInfo() { return [ "EC Point" => ($this->isInfinity() ? "Infinity" : [ "x" => $this->x->fromRed()->toString(16, 2), "y" => $this->y->fromRed()->toString(16, 2) ]) ]; } public function isInfinity() { return $this->inf; } public function add($point) { // O + P = P if( $this->inf ) return $point; // P + O = P if( $point->inf ) return $this; // P + P = 2P if( $this->eq($point) ) return $this->dbl(); // P + (-P) = O if( $this->neg()->eq($point) ) return $this->curve->point(null, null); // P + Q = O if( $this->x->cmp($point->x) === 0 ) return $this->curve->point(null, null); $c = $this->y->redSub($point->y); if( ! $c->isZero() ) $c = $c->redMul($this->x->redSub($point->x)->redInvm()); $nx = $c->redSqr()->redISub($this->x)->redISub($point->x); $ny = $c->redMul($this->x->redSub($nx))->redISub($this->y); return $this->curve->point($nx, $ny); } public function dbl() { if( $this->inf ) return $this; // 2P = 0 $ys1 = $this->y->redAdd($this->y); if( $ys1->isZero() ) return $this->curve->point(null, null); $x2 = $this->x->redSqr(); $dyinv = $ys1->redInvm(); $c = $x2->redAdd($x2)->redIAdd($x2)->redIAdd($this->curve->a)->redMul($dyinv); $nx = $c->redSqr()->redISub($this->x->redAdd($this->x)); $ny = $c->redMul($this->x->redSub($nx))->redISub($this->y); return $this->curve->point($nx, $ny); } public function getX() { return $this->x->fromRed(); } public function getY() { return $this->y->fromRed(); } public function mul($k) { $k = new BN($k, 16); if( $this->_hasDoubles($k) ) return $this->curve->_fixedNafMul($this, $k); elseif( isset($this->curve->endo) ) return $this->curve->_endoWnafMulAdd(array($this), array($k)); return $this->curve->_wnafMul($this, $k); } public function mulAdd($k1, $p2, $k2, $j = false) { $points = array($this, $p2); $coeffs = array($k1, $k2); if( isset($this->curve->endo) ) return $this->curve->_endoWnafMulAdd($points, $coeffs, $j); return $this->curve->_wnafMulAdd(1, $points, $coeffs, 2, $j); } public function jmulAdd($k1, $p2, $k2) { return $this->mulAdd($k1, $p2, $k2, true); } public function eq($point) { return ( $this === $point || $this->inf === $point->inf && ($this->inf || $this->x->cmp($point->x) === 0 && $this->y->cmp($point->y) === 0) ); } public function neg($precompute = false) { if( $this->inf ) return $this; $res = $this->curve->point($this->x, $this->y->redNeg()); if( $precompute && isset($this->precomputed) ) { $res->precomputed = array(); $pre = $this->precomputed; $negate = function($point) { return $point->neg(); }; if( isset($pre["naf"]) ) { $res->precomputed["naf"] = array( "wnd" => $pre["naf"]["wnd"], "points" => array_map($negate, $pre["naf"]["points"]) ); } if( isset($pre["doubles"]) ) { $res->precomputed["doubles"] = array( "step" => $pre["doubles"]["step"], "points" => array_map($negate, $pre["doubles"]["points"]) ); } } return $res; } public function toJ() { if( $this->inf ) return $this->curve->jpoint(null, null, null); return $this->curve->jpoint($this->x, $this->y, $this->curve->one); } } ?>
php
MIT
97685bc041bc0df2bea5226e92a7bf07a7cf14db
2026-01-05T05:11:27.721791Z
false
giekaton/php-metamask-user-login
https://github.com/giekaton/php-metamask-user-login/blob/97685bc041bc0df2bea5226e92a7bf07a7cf14db/backend/lib/Elliptic/Curve/ShortCurve/JPoint.php
backend/lib/Elliptic/Curve/ShortCurve/JPoint.php
<?php namespace Elliptic\Curve\ShortCurve; use BN\BN; class JPoint extends \Elliptic\Curve\BaseCurve\Point { public $x; public $y; public $z; public $zOne; function __construct($curve, $x, $y, $z) { parent::__construct($curve, "jacobian"); if( $x == null && $y == null && $z == null ) { $this->x = $this->curve->one; $this->y = $this->curve->one; $this->z = new BN(0); } else { $this->x = new BN($x, 16); $this->y = new BN($y, 16); $this->z = new BN($z, 16); } if( !$this->x->red ) $this->x = $this->x->toRed($this->curve->red); if( !$this->y->red ) $this->y = $this->y->toRed($this->curve->red); if( !$this->z->red ) $this->z = $this->z->toRed($this->curve->red); return $this->zOne = $this->z == $this->curve->one; } public function toP() { if( $this->isInfinity() ) return $this->curve->point(null, null); $zinv = $this->z->redInvm(); $zinv2 = $zinv->redSqr(); $ax = $this->x->redMul($zinv2); $ay = $this->y->redMul($zinv2)->redMul($zinv); return $this->curve->point($ax, $ay); } public function neg() { return $this->curve->jpoint($this->x, $this->y->redNeg(), $this->z); } public function add($p) { // O + P = P if( $this->isInfinity() ) return $p; // P + O = P if( $p->isInfinity() ) return $this; // 12M + 4S + 7A $pz2 = $p->z->redSqr(); $z2 = $this->z->redSqr(); $u1 = $this->x->redMul($pz2); $u2 = $p->x->redMul($z2); $s1 = $this->y->redMul($pz2->redMul($p->z)); $s2 = $p->y->redMul($z2->redMul($this->z)); $h = $u1->redSub($u2); $r = $s1->redSub($s2); if( $h->isZero() ) { if( ! $r->isZero() ) return $this->curve->jpoint(null, null, null); else return $this->dbl(); } $h2 = $h->redSqr(); $h3 = $h2->redMul($h); $v = $u1->redMul($h2); $nx = $r->redSqr()->redIAdd($h3)->redISub($v)->redISub($v); $ny = $r->redMul($v->redISub($nx))->redISub($s1->redMul($h3)); $nz = $this->z->redMul($p->z)->redMul($h); return $this->curve->jpoint($nx, $ny, $nz); } public function mixedAdd($p) { // O + P = P if( $this->isInfinity() ) return $p->toJ(); // P + O = P if( $p->isInfinity() ) return $this; // 8M + 3S + 7A $z2 = $this->z->redSqr(); $u1 = $this->x; $u2 = $p->x->redMul($z2); $s1 = $this->y; $s2 = $p->y->redMul($z2)->redMul($this->z); $h = $u1->redSub($u2); $r = $s1->redSub($s2); if( $h->isZero() ) { if( ! $r->isZero() ) return $this->curve->jpoint(null, null, null); else return $this->dbl(); } $h2 = $h->redSqr(); $h3 = $h2->redMul($h); $v = $u1->redMul($h2); $nx = $r->redSqr()->redIAdd($h3)->redISub($v)->redISub($v); $ny = $r->redMul($v->redISub($nx))->redISub($s1->redMul($h3)); $nz = $this->z->redMul($h); return $this->curve->jpoint($nx, $ny, $nz); } public function dblp($pow = null) { if( $pow == 0 || $this->isInfinity() ) return $this; if( $pow == null ) return $this->dbl(); if( $this->curve->zeroA || $this->curve->threeA ) { $r = $this; for($i = 0; $i < $pow; $i++) $r = $r->dbl(); return $r; } // 1M + 2S + 1A + N * (4S + 5M + 8A) // N = 1 => 6M + 6S + 9A $jx = $this->x; $jy = $this->y; $jz = $this->z; $jz4 = $jz->redSqr()->redSqr(); //Reuse results $jyd = $jy->redAdd($jy); for($i = 0; $i < $pow; $i++) { $jx2 = $jx->redSqr(); $jyd2 = $jyd->redSqr(); $jyd4 = $jyd2->redSqr(); $c = $jx2->redAdd($jx2)->redIAdd($jx2)->redIAdd($this->curve->a->redMul($jz4)); $t1 = $jx->redMul($jyd2); $nx = $c->redSqr()->redISub($t1->redAdd($t1)); $t2 = $t1->redISub($nx); $dny = $c->redMul($t2); $dny = $dny->redIAdd($dny)->redISub($jyd4); $nz = $jyd->redMul($jz); if( ($i + 1) < $pow) $jz4 = $jz4->redMul($jyd4); $jx = $nx; $jz = $nz; $jyd = $dny; } return $this->curve->jpoint($jx, $jyd->redMul($this->curve->tinv), $jz); } public function dbl() { if( $this->isInfinity() ) return $this; if( $this->curve->zeroA ) return $this->_zeroDbl(); elseif( $this->curve->threeA ) return $this->_threeDbl(); return $this->_dbl(); } private function _zOneDbl($withA) { $xx = $this->x->redSqr(); $yy = $this->y->redSqr(); $yyyy = $yy->redSqr(); // S = 2 * ((X1 + YY)^2 - XX - YYYY) $s = $this->x->redAdd($yy)->redSqr()->redISub($xx)->redISub($yyyy); $s = $s->redIAdd($s); // M = 3 * XX + a; a = 0 $m = null; if( $withA ) $m = $xx->redAdd($xx)->redIAdd($xx)->redIAdd($this->curve->a); else $m = $xx->redAdd($xx)->redIAdd($xx); // T = M ^ 2 - 2*S $t = $m->redSqr()->redISub($s)->redISub($s); $yyyy8 = $yyyy->redIAdd($yyyy); $yyyy8 = $yyyy8->redIAdd($yyyy8); $yyyy8 = $yyyy8->redIAdd($yyyy8); $ny = $m->redMul($s->redISub($t))->redISub($yyyy8); $nz = $this->y->redAdd($this->y); return $this->curve->jpoint($t, $ny, $nz); } private function _zeroDbl() { // Z = 1 if( $this->zOne ) { // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html // #doubling-mdbl-2007-bl // 1M + 5S + 14A return $this->_zOneDbl(false); } // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html // #doubling-dbl-2009-l // 2M + 5S + 13A $a = $this->x->redSqr(); $b = $this->y->redSqr(); $c = $b->redSqr(); // D = 2 * ((X1 + B)^2 - A - C) $d = $this->x->redAdd($b)->redSqr()->redISub($a)->redISub($c); $d = $d->redIAdd($d); $e = $a->redAdd($a)->redIAdd($a); $f = $e->redSqr(); $c8 = $c->redIAdd($c); $c8 = $c8->redIAdd($c8); $c8 = $c8->redIAdd($c8); // X3 = F - 2 * D $nx = $f->redISub($d)->redISub($d); // Y3 = E * (D - X3) - 8 * C $ny = $e->redMul($d->redISub($nx))->redISub($c8); // Z3 = 2 * Y1 * Z1 $nz = $this->y->redMul($this->z); $nz = $nz->redIAdd($nz); return $this->curve->jpoint($nx, $ny, $nz); } private function _threeDbl() { if( $this->zOne ) { // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html // #doubling-mdbl-2007-bl // 1M + 5S + 15A // XX = X1^2 $xx = $this->x->redSqr(); // YY = Y1^2 $yy = $this->y->redSqr(); // YYYY = YY^2 $yyyy = $yy->redSqr(); // S = 2 * ((X1 + YY)^2 - XX - YYYY) $s = $this->x->redAdd($yy)->redSqr()->redISub($xx)->redISub($yyyy); $s = $s->redIAdd($s); // M = 3 * XX + a $m = $xx->redAdd($xx)->redIAdd($xx)->redIAdd($this->curve->a); // T = M^2 - 2 * S $t = $m->redSqr()->redISub($s)->redISub($s); // X3 = T $nx = $t; // Y3 = M * (S - T) - 8 * YYYY $yyyy8 = $yyyy->redIAdd($yyyy); $yyyy8 = $yyyy8->redIAdd($yyyy8); $yyyy8 = $yyyy8->redIAdd($yyyy8); $ny = $m->redMul($s->redISub($t))->redISub($yyyy8); // Z3 = 2 * Y1 $nz = $this->y->redAdd($this->y); } else { // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b // 3M + 5S // delta = Z1^2 $delta = $this->z->redSqr(); // gamma = Y1^2 $gamma = $this->y->redSqr(); // beta = X1 * gamma $beta = $this->x->redMul($gamma); // alpha = 3 * (X1 - delta) * (X1 + delta) $alpha = $this->x->redSub($delta)->redMul($this->x->redAdd($delta)); $alpha = $alpha->redAdd($alpha)->redIAdd($alpha); // X3 = alpha^2 - 8 * beta $beta4 = $beta->redIAdd($beta); $beta4 = $beta4->redIAdd($beta4); $beta8 = $beta4->redAdd($beta4); $nx = $alpha->redSqr()->redISub($beta8); // Z3 = (Y1 + Z1)^2 - gamma - delta $nz = $this->y->redAdd($this->z)->redSqr()->redISub($gamma)->redISub($delta); $ggamma8 = $gamma->redSqr(); $ggamma8 = $ggamma8->redIAdd($ggamma8); $ggamma8 = $ggamma8->redIAdd($ggamma8); $ggamma8 = $ggamma8->redIAdd($ggamma8); // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2 $ny = $alpha->redMul($beta4->redISub($nx))->redISub($ggamma8); } return $this->curve->jpoint($nx, $ny, $nz); } private function _dbl() { // 4M + 6S + 10A $jx = $this->x; $jy = $this->y; $jz = $this->z; $jz4 = $jz->redSqr()->redSqr(); $jx2 = $jx->redSqr(); $jy2 = $jy->redSqr(); $c = $jx2->redAdd($jx2)->redIAdd($jx2)->redIAdd($this->curve->a->redMul($jz4)); $jxd4 = $jx->redAdd($jx); $jxd4 = $jxd4->redIAdd($jxd4); $t1 = $jxd4->redMul($jy2); $nx = $c->redSqr()->redISub($t1->redAdd($t1)); $t2 = $t1->redISub($nx); $jyd8 = $jy2->redSqr(); $jyd8 = $jyd8->redIAdd($jyd8); $jyd8 = $jyd8->redIAdd($jyd8); $jyd8 = $jyd8->redIAdd($jyd8); $ny = $c->redMul($t2)->redISub($jyd8); $nz = $jy->redAdd($jy)->redMul($jz); return $this->curve->jpoint($nx, $ny, $nz); } public function trpl() { if( !$this->curve->zeroA ) return $this->dbl()->add($this); // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl // 5M + 10S + ... $xx = $this->x->redSqr(); $yy = $this->y->redSqr(); $zz = $this->z->redSqr(); // YYYY = YY^2 $yyyy = $yy->redSqr(); // M = 3 * XX + a * ZZ2; a = 0 $m = $xx->redAdd($xx)->redIAdd($xx); // MM = M^2 $mm = $m->redSqr(); // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM $e = $this->x->redAdd($yy)->redSqr()->redISub($xx)->redISub($yyyy); $e = $e->redIAdd($e); $e = $e->redAdd($e)->redIAdd($e); $e = $e->redISub($mm); $ee = $e->redSqr(); // T = 16*YYYY $t = $yyyy->redIAdd($yyyy); $t = $t->redIAdd($t); $t = $t->redIAdd($t); $t = $t->redIAdd($t); // U = (M + E)^2 - MM - EE - T $u = $m->redAdd($e)->redSqr()->redISub($mm)->redISub($ee)->redISub($t); $yyu4 = $yy->redMul($u); $yyu4 = $yyu4->redIAdd($yyu4); $yyu4 = $yyu4->redIAdd($yyu4); // X3 = 4 * (X1 * EE - 4 * YY * U) $nx = $this->x->redMul($ee)->redISub($yyu4); $nx = $nx->redIAdd($nx); $nx = $nx->redIAdd($nx); // Y3 = 8 * Y1 * (U * (T - U) - E * EE) $ny = $this->y->redMul($u->redMul($t->redISub($u))->redISub($e->redMul($ee))); $ny = $ny->redIAdd($ny); $ny = $ny->redIAdd($ny); $ny = $ny->redIAdd($ny); // Z3 = (Z1 + E)^2 - ZZ - EE $nz = $this->z->redAdd($e)->redSqr()->redISub($zz)->redISub($ee); return $this->curve->jpoint($nx, $ny, $nz); } public function mul($k, $kbase) { return $this->curve->_wnafMul($this, new BN($k, $kbase)); } public function eq($p) { if( $p->type == "affine" ) return $this->eq($p->toJ()); if( $this == $p ) return true; // x1 * z2^2 == x2 * z1^2 $z2 = $this->z->redSqr(); $pz2 = $p->z->redSqr(); if( ! $this->x->redMul($pz2)->redISub($p->x->redMul($z2))->isZero() ) return false; // y1 * z2^3 == y2 * z1^3 $z3 = $z2->redMul($this->z); $pz3 = $pz2->redMul($p->z); return $this->y->redMul($pz3)->redISub($p->y->redMul($z3))->isZero(); } public function eqXToP($x) { $zs = $this->z->redSqr(); $rx = $x->toRed($this->curve->red)->redMul($zs); if( $this->x->cmp($rx) == 0 ) return true; $xc = $x->_clone(); $t = $this->curve->redN->redMul($zs); while(true) { $xc->iadd($this->curve->n); if( $xc->cmp($this->curve->p) >= 0 ) return false; $rx->redIAdd($t); if( $this->x->cmp($rx) == 0 ) return true; } } public function inspect() { if( $this->isInfinity() ) return "<EC JPoint Infinity>"; return "<EC JPoint x: " . $this->x->toString(16, 2) . " y: " . $this->y->toString(16, 2) . " z: " . $this->z->toString(16, 2) . ">"; } public function __debugInfo() { return [ "EC JPoint" => ($this->isInfinity() ? "Infinity" : [ "x" => $this->x->toString(16,2), "y" => $this->y->toString(16,2), "z" => $this->z->toString(16,2) ] ) ]; } public function isInfinity() { // XXX This code assumes that zero is always zero in red return $this->z->isZero(); } } ?>
php
MIT
97685bc041bc0df2bea5226e92a7bf07a7cf14db
2026-01-05T05:11:27.721791Z
false
giekaton/php-metamask-user-login
https://github.com/giekaton/php-metamask-user-login/blob/97685bc041bc0df2bea5226e92a7bf07a7cf14db/backend/lib/Elliptic/Curve/BaseCurve/Point.php
backend/lib/Elliptic/Curve/BaseCurve/Point.php
<?php namespace Elliptic\Curve\BaseCurve; use Elliptic\Utils; abstract class Point { public $curve; public $type; public $precomputed; function __construct($curve, $type) { $this->curve = $curve; $this->type = $type; $this->precomputed = null; } abstract public function eq($other); public function validate() { return $this->curve->validate($this); } public function encodeCompressed($enc) { return $this->encode($enc, true); } public function encode($enc, $compact = false) { return Utils::encode($this->_encode($compact), $enc); } protected function _encode($compact) { $len = $this->curve->p->byteLength(); $x = $this->getX()->toArray("be", $len); if( $compact ) { array_unshift($x, ($this->getY()->isEven() ? 0x02 : 0x03)); return $x; } return array_merge(array(0x04), $x, $this->getY()->toArray("be", $len)); } public function precompute($power = null) { if( isset($this->precomputed) ) return $this; $this->precomputed = array( "naf" => $this->_getNAFPoints(8), "doubles" => $this->_getDoubles(4, $power), "beta" => $this->_getBeta() ); return $this; } protected function _hasDoubles($k) { if( !isset($this->precomputed) || !isset($this->precomputed["doubles"]) ) return false; return count($this->precomputed["doubles"]["points"]) >= ceil(($k->bitLength() + 1) / $this->precomputed["doubles"]["step"]); } public function _getDoubles($step = null, $power = null) { if( isset($this->precomputed) && isset($this->precomputed["doubles"]) ) return $this->precomputed["doubles"]; $doubles = array( $this ); $acc = $this; for($i = 0; $i < $power; $i += $step) { for($j = 0; $j < $step; $j++) $acc = $acc->dbl(); array_push($doubles, $acc); } return array( "step" => $step, "points" => $doubles ); } public function _getNAFPoints($wnd) { if( isset($this->precomputed) && isset($this->precomputed["naf"]) ) return $this->precomputed["naf"]; $res = array( $this ); $max = (1 << $wnd) - 1; $dbl = $max === 1 ? null : $this->dbl(); for($i = 1; $i < $max; $i++) array_push($res, $res[$i - 1]->add($dbl)); return array( "wnd" => $wnd, "points" => $res ); } public function _getBeta() { return null; } public function dblp($k) { $r = $this; for($i = 0; $i < $k; $i++) $r = $r->dbl(); return $r; } } ?>
php
MIT
97685bc041bc0df2bea5226e92a7bf07a7cf14db
2026-01-05T05:11:27.721791Z
false
giekaton/php-metamask-user-login
https://github.com/giekaton/php-metamask-user-login/blob/97685bc041bc0df2bea5226e92a7bf07a7cf14db/backend/lib/Elliptic/Curve/MontCurve/Point.php
backend/lib/Elliptic/Curve/MontCurve/Point.php
<?php namespace Elliptic\Curve\MontCurve; use BN\BN; class Point extends \Elliptic\Curve\BaseCurve\Point { public $x; public $z; function __construct($curve, $x, $z) { parent::__construct($curve, "projective"); if( $x == null && $z == null ) { $this->x = $this->curve->one; $this->z = $this->curve->zero; } else { $this->x = new BN($x, 16); $this->z = new BN($z, 16); if( !$this->x->red ) $this->x = $this->x->toRed($this->curve->red); if( !$this->z->red ) $this->z = $this->z->toRed($this->curve->red); } } public function precompute($power = null) { // No-op } protected function _encode($compact) { return $this->getX()->toArray("be", $this->curve->p->byteLength()); } public static function fromJSON($curve, $obj) { return new Point($curve, $obj[0], isset($obj[1]) ? $obj[1] : $curve->one); } public function inspect() { if( $this->isInfinity() ) return "<EC Point Infinity>"; return "<EC Point x: " . $this->x->fromRed()->toString(16, 2) . " z: " . $this->z->fromRed()->toString(16, 2) . ">"; } public function isInfinity() { // XXX This code assumes that zero is always zero in red return $this->z->isZero(); } public function dbl() { // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 // 2M + 2S + 4A // A = X1 + Z1 $a = $this->x->redAdd($this->z); // AA = A^2 $aa = $a->redSqr(); // B = X1 - Z1 $b = $this->x->redSub($this->z); // BB = B^2 $bb = $b->redSqr(); // C = AA - BB $c = $aa->redSub($bb); // X3 = AA * BB $nx = $aa->redMul($bb); // Z3 = C * (BB + A24 * C) $nz = $c->redMul( $bb->redAdd($this->curve->a24->redMul($c)) ); return $this->curve->point($nx, $nz); } public function add($p) { throw new \Exception('Not supported on Montgomery curve'); } public function diffAdd($p, $diff) { // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 // 4M + 2S + 6A // A = X2 + Z2 $a = $this->x->redAdd($this->z); // B = X2 - Z2 $b = $this->x->redSub($this->z); // C = X3 + Z3 $c = $p->x->redAdd($p->z); // D = X3 - Z3 $d = $p->x->redSub($p->z); // DA = D * A $da = $d->redMul($a); // CB = C * B $cb = $c->redMul($b); // X5 = Z1 * (DA + CB)^2 $nx = $diff->z->redMul($da->redAdd($cb)->redSqr()); // Z5 = X1 * (DA - CB)^2 $nz = $diff->x->redMul($da->redSub($cb)->redSqr()); return $this->curve->point($nx, $nz); } public function mul($k) { $t = $k->_clone(); $a = $this; // (N / 2) * Q + Q $b = $this->curve->point(null, null); // (N / 2) * Q $c = $this; // Q $bits = array(); while( !$t->isZero() ) { // TODO: Maybe it is faster to use toString(2)? array_push($bits, $t->andln(1)); $t->iushrn(1); } for($i = count($bits) - 1; $i >= 0; $i--) { if( $bits[$i] === 0 ) { // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q $a = $a->diffAdd($b, $c); // N * Q = 2 * ((N / 2) * Q + Q)) $b = $b->dbl(); } else { // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q) $b = $a->diffAdd($b, $c); // N * Q + Q = 2 * ((N / 2) * Q + Q) $a = $a->dbl(); } } return $b; } public function eq($other) { return $this->getX()->cmp($other->getX()) === 0; } public function normalize() { $this->x = $this->x->redMul($this->z->redInvm()); $this->z = $this->curve->one; return $this; } public function getX() { $this->normalize(); return $this->x->fromRed(); } } ?>
php
MIT
97685bc041bc0df2bea5226e92a7bf07a7cf14db
2026-01-05T05:11:27.721791Z
false
dvaknheo/duckphp
https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/autoload.php
autoload.php
<?php require __DIR__.'/src/Core/AutoLoader.php'; spl_autoload_register([DuckPhp\Core\AutoLoader::class ,'DuckPhpSystemAutoLoader']);
php
MIT
16b1924f5d43911d9448af5b63ab27d20529a104
2026-01-05T05:11:36.735455Z
false
dvaknheo/duckphp
https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/DuckPhp.php
src/DuckPhp.php
<?php declare(strict_types=1); /** * DuckPhp * From this time, you never be alone~ */ //dvaknheo@github.com //OK,Lazy namespace DuckPhp; use DuckPhp\Component\Command; use DuckPhp\Component\DbManager; use DuckPhp\Component\ExtOptionsLoader; use DuckPhp\Component\RedisManager; use DuckPhp\Component\RouteHookCheckStatus; use DuckPhp\Component\RouteHookPathInfoCompat; use DuckPhp\Component\RouteHookResource; use DuckPhp\Component\RouteHookRewrite; use DuckPhp\Component\RouteHookRouteMap; use DuckPhp\Core\App; use DuckPhp\Core\Console; use DuckPhp\FastInstaller\FastInstaller; use DuckPhp\GlobalAdmin\GlobalAdmin; use DuckPhp\GlobalUser\GlobalUser; class DuckPhp extends App { protected $common_options = [ 'ext_options_file_enable' => true, 'ext_options_file' => 'config/DuckPhpApps.config.php', 'ext' => [ RouteHookCheckStatus::class => true, RouteHookRewrite::class => true, RouteHookRouteMap::class => true, RouteHookResource::class => true, //RouteHookPathInfoCompat::class => false, ], 'session_prefix' => null, 'table_prefix' => null, 'path_info_compact_enable' => false, 'class_admin' => '', 'class_user' => '', 'database_driver' => '', 'cli_command_with_app' => true, 'cli_command_with_common' => true, 'cli_command_with_fast_installer' => true, 'allow_require_ext_app' => true, //'install_need_database' => true, //'install_need_redis' => false, //* // 'path_config' => 'config', // 'database' => null, // 'database_driver' => '', // 'database_list' => null, // 'database_list_reload_by_setting' => true, // 'database_list_try_single' => true, // 'database_log_sql_query' => false, // 'database_log_sql_level' => 'debug', // 'database_class' => '', // 'redis' => null, // 'redis_list' => null, // 'redis_list_reload_by_setting' => true, // 'redis_list_try_single' => true, // 'controller_url_prefix' => '', // 'route_map_important' => [], // 'route_map' => [], // 'rewrite_map' => [], // 'path_info_compact_enable' => false, // 'path_info_compact_action_key' => '_r', // 'path_info_compact_class_key' => '', //*/ ]; protected function prepareComponents() { if ($this->options['ext_options_file_enable']) { ExtOptionsLoader::_()->loadExtOptions(static::class); } if ($this->options['cli_command_with_app']) { array_unshift($this->options['cli_command_classes'], static::class); } if ($this->options['cli_command_with_common']) { array_push($this->options['cli_command_classes'], Command::class); } if ($this->options['cli_command_with_fast_installer']) { array_push($this->options['cli_command_classes'], FastInstaller::class); } } protected function initComponents(array $options, object $context = null) { parent::initComponents($options, $context); $this->addPublicClassesInRoot([ DbManager::class, RedisManager::class, GlobalAdmin::class, GlobalUser::class, ]); if ($this->is_root) { DbManager::_()->init($this->options, $this); RedisManager::_()->init($this->options, $this); } else { if ($this->isLocalDatabase()) { $this->createLocalObject(DbManager::class); DbManager::_()->init($this->options, $this); } if ($this->isLocalRedis()) { $this->createLocalObject(RedisManager::class); RedisManager::_()->init($this->options, $this); } } if ($this->options['path_info_compact_enable'] ?? false) { RouteHookPathInfoCompat::_()->init($this->options, $this); } if ($this->options['class_admin']) { $class = $this->options['class_admin']; GlobalAdmin::_($class::_Z(static::Phase())); } if ($this->options['class_user']) { $class = $this->options['class_user']; GlobalUser::_($class::_Z(static::Phase())); } return $this; } protected function isLocalDatabase() { $flag = $this->options['local_database'] ?? false; if ($flag) { return true; } $driver = DbManager::_()->options['database_driver'] ?? ''; if ($this->options['database_driver'] && ($driver != $this->options['database_driver'])) { return true; } return false; } protected function isLocalRedis() { return ($this->options['local_redis'] ?? false) ? true : false; } }
php
MIT
16b1924f5d43911d9448af5b63ab27d20529a104
2026-01-05T05:11:36.735455Z
false
dvaknheo/duckphp
https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/DuckPhpAllInOne.php
src/DuckPhpAllInOne.php
<?php declare(strict_types=1); /** * DuckPhp * From this time, you never be alone~ */ //dvaknheo@github.com //OK,Lazy namespace DuckPhp; use DuckPhp\Helper\AppHelperTrait; use DuckPhp\Helper\BusinessHelperTrait; use DuckPhp\Helper\ControllerHelperTrait; use DuckPhp\Helper\ModelHelperTrait; class DuckPhpAllInOne extends DuckPhp { use ModelHelperTrait; use BusinessHelperTrait, ControllerHelperTrait, AppHelperTrait{ BusinessHelperTrait::Setting insteadof ControllerHelperTrait; BusinessHelperTrait::Config insteadof ControllerHelperTrait; BusinessHelperTrait::XpCall insteadof ControllerHelperTrait; BusinessHelperTrait::FireEvent insteadof ControllerHelperTrait; BusinessHelperTrait::OnEvent insteadof ControllerHelperTrait; BusinessHelperTrait::OnEvent insteadof AppHelperTrait; BusinessHelperTrait::FireEvent insteadof AppHelperTrait; BusinessHelperTrait::PathOfProject insteadof AppHelperTrait; BusinessHelperTrait::PathOfRuntime insteadof AppHelperTrait; ControllerHelperTrait::header insteadof AppHelperTrait; ControllerHelperTrait::setcookie insteadof AppHelperTrait; ControllerHelperTrait::exit insteadof AppHelperTrait; ControllerHelperTrait::AdminService insteadof BusinessHelperTrait; ControllerHelperTrait::UserService insteadof BusinessHelperTrait; } }
php
MIT
16b1924f5d43911d9448af5b63ab27d20529a104
2026-01-05T05:11:36.735455Z
false
dvaknheo/duckphp
https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Foundation/SimpleControllerTrait.php
src/Foundation/SimpleControllerTrait.php
<?php declare(strict_types=1); /** * DuckPhp * From this time, you never be alone~ */ namespace DuckPhp\Foundation; use DuckPhp\Component\PhaseProxy; use DuckPhp\Component\ZCallTrait; use DuckPhp\Core\PhaseContainer; use DuckPhp\Core\Route; trait SimpleControllerTrait { use ZCallTrait; public static function _($object = null) { $route = Route::_(); $postfix = $route->options['controller_class_postfix']; $class_base = $route->options['controller_class_base']; /* postfix_set,postfix_match base_set ,base_match , result Y Y Y Y => Y Y Y Y N => N Y Y N * => Y Y N * * => N N * Y Y => Y N * Y N => N N * N * => Y ------------ Y Y Y Y => Y Y Y Y N => N Y Y N Y => Y Y Y N N => Y Y N Y Y => N Y N Y N => N Y N N Y => N Y N N N => N N Y Y Y => Y N N Y Y => Y N Y Y N => N N N Y N => N N Y N Y => Y N Y N N => Y N N N Y => Y N N N N => Y //*/ $is_controller = false; if ($postfix) { if (substr(static::class, -strlen($postfix)) === $postfix) { if ($class_base) { if (\is_subclass_of(static::class, $class_base)) { $is_controller = true; } else { /** @phpstan-ignore-line */ $is_controller = false; } } else { $is_controller = true; } } else { $is_controller = false; } } else { if ($class_base) { if (\is_subclass_of(static::class, $class_base)) { $is_controller = true; } else { /** @phpstan-ignore-line */ $is_controller = false; } } else { $is_controller = true; } } if ($is_controller) { $class = $object ? get_class($object) :static::class ; if ($class !== static::class) { $route->options['controller_class_map'][static::class] = $class; } $object = (new \ReflectionClass($class))->newInstanceWithoutConstructor(); return $object; } $ret = PhaseContainer::GetObject(static::class, $object); return $ret; } /** * @return self */ public static function _Z($phase = null) { return PhaseProxy::CreatePhaseProxy($phase, static::class); } public static function OverrideParent() { $parent = get_parent_class(static::class); Route::_()->replaceController($parent, static::class); } }
php
MIT
16b1924f5d43911d9448af5b63ab27d20529a104
2026-01-05T05:11:36.735455Z
false
dvaknheo/duckphp
https://github.com/dvaknheo/duckphp/blob/16b1924f5d43911d9448af5b63ab27d20529a104/src/Foundation/Helper.php
src/Foundation/Helper.php
<?php declare(strict_types=1); /** * DuckPhp * From this time, you never be alone~ */ //dvaknheo@github.com //OK,Lazy namespace DuckPhp\Foundation; use DuckPhp\Helper\AppHelperTrait; use DuckPhp\Helper\BusinessHelperTrait; use DuckPhp\Helper\ControllerHelperTrait; use DuckPhp\Helper\ModelHelperTrait; class Helper { use ModelHelperTrait; use BusinessHelperTrait, ControllerHelperTrait, AppHelperTrait{ BusinessHelperTrait::Setting insteadof ControllerHelperTrait; BusinessHelperTrait::Config insteadof ControllerHelperTrait; BusinessHelperTrait::XpCall insteadof ControllerHelperTrait; BusinessHelperTrait::FireEvent insteadof ControllerHelperTrait; BusinessHelperTrait::OnEvent insteadof ControllerHelperTrait; BusinessHelperTrait::OnEvent insteadof AppHelperTrait; BusinessHelperTrait::FireEvent insteadof AppHelperTrait; BusinessHelperTrait::PathOfProject insteadof AppHelperTrait; BusinessHelperTrait::PathOfRuntime insteadof AppHelperTrait; ControllerHelperTrait::header insteadof AppHelperTrait; ControllerHelperTrait::setcookie insteadof AppHelperTrait; ControllerHelperTrait::exit insteadof AppHelperTrait; ControllerHelperTrait::AdminService insteadof BusinessHelperTrait; ControllerHelperTrait::UserService insteadof BusinessHelperTrait; } }
php
MIT
16b1924f5d43911d9448af5b63ab27d20529a104
2026-01-05T05:11:36.735455Z
false