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
laqul/laqul
https://github.com/laqul/laqul/blob/da37670fa22c693a566e97e2b57c7d7399e9daac/api/config/auth.php
api/config/auth.php
<?php return [ /* |-------------------------------------------------------------------------- | Authentication Defaults |-------------------------------------------------------------------------- | | This option controls the default authentication "guard" and password | reset options for your application. You may change these defaults | as required, but they're a perfect start for most applications. | */ 'defaults' => [ 'guard' => 'web', 'passwords' => 'users', ], /* |-------------------------------------------------------------------------- | Authentication Guards |-------------------------------------------------------------------------- | | Next, you may define every authentication guard for your application. | Of course, a great default configuration has been defined for you | here which uses session storage and the Eloquent user provider. | | All authentication drivers have a user provider. This defines how the | users are actually retrieved out of your database or other storage | mechanisms used by this application to persist your user's data. | | Supported: "session", "token" | */ 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'passport', 'provider' => 'users', ], ], /* |-------------------------------------------------------------------------- | User Providers |-------------------------------------------------------------------------- | | All authentication drivers have a user provider. This defines how the | users are actually retrieved out of your database or other storage | mechanisms used by this application to persist your user's data. | | If you have multiple user tables or models you may configure multiple | sources which represent each model / table. These sources may then | be assigned to any extra authentication guards you have defined. | | Supported: "database", "eloquent" | */ 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => App\Models\User\User::class, ], // 'users' => [ // 'driver' => 'database', // 'table' => 'users', // ], ], /* |-------------------------------------------------------------------------- | Resetting Passwords |-------------------------------------------------------------------------- | | You may specify multiple password reset configurations if you have more | than one user table or model in the application and you want to have | separate password reset settings based on the specific user types. | | The expire time is the number of minutes that the reset token should be | considered valid. This security feature keeps tokens short-lived so | they have less time to be guessed. You may change this as needed. | */ 'passwords' => [ 'users' => [ 'provider' => 'users', 'table' => 'password_resets', 'expire' => 60, ], ], 'tokenLifeTime' => [ 'default' => env('DEFAULT_TOKEN_LIFETIME', true), 'refreshToken' => env('REFRESH_TOKEN_LIFETIME', 15552000), // 6 months 'accessToken' => env('ACCESS_TOKEN_LIFETIME', 1800) // 30 minutes ], 'firebaseToken' => [ 'generate' => env('GENERATE_FIREBASE_AUTH_TOKEN', false), 'serviceAccountEmail' => env('FIREBASE_SERVICE_ACCOUNT'), 'aud' => env('FIREBASE_AUD') ] ];
php
MIT
da37670fa22c693a566e97e2b57c7d7399e9daac
2026-01-05T05:16:00.151695Z
false
laqul/laqul
https://github.com/laqul/laqul/blob/da37670fa22c693a566e97e2b57c7d7399e9daac/api/database/seeds/UserSeeder.php
api/database/seeds/UserSeeder.php
<?php use Illuminate\Database\Seeder; use App\Models\User\User; class UserSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { User::create([ 'client_id' => '71d4f8ea-1138-11e8-a472-002163944a0x', 'name' => 'Test User', 'email' => 'test@test.com', 'password' => bcrypt('12345678'), 'timezone' => 'America/Mexico_City' ]); } }
php
MIT
da37670fa22c693a566e97e2b57c7d7399e9daac
2026-01-05T05:16:00.151695Z
false
laqul/laqul
https://github.com/laqul/laqul/blob/da37670fa22c693a566e97e2b57c7d7399e9daac/api/database/seeds/OauthClientSeeder.php
api/database/seeds/OauthClientSeeder.php
<?php use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class OauthClientSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('oauth_clients')->insert([ 'id' => '71d4f8ea-1138-11e8-a472-002163944a0x', 'name' => 'Default', 'secret' => 'y1d4f8ea113811e8a472002163944a0x1234', 'redirect' => '#', 'personal_access_client' => false, 'password_client' => true, 'revoked' => false ]); } }
php
MIT
da37670fa22c693a566e97e2b57c7d7399e9daac
2026-01-05T05:16:00.151695Z
false
laqul/laqul
https://github.com/laqul/laqul/blob/da37670fa22c693a566e97e2b57c7d7399e9daac/api/database/seeds/DatabaseSeeder.php
api/database/seeds/DatabaseSeeder.php
<?php use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $this->call(OauthClientSeeder::class); $this->call(UserSeeder::class); } }
php
MIT
da37670fa22c693a566e97e2b57c7d7399e9daac
2026-01-05T05:16:00.151695Z
false
laqul/laqul
https://github.com/laqul/laqul/blob/da37670fa22c693a566e97e2b57c7d7399e9daac/api/database/factories/UserFactory.php
api/database/factories/UserFactory.php
<?php use Faker\Generator as Faker; /* |-------------------------------------------------------------------------- | Model Factories |-------------------------------------------------------------------------- | | This directory should contain each of the model factory definitions for | your application. Factories provide a convenient way to generate new | model instances for testing / seeding your application's database. | */ $factory->define(App\User::class, function (Faker $faker) { return [ 'name' => $faker->name, 'email' => $faker->unique()->safeEmail, 'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret 'remember_token' => str_random(10), ]; });
php
MIT
da37670fa22c693a566e97e2b57c7d7399e9daac
2026-01-05T05:16:00.151695Z
false
laqul/laqul
https://github.com/laqul/laqul/blob/da37670fa22c693a566e97e2b57c7d7399e9daac/api/database/migrations/2016_06_01_000004_create_oauth_clients_table.php
api/database/migrations/2016_06_01_000004_create_oauth_clients_table.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateOauthClientsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('oauth_clients', function (Blueprint $table) { $table->uuid('id')->primary(); $table->integer('user_id')->index()->nullable(); $table->string('name'); $table->string('secret', 100); $table->text('redirect'); $table->boolean('personal_access_client'); $table->boolean('password_client'); $table->boolean('revoked'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('oauth_clients'); } }
php
MIT
da37670fa22c693a566e97e2b57c7d7399e9daac
2026-01-05T05:16:00.151695Z
false
laqul/laqul
https://github.com/laqul/laqul/blob/da37670fa22c693a566e97e2b57c7d7399e9daac/api/database/migrations/2018_04_04_011623_create_email_verifications_table.php
api/database/migrations/2018_04_04_011623_create_email_verifications_table.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateEmailVerificationsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('email_verifications', function (Blueprint $table) { $table->increments('id'); $table->uuid('client_id')->index(); $table->string('email'); $table->char('code', 100)->index(); $table->unique(['client_id', 'email']); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('email_verifications'); } }
php
MIT
da37670fa22c693a566e97e2b57c7d7399e9daac
2026-01-05T05:16:00.151695Z
false
laqul/laqul
https://github.com/laqul/laqul/blob/da37670fa22c693a566e97e2b57c7d7399e9daac/api/database/migrations/2014_10_12_000000_create_users_table.php
api/database/migrations/2014_10_12_000000_create_users_table.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->uuid('client_id')->index(); $table->string('name'); $table->string('email')->index(); $table->string('avatar', 100)->default('default_avatar.jpg'); $table->string('password'); $table->string('timezone', 50); $table->boolean('active')->default(true); $table->unique(['client_id', 'email']); $table->softDeletes(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } }
php
MIT
da37670fa22c693a566e97e2b57c7d7399e9daac
2026-01-05T05:16:00.151695Z
false
laqul/laqul
https://github.com/laqul/laqul/blob/da37670fa22c693a566e97e2b57c7d7399e9daac/api/database/migrations/2014_10_12_100000_create_password_resets_table.php
api/database/migrations/2014_10_12_100000_create_password_resets_table.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePasswordResetsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('password_resets', function (Blueprint $table) { $table->integer('user_id')->unique(); $table->string('token')->index(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('password_resets'); } }
php
MIT
da37670fa22c693a566e97e2b57c7d7399e9daac
2026-01-05T05:16:00.151695Z
false
laqul/laqul
https://github.com/laqul/laqul/blob/da37670fa22c693a566e97e2b57c7d7399e9daac/api/database/migrations/2018_04_04_154423_create_notifications_table.php
api/database/migrations/2018_04_04_154423_create_notifications_table.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateNotificationsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('notifications', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->index(); $table->string('type', 20)->index(); $table->string('color', 20); $table->string('title', 50); $table->string('body', 140); $table->boolean('open')->default(false); $table->json('payload'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('notifications'); } }
php
MIT
da37670fa22c693a566e97e2b57c7d7399e9daac
2026-01-05T05:16:00.151695Z
false
laqul/laqul
https://github.com/laqul/laqul/blob/da37670fa22c693a566e97e2b57c7d7399e9daac/api/database/migrations/2018_04_04_145622_create_permission_tables.php
api/database/migrations/2018_04_04_145622_create_permission_tables.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePermissionTables extends Migration { /** * Run the migrations. * * @return void */ public function up() { $tableNames = config('permission.table_names'); Schema::create($tableNames['permissions'], function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('guard_name'); $table->timestamps(); }); Schema::create($tableNames['roles'], function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('guard_name'); $table->timestamps(); }); Schema::create($tableNames['model_has_permissions'], function (Blueprint $table) use ($tableNames) { $table->integer('permission_id')->unsigned(); $table->morphs('model'); $table->foreign('permission_id') ->references('id') ->on($tableNames['permissions']) ->onDelete('cascade'); $table->primary(['permission_id', 'model_id', 'model_type']); }); Schema::create($tableNames['model_has_roles'], function (Blueprint $table) use ($tableNames) { $table->integer('role_id')->unsigned(); $table->morphs('model'); $table->foreign('role_id') ->references('id') ->on($tableNames['roles']) ->onDelete('cascade'); $table->primary(['role_id', 'model_id', 'model_type']); }); Schema::create($tableNames['role_has_permissions'], function (Blueprint $table) use ($tableNames) { $table->integer('permission_id')->unsigned(); $table->integer('role_id')->unsigned(); $table->foreign('permission_id') ->references('id') ->on($tableNames['permissions']) ->onDelete('cascade'); $table->foreign('role_id') ->references('id') ->on($tableNames['roles']) ->onDelete('cascade'); $table->primary(['permission_id', 'role_id']); app('cache')->forget('spatie.permission.cache'); }); } /** * Reverse the migrations. * * @return void */ public function down() { $tableNames = config('permission.table_names'); Schema::drop($tableNames['role_has_permissions']); Schema::drop($tableNames['model_has_roles']); Schema::drop($tableNames['model_has_permissions']); Schema::drop($tableNames['roles']); Schema::drop($tableNames['permissions']); } }
php
MIT
da37670fa22c693a566e97e2b57c7d7399e9daac
2026-01-05T05:16:00.151695Z
false
laqul/laqul
https://github.com/laqul/laqul/blob/da37670fa22c693a566e97e2b57c7d7399e9daac/api/database/migrations/2018_04_04_142417_create_social_accounts_table.php
api/database/migrations/2018_04_04_142417_create_social_accounts_table.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateSocialAccountsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('social_accounts', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->index(); $table->string('password'); $table->string('provider', 20)->index(); $table->unique(['user_id', 'provider']); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('social_accounts'); } }
php
MIT
da37670fa22c693a566e97e2b57c7d7399e9daac
2026-01-05T05:16:00.151695Z
false
laqul/laqul
https://github.com/laqul/laqul/blob/da37670fa22c693a566e97e2b57c7d7399e9daac/api/database/migrations/2016_06_01_000005_create_oauth_personal_access_clients_table.php
api/database/migrations/2016_06_01_000005_create_oauth_personal_access_clients_table.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateOauthPersonalAccessClientsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('oauth_personal_access_clients', function (Blueprint $table) { $table->increments('id'); $table->uuid('client_id')->index(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('oauth_personal_access_clients'); } }
php
MIT
da37670fa22c693a566e97e2b57c7d7399e9daac
2026-01-05T05:16:00.151695Z
false
laqul/laqul
https://github.com/laqul/laqul/blob/da37670fa22c693a566e97e2b57c7d7399e9daac/api/database/migrations/2016_06_01_000002_create_oauth_access_tokens_table.php
api/database/migrations/2016_06_01_000002_create_oauth_access_tokens_table.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateOauthAccessTokensTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('oauth_access_tokens', function (Blueprint $table) { $table->string('id', 100)->primary(); $table->integer('user_id')->index()->nullable(); $table->uuid('client_id'); $table->string('name')->nullable(); $table->text('scopes')->nullable(); $table->boolean('revoked'); $table->timestamps(); $table->dateTime('expires_at')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('oauth_access_tokens'); } }
php
MIT
da37670fa22c693a566e97e2b57c7d7399e9daac
2026-01-05T05:16:00.151695Z
false
laqul/laqul
https://github.com/laqul/laqul/blob/da37670fa22c693a566e97e2b57c7d7399e9daac/api/database/migrations/2016_06_01_000003_create_oauth_refresh_tokens_table.php
api/database/migrations/2016_06_01_000003_create_oauth_refresh_tokens_table.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateOauthRefreshTokensTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('oauth_refresh_tokens', function (Blueprint $table) { $table->string('id', 100)->primary(); $table->string('access_token_id', 100)->index(); $table->boolean('revoked'); $table->dateTime('expires_at')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('oauth_refresh_tokens'); } }
php
MIT
da37670fa22c693a566e97e2b57c7d7399e9daac
2026-01-05T05:16:00.151695Z
false
laqul/laqul
https://github.com/laqul/laqul/blob/da37670fa22c693a566e97e2b57c7d7399e9daac/api/database/migrations/2018_04_04_153230_create_messaging_tokens_table.php
api/database/migrations/2018_04_04_153230_create_messaging_tokens_table.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateMessagingTokensTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('messaging_tokens', function (Blueprint $table) { $table->string('token', 200)->primary(); $table->integer('user_id')->index(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('messaging_tokens'); } }
php
MIT
da37670fa22c693a566e97e2b57c7d7399e9daac
2026-01-05T05:16:00.151695Z
false
laqul/laqul
https://github.com/laqul/laqul/blob/da37670fa22c693a566e97e2b57c7d7399e9daac/api/database/migrations/2016_06_01_000001_create_oauth_auth_codes_table.php
api/database/migrations/2016_06_01_000001_create_oauth_auth_codes_table.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateOauthAuthCodesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('oauth_auth_codes', function (Blueprint $table) { $table->string('id', 100)->primary(); $table->integer('user_id'); $table->uuid('client_id'); $table->text('scopes')->nullable(); $table->boolean('revoked'); $table->dateTime('expires_at')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('oauth_auth_codes'); } }
php
MIT
da37670fa22c693a566e97e2b57c7d7399e9daac
2026-01-05T05:16:00.151695Z
false
laqul/laqul
https://github.com/laqul/laqul/blob/da37670fa22c693a566e97e2b57c7d7399e9daac/api/resources/lang/en/passwords.php
api/resources/lang/en/passwords.php
<?php return [ /* |-------------------------------------------------------------------------- | Password Reset Language Lines |-------------------------------------------------------------------------- | | The following language lines are the default lines which match reasons | that are given by the password broker for a password update attempt | has failed, such as for an invalid token or invalid new password. | */ 'password' => 'Passwords must be at least six characters and match the confirmation.', 'reset' => 'Your password has been reset!', 'sent' => 'We have e-mailed your password reset link!', 'token' => 'This password reset token is invalid.', 'user' => "We can't find a user with that e-mail address.", ];
php
MIT
da37670fa22c693a566e97e2b57c7d7399e9daac
2026-01-05T05:16:00.151695Z
false
laqul/laqul
https://github.com/laqul/laqul/blob/da37670fa22c693a566e97e2b57c7d7399e9daac/api/resources/lang/en/pagination.php
api/resources/lang/en/pagination.php
<?php return [ /* |-------------------------------------------------------------------------- | Pagination Language Lines |-------------------------------------------------------------------------- | | The following language lines are used by the paginator library to build | the simple pagination links. You are free to change them to anything | you want to customize your views to better match your application. | */ 'previous' => '&laquo; Previous', 'next' => 'Next &raquo;', ];
php
MIT
da37670fa22c693a566e97e2b57c7d7399e9daac
2026-01-05T05:16:00.151695Z
false
laqul/laqul
https://github.com/laqul/laqul/blob/da37670fa22c693a566e97e2b57c7d7399e9daac/api/resources/lang/en/validation.php
api/resources/lang/en/validation.php
<?php return [ /* |-------------------------------------------------------------------------- | Validation Language Lines |-------------------------------------------------------------------------- | | The following language lines contain the default error messages used by | the validator class. Some of these rules have multiple versions such | as the size rules. Feel free to tweak each of these messages here. | */ 'accepted' => 'The :attribute must be accepted.', 'active_url' => 'The :attribute is not a valid URL.', 'after' => 'The :attribute must be a date after :date.', 'after_or_equal' => 'The :attribute must be a date after or equal to :date.', 'alpha' => 'The :attribute may only contain letters.', 'alpha_dash' => 'The :attribute may only contain letters, numbers, and dashes.', 'alpha_num' => 'The :attribute may only contain letters and numbers.', 'array' => 'The :attribute must be an array.', 'before' => 'The :attribute must be a date before :date.', 'before_or_equal' => 'The :attribute must be a date before or equal to :date.', 'between' => [ 'numeric' => 'The :attribute must be between :min and :max.', 'file' => 'The :attribute must be between :min and :max kilobytes.', 'string' => 'The :attribute must be between :min and :max characters.', 'array' => 'The :attribute must have between :min and :max items.', ], 'boolean' => 'The :attribute field must be true or false.', 'confirmed' => 'The :attribute confirmation does not match.', 'date' => 'The :attribute is not a valid date.', 'date_format' => 'The :attribute does not match the format :format.', 'different' => 'The :attribute and :other must be different.', 'digits' => 'The :attribute must be :digits digits.', 'digits_between' => 'The :attribute must be between :min and :max digits.', 'dimensions' => 'The :attribute has invalid image dimensions.', 'distinct' => 'The :attribute field has a duplicate value.', 'email' => 'The :attribute must be a valid email address.', 'exists' => 'The selected :attribute is invalid.', 'file' => 'The :attribute must be a file.', 'filled' => 'The :attribute field must have a value.', 'image' => 'The :attribute must be an image.', 'in' => 'The selected :attribute is invalid.', 'in_array' => 'The :attribute field does not exist in :other.', 'integer' => 'The :attribute must be an integer.', 'ip' => 'The :attribute must be a valid IP address.', 'ipv4' => 'The :attribute must be a valid IPv4 address.', 'ipv6' => 'The :attribute must be a valid IPv6 address.', 'json' => 'The :attribute must be a valid JSON string.', 'max' => [ 'numeric' => 'The :attribute may not be greater than :max.', 'file' => 'The :attribute may not be greater than :max kilobytes.', 'string' => 'The :attribute may not be greater than :max characters.', 'array' => 'The :attribute may not have more than :max items.', ], 'mimes' => 'The :attribute must be a file of type: :values.', 'mimetypes' => 'The :attribute must be a file of type: :values.', 'min' => [ 'numeric' => 'The :attribute must be at least :min.', 'file' => 'The :attribute must be at least :min kilobytes.', 'string' => 'The :attribute must be at least :min characters.', 'array' => 'The :attribute must have at least :min items.', ], 'not_in' => 'The selected :attribute is invalid.', 'not_regex' => 'The :attribute format is invalid.', 'numeric' => 'The :attribute must be a number.', 'present' => 'The :attribute field must be present.', 'regex' => 'The :attribute format is invalid.', 'required' => 'The :attribute field is required.', 'required_if' => 'The :attribute field is required when :other is :value.', 'required_unless' => 'The :attribute field is required unless :other is in :values.', 'required_with' => 'The :attribute field is required when :values is present.', 'required_with_all' => 'The :attribute field is required when :values is present.', 'required_without' => 'The :attribute field is required when :values is not present.', 'required_without_all' => 'The :attribute field is required when none of :values are present.', 'same' => 'The :attribute and :other must match.', 'size' => [ 'numeric' => 'The :attribute must be :size.', 'file' => 'The :attribute must be :size kilobytes.', 'string' => 'The :attribute must be :size characters.', 'array' => 'The :attribute must contain :size items.', ], 'string' => 'The :attribute must be a string.', 'timezone' => 'The :attribute must be a valid zone.', 'unique' => 'The :attribute has already been taken.', 'uploaded' => 'The :attribute failed to upload.', 'url' => 'The :attribute format is invalid.', /* |-------------------------------------------------------------------------- | Custom Validation Language Lines |-------------------------------------------------------------------------- | | Here you may specify custom validation messages for attributes using the | convention "attribute.rule" to name the lines. This makes it quick to | specify a specific custom language line for a given attribute rule. | */ 'custom' => [ 'attribute-name' => [ 'rule-name' => 'custom-message', ], ], /* |-------------------------------------------------------------------------- | Custom Validation Attributes |-------------------------------------------------------------------------- | | The following language lines are used to swap attribute place-holders | with something more reader friendly such as E-Mail Address instead | of "email". This simply helps us make messages a little cleaner. | */ 'attributes' => [], 'current_password' => 'The :attribute is not valid.', ];
php
MIT
da37670fa22c693a566e97e2b57c7d7399e9daac
2026-01-05T05:16:00.151695Z
false
laqul/laqul
https://github.com/laqul/laqul/blob/da37670fa22c693a566e97e2b57c7d7399e9daac/api/resources/lang/en/auth.php
api/resources/lang/en/auth.php
<?php return [ /* |-------------------------------------------------------------------------- | Authentication Language Lines |-------------------------------------------------------------------------- | | The following language lines are used during authentication for various | messages that we need to display to the user. You are free to modify | these language lines according to your application's requirements. | */ 'failed' => 'These credentials do not match our records.', 'throttle' => 'Too many login attempts. Please try again in :seconds seconds.', ];
php
MIT
da37670fa22c693a566e97e2b57c7d7399e9daac
2026-01-05T05:16:00.151695Z
false
laqul/laqul
https://github.com/laqul/laqul/blob/da37670fa22c693a566e97e2b57c7d7399e9daac/api/resources/views/welcome.blade.php
api/resources/views/welcome.blade.php
<!doctype html> <html lang="{{ app()->getLocale() }}"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Laravel</title> <!-- Fonts --> <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css"> <!-- Styles --> <style> html, body { background-color: #fff; color: #636b6f; font-family: 'Raleway', sans-serif; font-weight: 100; height: 100vh; margin: 0; } .full-height { height: 100vh; } .flex-center { align-items: center; display: flex; justify-content: center; } .position-ref { position: relative; } .top-right { position: absolute; right: 10px; top: 18px; } .content { text-align: center; } .title { font-size: 84px; } .links > a { color: #636b6f; padding: 0 25px; font-size: 12px; font-weight: 600; letter-spacing: .1rem; text-decoration: none; text-transform: uppercase; } .m-b-md { margin-bottom: 30px; } </style> </head> <body> <div class="flex-center position-ref full-height"> @if (Route::has('login')) <div class="top-right links"> @auth <a href="{{ url('/home') }}">Home</a> @else <a href="{{ route('login') }}">Login</a> <a href="{{ route('register') }}">Register</a> @endauth </div> @endif <div class="content"> <div class="title m-b-md"> Laravel </div> <div class="links"> <a href="https://laravel.com/docs">Documentation</a> <a href="https://laracasts.com">Laracasts</a> <a href="https://laravel-news.com">News</a> <a href="https://forge.laravel.com">Forge</a> <a href="https://github.com/laravel/laravel">GitHub</a> </div> </div> </div> </body> </html>
php
MIT
da37670fa22c693a566e97e2b57c7d7399e9daac
2026-01-05T05:16:00.151695Z
false
laqul/laqul
https://github.com/laqul/laqul/blob/da37670fa22c693a566e97e2b57c7d7399e9daac/api/resources/views/vendor/graphql/graphiql.php
api/resources/views/vendor/graphql/graphiql.php
<!DOCTYPE html> <html> <head> <style> html, body { height: 100%; margin: 0; padding: 0; width: 100%; overflow: hidden; } #graphiql { height: 100vh; } </style> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/graphiql/0.10.2/graphiql.min.css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.3/fetch.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.4/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.4/react-dom.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/graphiql/0.11.11/graphiql.min.js"></script> </head> <body> <div id="graphiql">Loading...</div> <script> /** * This GraphiQL example illustrates how to use some of GraphiQL's props * in order to enable reading and updating the URL parameters, making * link sharing of queries a little bit easier. * * This is only one example of this kind of feature, GraphiQL exposes * various React params to enable interesting integrations. */ // Parse the search string to get url parameters. var search = window.location.search; var parameters = {}; search.substr(1).split('&').forEach(function (entry) { var eq = entry.indexOf('='); if (eq >= 0) { parameters[decodeURIComponent(entry.slice(0, eq))] = decodeURIComponent(entry.slice(eq + 1)); } }); // if variables was provided, try to format it. if (parameters.variables) { try { parameters.variables = JSON.stringify(JSON.parse(parameters.variables), null, 2); } catch (e) { // Do nothing, we want to display the invalid JSON as a string, rather // than present an error. } } // When the query and variables string is edited, update the URL bar so // that it can be easily shared function onEditQuery(newQuery) { parameters.query = newQuery; updateURL(); } function onEditVariables(newVariables) { parameters.variables = newVariables; updateURL(); } function onEditOperationName(newOperationName) { parameters.operationName = newOperationName; updateURL(); } function updateURL() { var newSearch = '?' + Object.keys(parameters).filter(function (key) { return Boolean(parameters[key]); }).map(function (key) { return encodeURIComponent(key) + '=' + encodeURIComponent(parameters[key]); }).join('&'); history.replaceState(null, null, newSearch); } // Defines a GraphQL fetcher using the fetch API. function graphQLFetcher(graphQLParams) { return fetch('<?php echo $graphqlPath; ?>', { method: 'post', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(graphQLParams), credentials: 'include', }).then(function (response) { return response.text(); }).then(function (responseBody) { try { return JSON.parse(responseBody); } catch (error) { return responseBody; } }); } // Render <GraphiQL /> into the body. ReactDOM.render( React.createElement(GraphiQL, { fetcher: graphQLFetcher, query: parameters.query, variables: parameters.variables, operationName: parameters.operationName, onEditQuery: onEditQuery, onEditVariables: onEditVariables, onEditOperationName: onEditOperationName }), document.getElementById('graphiql') ); </script> </body> </html>
php
MIT
da37670fa22c693a566e97e2b57c7d7399e9daac
2026-01-05T05:16:00.151695Z
false
laqul/laqul
https://github.com/laqul/laqul/blob/da37670fa22c693a566e97e2b57c7d7399e9daac/api/resources/views/mails/email-verification.blade.php
api/resources/views/mails/email-verification.blade.php
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <h1>Email Verification</h1> {{config('client.registrationUrl').'/'.$code}} </body> </html>
php
MIT
da37670fa22c693a566e97e2b57c7d7399e9daac
2026-01-05T05:16:00.151695Z
false
laqul/laqul
https://github.com/laqul/laqul/blob/da37670fa22c693a566e97e2b57c7d7399e9daac/api/resources/views/mails/forgot-password-plain.blade.php
api/resources/views/mails/forgot-password-plain.blade.php
Reset your password {{config('client.resetPasswordUrl').'/'.$token}}
php
MIT
da37670fa22c693a566e97e2b57c7d7399e9daac
2026-01-05T05:16:00.151695Z
false
laqul/laqul
https://github.com/laqul/laqul/blob/da37670fa22c693a566e97e2b57c7d7399e9daac/api/resources/views/mails/email-verification-plain.blade.php
api/resources/views/mails/email-verification-plain.blade.php
Email Verification {{config('client.registrationUrl').'/'.$code}}
php
MIT
da37670fa22c693a566e97e2b57c7d7399e9daac
2026-01-05T05:16:00.151695Z
false
laqul/laqul
https://github.com/laqul/laqul/blob/da37670fa22c693a566e97e2b57c7d7399e9daac/api/resources/views/mails/forgot-password.blade.php
api/resources/views/mails/forgot-password.blade.php
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <h1>Reset your password</h1> {{config('client.resetPasswordUrl').'/'.$token}} </body> </html>
php
MIT
da37670fa22c693a566e97e2b57c7d7399e9daac
2026-01-05T05:16:00.151695Z
false
tuupola/cors-middleware
https://github.com/tuupola/cors-middleware/blob/e391075e2635f29bed258926f9b588d1418c4ee6/rector.php
rector.php
<?php declare(strict_types=1); use Rector\CodeQuality\Rector\If_\SimplifyIfElseToTernaryRector; use Rector\CodingStyle\Rector\Closure\StaticClosureRector; use Rector\Config\RectorConfig; use Rector\Set\ValueObject\LevelSetList; use Rector\Set\ValueObject\SetList; use Rector\PHPUnit\Set\PHPUnitSetList; use Rector\PHPUnit\Rector\Class_\AddSeeTestAnnotationRector; return static function (RectorConfig $rectorConfig): void { $rectorConfig->phpstanConfig(__DIR__ . "/phpstan.neon"); $rectorConfig->paths([ __DIR__ . "/src", __DIR__ . "/tests", ]); $rectorConfig->sets([ LevelSetList::UP_TO_PHP_72, SetList::CODE_QUALITY, //SetList::DEAD_CODE, //SetList::PRIVATIZATION, //SetList::NAMING, //SetList::TYPE_DECLARATION, //SetList::EARLY_RETURN, //SetList::TYPE_DECLARATION_STRICT, SetList::DEAD_CODE, PHPUnitSetList::PHPUNIT_CODE_QUALITY, //PHPUnitSetList::PHPUNIT_90, SetList::CODING_STYLE, ]); $rectorConfig->skip([ StaticClosureRector::class, SimplifyIfElseToTernaryRector::class, AddSeeTestAnnotationRector::class, ]); $rectorConfig->importNames(); };
php
MIT
e391075e2635f29bed258926f9b588d1418c4ee6
2026-01-05T05:16:15.421418Z
false
tuupola/cors-middleware
https://github.com/tuupola/cors-middleware/blob/e391075e2635f29bed258926f9b588d1418c4ee6/ecs.php
ecs.php
<?php declare(strict_types=1); use PhpCsFixer\Fixer\ArrayNotation\ArraySyntaxFixer; use Symplify\EasyCodingStandard\Config\ECSConfig; use Symplify\EasyCodingStandard\ValueObject\Set\SetList; use PhpCsFixer\Fixer\Phpdoc\PhpdocLineSpanFixer; use PhpCsFixer\Fixer\Phpdoc\NoSuperfluousPhpdocTagsFixer; return static function (ECSConfig $ecsConfig): void { $ecsConfig->paths([__DIR__ . "/src", __DIR__ . "/tests"]); $ecsConfig->ruleWithConfiguration(ArraySyntaxFixer::class, [ "syntax" => "short", ]); $ecsConfig->rules([ // FullyQualifiedStrictTypesFixer::class, ]); $ecsConfig->skip([ // ClassAttributesSeparationFixer::class, NoSuperfluousPhpdocTagsFixer::class, ]); $ecsConfig->sets([ SetList::SPACES, SetList::ARRAY, SetList::DOCBLOCK, SetList::PSR_12, ]); $ecsConfig->ruleWithConfiguration(PhpdocLineSpanFixer::class, [ "property" => "single", "const" => "single", ]); };
php
MIT
e391075e2635f29bed258926f9b588d1418c4ee6
2026-01-05T05:16:15.421418Z
false
tuupola/cors-middleware
https://github.com/tuupola/cors-middleware/blob/e391075e2635f29bed258926f9b588d1418c4ee6/src/Settings.php
src/Settings.php
<?php /* Copyright (c) 2022 Pavlo Mikhailidi 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. */ declare(strict_types=1); namespace Tuupola\Middleware; use Neomerx\Cors\Strategies\Settings as BaseSettings; class Settings extends BaseSettings { /** @var array<string> */ private $allowedOrigins = []; public function setAllowedOrigins(array $origins): BaseSettings { $this->allowedOrigins = $origins; return parent::setAllowedOrigins($origins); } public function isRequestOriginAllowed(string $requestOrigin): bool { $isAllowed = parent::isRequestOriginAllowed($requestOrigin); if (! $isAllowed) { $isAllowed = $this->wildcardOriginAllowed($requestOrigin); } return $isAllowed; } private function wildcardOriginAllowed(string $origin): bool { foreach ($this->allowedOrigins as $allowedOrigin) { if (fnmatch($allowedOrigin, $origin)) { return true; } } return false; } }
php
MIT
e391075e2635f29bed258926f9b588d1418c4ee6
2026-01-05T05:16:15.421418Z
false
tuupola/cors-middleware
https://github.com/tuupola/cors-middleware/blob/e391075e2635f29bed258926f9b588d1418c4ee6/src/CorsMiddleware.php
src/CorsMiddleware.php
<?php /* Copyright (c) 2016-2022 Mika Tuupola 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. */ /** * @see https://github.com/tuupola/cors-middleware * @see https://github.com/neomerx/cors-psr7 * @see https://www.w3.org/TR/cors/ * @license https://www.opensource.org/licenses/mit-license.php */ declare(strict_types=1); namespace Tuupola\Middleware; use Closure; use Neomerx\Cors\Analyzer as CorsAnalyzer; use Neomerx\Cors\Contracts\AnalysisResultInterface as CorsAnalysisResultInterface; use Neomerx\Cors\Contracts\Constants\CorsResponseHeaders; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use Psr\Log\LoggerInterface; use Tuupola\Http\Factory\ResponseFactory; use Tuupola\Middleware\Settings as CorsSettings; final class CorsMiddleware implements MiddlewareInterface { use DoublePassTrait; /** @var int */ private const PORT_HTTP = 80; /** @var int */ private const PORT_HTTPS = 443; /** @var LoggerInterface|null */ private $logger; /** * @var array{ * origin: array<string>, * methods: array<string>|callable|null, * "headers.allow": array<string>, * "headers.expose": array<string>, * credentials: bool, * "origin.server": null|string, * cache: int, * error: null|callable, * logger: null|LoggerInterface, * } */ private $options = [ "origin" => ["*"], "methods" => ["GET", "POST", "PUT", "PATCH", "DELETE"], "headers.allow" => [], "headers.expose" => [], "credentials" => false, "origin.server" => null, "cache" => 0, "error" => null, "logger" => null, ]; /** * @param array{ * origin?: string|array<string>, * methods?: array<string>|callable|null, * "headers.allow"?: array<string>, * "headers.expose"?: array<string>, * credentials?: bool, * "origin.server"?: null|string, * cache?: int, * error?: null|callable, * logger?: null|LoggerInterface, * } $options */ public function __construct(array $options = []) { /* TODO: This only exists to for BC. */ if (isset($options["origin"])) { $options["origin"] = (array) $options["origin"]; } /* Store passed in options overwriting any defaults. */ $this->hydrate($options); } /** * Execute as PSR-15 middleware. */ public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $response = (new ResponseFactory())->createResponse(); $analyzer = CorsAnalyzer::instance($this->buildSettings($request, $response)); if ($this->logger !== null) { $analyzer->setLogger($this->logger); } $cors = $analyzer->analyze($request); switch ($cors->getRequestType()) { case CorsAnalysisResultInterface::ERR_ORIGIN_NOT_ALLOWED: $response = $response->withStatus(401); return $this->processError($request, $response, [ "message" => "CORS request origin is not allowed.", ]); case CorsAnalysisResultInterface::ERR_METHOD_NOT_SUPPORTED: $response = $response->withStatus(401); return $this->processError($request, $response, [ "message" => "CORS requested method is not supported.", ]); case CorsAnalysisResultInterface::ERR_HEADERS_NOT_SUPPORTED: $response = $response->withStatus(401); return $this->processError($request, $response, [ "message" => "CORS requested header is not allowed.", ]); case CorsAnalysisResultInterface::TYPE_PRE_FLIGHT_REQUEST: $cors_headers = $cors->getResponseHeaders(); foreach ($cors_headers as $header => $value) { /* Diactoros errors on integer values. */ if (! is_array($value)) { $value = (string) $value; } $response = $response->withHeader($header, $value); } return $response->withStatus(200); case CorsAnalysisResultInterface::TYPE_REQUEST_OUT_OF_CORS_SCOPE: return $handler->handle($request); default: /* Actual CORS request. */ $response = $handler->handle($request); $cors_headers = $cors->getResponseHeaders(); $cors_headers = $this->fixHeaders($cors_headers); foreach ($cors_headers as $header => $value) { /* Diactoros errors on integer values. */ if (! is_array($value)) { $value = (string) $value; } $response = $response->withHeader($header, $value); } return $response; } } /** * Hydrate all options from the given array. */ private function hydrate(array $data = []): void { foreach ($data as $key => $value) { /* https://github.com/facebook/hhvm/issues/6368 */ $key = str_replace(".", " ", $key); $method = lcfirst(ucwords($key)); $method = str_replace(" ", "", $method); $callable = [$this, $method]; if (is_callable($callable)) { /* Try to use setter */ call_user_func($callable, $value); } else { /** * Or fallback to setting option directly * Shouldn't be in use as every option is covered by setters * * @phpstan-ignore-next-line */ $this->options[$key] = $value; } } } /** * Build a CORS settings object. */ private function buildSettings(ServerRequestInterface $request, ResponseInterface $response): CorsSettings { $settings = new CorsSettings(); $serverOrigin = $this->determineServerOrigin(); $settings->init( $serverOrigin["scheme"], $serverOrigin["host"], $serverOrigin["port"] ); $settings->setAllowedOrigins($this->options["origin"]); if (is_callable($this->options["methods"])) { $methods = (array) $this->options["methods"]($request, $response); } else { $methods = (array) $this->options["methods"]; } $settings->setAllowedMethods($methods); /* transform all headers to lowercase */ $headers = array_change_key_case($this->options["headers.allow"]); $settings->setAllowedHeaders($headers); $settings->setExposedHeaders($this->options["headers.expose"]); if ($this->options["credentials"]) { $settings->setCredentialsSupported(); } $settings->setPreFlightCacheMaxAge($this->options["cache"]); return $settings; } /** * Try to determine the server origin uri fragments * * @return array{scheme: string, host: string, port: int} */ private function determineServerOrigin(): array { /* Set defaults */ $url = [ "scheme" => "https", "host" => "localhost", "port" => self::PORT_HTTPS, ]; /* Load details from server origin */ if (is_string($this->options["origin.server"])) { /** @var false|array{scheme: string, host: string, port?: int} $url_chunks */ $url_chunks = parse_url($this->options["origin.server"]); if ($url_chunks !== false) { $url = $url_chunks; } if (! array_key_exists("port", $url)) { $url["port"] = $url["scheme"] === "https" ? self::PORT_HTTPS : self::PORT_HTTP; } } return $url; } /** * Edge cannot handle Access-Control-Expose-Headers having a trailing whitespace after the comma * * @see https://github.com/tuupola/cors-middleware/issues/40 */ private function fixHeaders(array $headers): array { if (isset($headers[CorsResponseHeaders::EXPOSE_HEADERS])) { $headers[CorsResponseHeaders::EXPOSE_HEADERS] = str_replace( " ", "", $headers[CorsResponseHeaders::EXPOSE_HEADERS] ); } return $headers; } /** * Set allowed origin. * @phpstan-ignore method.unused */ private function origin(array $origin): void { $this->options["origin"] = $origin; } /** * Set request methods to be allowed. * @param callable|array $methods. * @phpstan-ignore method.unused */ private function methods($methods): void { if (is_callable($methods)) { if ($methods instanceof Closure) { $this->options["methods"] = $methods->bindTo($this); } else { $this->options["methods"] = $methods; } } else { $this->options["methods"] = (array) $methods; } } /** * Set headers to be allowed. * @phpstan-ignore method.unused */ private function headersAllow(array $headers): void { $this->options["headers.allow"] = $headers; } /** * Set headers to be exposed. * @phpstan-ignore method.unused */ private function headersExpose(array $headers): void { $this->options["headers.expose"] = $headers; } /** * Enable or disable cookies and authentication. * @phpstan-ignore method.unused */ private function credentials(bool $credentials): void { $this->options["credentials"] = $credentials; } /** * Set the server origin. * @phpstan-ignore method.unused */ private function originServer(?string $origin): void { $this->options["origin.server"] = $origin; } /** * Set the cache time in seconds. * @phpstan-ignore method.unused */ private function cache(int $cache): void { $this->options["cache"] = $cache; } /** * Set the error handler. * @phpstan-ignore method.unused */ private function error(callable $error): void { if ($error instanceof Closure) { $this->options["error"] = $error->bindTo($this); } else { $this->options["error"] = $error; } } /** * Set the PSR-3 logger. * @phpstan-ignore method.unused */ private function logger(?LoggerInterface $logger = null): void { $this->logger = $logger; } /** * Call the error handler if it exists. */ private function processError( ServerRequestInterface $request, ResponseInterface $response, ?array $arguments = null ): ResponseInterface { if (is_callable($this->options["error"])) { $handler_response = $this->options["error"]($request, $response, $arguments); if (is_a($handler_response, ResponseInterface::class)) { return $handler_response; } } return $response; } }
php
MIT
e391075e2635f29bed258926f9b588d1418c4ee6
2026-01-05T05:16:15.421418Z
false
tuupola/cors-middleware
https://github.com/tuupola/cors-middleware/blob/e391075e2635f29bed258926f9b588d1418c4ee6/tests/CorsMiddlewareTest.php
tests/CorsMiddlewareTest.php
<?php /* Copyright (c) 2016-2022 Mika Tuupola 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. */ /** * @see https://github.com/tuupola/cors-middleware * @see https://github.com/neomerx/cors-psr7 * @see https://www.w3.org/TR/cors/ * @license https://www.opensource.org/licenses/mit-license.php */ namespace Tuupola\Middleware; use Equip\Dispatch\MiddlewareCollection; use PHPUnit\Framework\TestCase; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Log\NullLogger; use Tuupola\Http\Factory\ResponseFactory; use Tuupola\Http\Factory\ServerRequestFactory; class CorsMiddlewareTest extends TestCase { public function testShouldBeTrue(): void { $this->assertTrue(true); } public function testShouldReturn200ByDefault(): void { $request = (new ServerRequestFactory()) ->createServerRequest("GET", "https://example.com/api"); $response = (new ResponseFactory())->createResponse(); $cors = new CorsMiddleware(); $next = static function (ServerRequestInterface $request, ResponseInterface $response) { $response->getBody()->write("Foo"); return $response; }; $response = $cors($request, $response, $next); $this->assertSame(200, $response->getStatusCode()); } public function testShouldAcceptWildcardSettings(): void { $request = (new ServerRequestFactory()) ->createServerRequest("POST", "https://example.com/api") ->withHeader("Origin", "https://subdomain.example.com"); $response = (new ResponseFactory())->createResponse(); $cors = new CorsMiddleware([ "origin" => [ "*.example.com", ], "methods" => ["GET", "POST", "PUT", "PATCH", "DELETE"], "headers.allow" => ["Authorization", "If-Match", "If-Unmodified-Since"], "headers.expose" => ["Authorization", "Etag"], "credentials" => true, "cache" => 86400, ]); $next = static function (ServerRequestInterface $request, ResponseInterface $response) { $response->getBody()->write("Foo"); return $response; }; $response = $cors($request, $response, $next); $this->assertSame(200, $response->getStatusCode()); $this->assertSame("https://subdomain.example.com", $response->getHeaderLine("Access-Control-Allow-Origin")); $this->assertSame("true", $response->getHeaderLine("Access-Control-Allow-Credentials")); $this->assertSame("Origin", $response->getHeaderLine("Vary")); $this->assertSame("Authorization,Etag", $response->getHeaderLine("Access-Control-Expose-Headers")); } public function testShouldHaveCorsHeaders(): void { $request = (new ServerRequestFactory()) ->createServerRequest("GET", "https://example.com/api") ->withHeader("Origin", "http://www.example.com"); $response = (new ResponseFactory())->createResponse(); $cors = new CorsMiddleware([ "origin" => "*", "methods" => ["GET", "POST", "PUT", "PATCH", "DELETE"], "headers.allow" => ["Authorization", "If-Match", "If-Unmodified-Since"], "headers.expose" => ["Authorization", "Etag"], "credentials" => true, "cache" => 86400, ]); $next = static function (ServerRequestInterface $request, ResponseInterface $response) { $response->getBody()->write("Foo"); return $response; }; $response = $cors($request, $response, $next); $this->assertSame("http://www.example.com", $response->getHeaderLine("Access-Control-Allow-Origin")); $this->assertSame("true", $response->getHeaderLine("Access-Control-Allow-Credentials")); $this->assertSame("Origin", $response->getHeaderLine("Vary")); $this->assertSame("Authorization,Etag", $response->getHeaderLine("Access-Control-Expose-Headers")); } public function testShouldReturn401WithWrongOrigin(): void { $request = (new ServerRequestFactory()) ->createServerRequest("GET", "https://example.com/api") ->withHeader("Origin", "http://www.foo.com"); $response = (new ResponseFactory())->createResponse(); $cors = new CorsMiddleware([ "origin" => ["http://www.example.com"], "methods" => ["GET", "POST", "PUT", "PATCH", "DELETE"], "headers.allow" => ["Authorization", "If-Match", "If-Unmodified-Since"], "headers.expose" => ["Authorization", "Etag"], "credentials" => true, "cache" => 86400, ]); $next = static function (ServerRequestInterface $request, ResponseInterface $response) { $response->getBody()->write("Foo"); return $response; }; $response = $cors($request, $response, $next); $this->assertSame(401, $response->getStatusCode()); } public function testShouldReturn200WithCorrectOrigin(): void { $request = (new ServerRequestFactory()) ->createServerRequest("GET", "https://example.com/api") ->withHeader("Origin", "http://mobile.example.com"); $response = (new ResponseFactory())->createResponse(); $cors = new CorsMiddleware([ "origin" => ["http://www.example.com", "http://mobile.example.com"], "methods" => ["GET", "POST", "PUT", "PATCH", "DELETE"], "headers.allow" => ["Authorization", "If-Match", "If-Unmodified-Since"], "headers.expose" => ["Authorization", "Etag"], "credentials" => true, "cache" => 86400, ]); $next = static function (ServerRequestInterface $request, ResponseInterface $response) { $response->getBody()->write("Foo"); return $response; }; $response = $cors($request, $response, $next); $this->assertSame(200, $response->getStatusCode()); } public function testShouldReturn401WithWrongMethod(): void { $request = (new ServerRequestFactory()) ->createServerRequest("OPTIONS", "https://example.com/api") ->withHeader("Origin", "http://www.example.com") ->withHeader("Access-Control-Request-Headers", "Authorization") ->withHeader("Access-Control-Request-Method", "PUT"); $response = (new ResponseFactory())->createResponse(); $cors = new CorsMiddleware([ "origin" => "*", "methods" => ["GET", "POST", "DELETE"], "headers.allow" => ["Authorization", "If-Match", "If-Unmodified-Since"], "headers.expose" => ["Authorization", "Etag"], "credentials" => true, "cache" => 86400, ]); $next = static function (ServerRequestInterface $request, ResponseInterface $response) { $response->getBody()->write("Foo"); return $response; }; $response = $cors($request, $response, $next); $this->assertSame(401, $response->getStatusCode()); } public function testShouldReturn401WithWrongMethodFromFunction(): void { $request = (new ServerRequestFactory()) ->createServerRequest("OPTIONS", "https://example.com/api") ->withHeader("Origin", "http://www.example.com") ->withHeader("Access-Control-Request-Headers", "Authorization") ->withHeader("Access-Control-Request-Method", "PUT"); $response = (new ResponseFactory())->createResponse(); $cors = new CorsMiddleware([ "origin" => "*", "methods" => function ($request) { return ["GET", "POST", "DELETE"]; }, "headers.allow" => ["Authorization", "If-Match", "If-Unmodified-Since"], "headers.expose" => ["Authorization", "Etag"], "credentials" => true, "cache" => 86400, ]); $next = static function (ServerRequestInterface $request, ResponseInterface $response) { $response->getBody()->write("Foo"); return $response; }; $response = $cors($request, $response, $next); $this->assertSame(401, $response->getStatusCode()); } public function testShouldReturn401WithWrongMethodFromInvokableClass(): void { $request = (new ServerRequestFactory()) ->createServerRequest("OPTIONS", "https://example.com/api") ->withHeader("Origin", "http://www.example.com") ->withHeader("Access-Control-Request-Headers", "Authorization") ->withHeader("Access-Control-Request-Method", "PUT"); $response = (new ResponseFactory())->createResponse(); $cors = new CorsMiddleware([ "origin" => "*", "methods" => new TestMethodsHandler(), "headers.allow" => ["Authorization", "If-Match", "If-Unmodified-Since"], "headers.expose" => ["Authorization", "Etag"], "credentials" => true, "cache" => 86400, ]); $next = static function (ServerRequestInterface $request, ResponseInterface $response) { $response->getBody()->write("Foo"); return $response; }; $response = $cors($request, $response, $next); $this->assertSame(401, $response->getStatusCode()); } public function testShouldReturn200WithCorrectMethodFromFunction(): void { $request = (new ServerRequestFactory()) ->createServerRequest("OPTIONS", "https://example.com/api") ->withHeader("Origin", "http://www.example.com") ->withHeader("Access-Control-Request-Headers", "Authorization") ->withHeader("Access-Control-Request-Method", "DELETE"); $response = (new ResponseFactory())->createResponse(); $cors = new CorsMiddleware([ "origin" => ["*"], "methods" => function ($request) { return ["GET", "POST", "DELETE"]; }, "headers.allow" => ["Authorization", "If-Match", "If-Unmodified-Since"], "headers.expose" => ["Authorization", "Etag"], "credentials" => true, "cache" => 86400, ]); $next = static function (ServerRequestInterface $request, ResponseInterface $response) { $response->getBody()->write("Foo"); return $response; }; $response = $cors($request, $response, $next); $this->assertSame(200, $response->getStatusCode()); } public function testShouldReturn200WithCorrectMethodFromInvokableClass(): void { $request = (new ServerRequestFactory()) ->createServerRequest("OPTIONS", "https://example.com/api") ->withHeader("Origin", "http://www.example.com") ->withHeader("Access-Control-Request-Headers", "Authorization") ->withHeader("Access-Control-Request-Method", "DELETE"); $response = (new ResponseFactory())->createResponse(); $cors = new CorsMiddleware([ "origin" => ["*"], "methods" => new TestMethodsHandler(), "headers.allow" => ["Authorization", "If-Match", "If-Unmodified-Since"], "headers.expose" => ["Authorization", "Etag"], "credentials" => true, "cache" => 86400, ]); $next = static function (ServerRequestInterface $request, ResponseInterface $response) { $response->getBody()->write("Foo"); return $response; }; $response = $cors($request, $response, $next); $this->assertSame(200, $response->getStatusCode()); } public function testShouldReturn200WithCorrectMethodUsingArrayNotation(): void { $request = (new ServerRequestFactory()) ->createServerRequest("OPTIONS", "https://example.com/api") ->withHeader("Origin", "http://www.example.com") ->withHeader("Access-Control-Request-Headers", "Authorization") ->withHeader("Access-Control-Request-Method", "DELETE"); $response = (new ResponseFactory())->createResponse(); $cors = new CorsMiddleware([ "origin" => ["*"], "methods" => function (ServerRequestInterface $request) { return TestMethodsHandler::methods($request); }, "headers.allow" => ["Authorization", "If-Match", "If-Unmodified-Since"], "headers.expose" => ["Authorization", "Etag"], "credentials" => true, "cache" => 86400, ]); $next = static function (ServerRequestInterface $request, ResponseInterface $response) { $response->getBody()->write("Foo"); return $response; }; $response = $cors($request, $response, $next); $this->assertSame(200, $response->getStatusCode()); } public function testShouldReturn401WithWrongHeader(): void { $request = (new ServerRequestFactory()) ->createServerRequest("OPTIONS", "https://example.com/api") ->withHeader("Origin", "http://www.example.com") ->withHeader("Access-Control-Request-Headers", "X-Nosuch") ->withHeader("Access-Control-Request-Method", "PUT"); $response = (new ResponseFactory())->createResponse(); $cors = new CorsMiddleware([ "origin" => ["*"], "methods" => ["GET", "POST", "PUT", "PATCH", "DELETE"], "headers.allow" => ["Authorization", "If-Match", "If-Unmodified-Since"], "headers.expose" => ["Authorization", "Etag"], "credentials" => true, "cache" => 86400, "error" => function ($request, $response, $arguments) { return "ignored"; }, ]); $next = static function (ServerRequestInterface $request, ResponseInterface $response) { $response->getBody()->write("Foo"); return $response; }; $response = $cors($request, $response, $next); $this->assertSame(401, $response->getStatusCode()); } public function testShouldReturn200WithProperPreflightRequest(): void { $request = (new ServerRequestFactory()) ->createServerRequest("OPTIONS", "https://example.com/api") ->withHeader("Origin", "http://www.example.com") ->withHeader("Access-Control-Request-Headers", "Authorization") ->withHeader("Access-Control-Request-Method", "PUT"); $response = (new ResponseFactory())->createResponse(); $cors = new CorsMiddleware([ "origin" => ["*"], "methods" => ["GET", "POST", "PUT", "PATCH", "DELETE"], "headers.allow" => ["Authorization", "If-Match", "If-Unmodified-Since"], "headers.expose" => ["Authorization", "Etag"], "credentials" => true, "cache" => 86400, ]); $next = static function (ServerRequestInterface $request, ResponseInterface $response) { $response->getBody()->write("Foo"); return $response; }; $response = $cors($request, $response, $next); $this->assertSame(200, $response->getStatusCode()); } public function testShouldReturn200WithNoCorsHeaders(): void { $request = (new ServerRequestFactory()) ->createServerRequest("GET", "https://example.com/api") ->withHeader("Origin", "https://example.com"); $response = (new ResponseFactory())->createResponse(); $cors = new CorsMiddleware([ "origin" => [], "origin.server" => "https://example.com", ]); $next = static function (ServerRequestInterface $request, ResponseInterface $response) { $response->getBody()->write("Foo"); return $response; }; $response = $cors($request, $response, $next); $this->assertSame(200, $response->getStatusCode()); $this->assertEmpty($response->getHeaderLine("Access-Control-Allow-Origin")); } public function testAnonymousMethodsFunctionBindsToMiddlewareInstance(): void { $request = (new ServerRequestFactory()) ->createServerRequest("OPTIONS", "https://example.com/api") ->withHeader("Origin", "http://www.example.com") ->withHeader("Access-Control-Request-Headers", "X-Nosuch") ->withHeader("Access-Control-Request-Method", "PUT"); $interceptedClassName = ""; $response = (new ResponseFactory())->createResponse(); $logger = new NullLogger(); $cors = new CorsMiddleware([ "logger" => $logger, "origin" => ["*"], "methods" => function () use (&$interceptedClassName) { $interceptedClassName = get_class($this); return ["GET"]; }, "headers.allow" => ["Authorization", "If-Match", "If-Unmodified-Since"], "headers.expose" => ["Authorization", "Etag"], "credentials" => true, "cache" => 86400, ]); $next = static function (ServerRequestInterface $request, ResponseInterface $response) { $response->getBody()->write("Foo"); return $response; }; $response = $cors($request, $response, $next); $this->assertSame( CorsMiddleware::class, $interceptedClassName ); $this->assertSame(401, $response->getStatusCode()); } public function testShouldCallAnonymousErrorFunction(): void { $request = (new ServerRequestFactory()) ->createServerRequest("OPTIONS", "https://example.com/api") ->withHeader("Origin", "http://www.example.com") ->withHeader("Access-Control-Request-Headers", "X-Nosuch") ->withHeader("Access-Control-Request-Method", "PUT"); $response = (new ResponseFactory())->createResponse(); $logger = new NullLogger(); $cors = new CorsMiddleware([ "logger" => $logger, "origin" => ["*"], "methods" => ["GET", "POST", "PUT", "PATCH", "DELETE"], "headers.allow" => ["Authorization", "If-Match", "If-Unmodified-Since"], "headers.expose" => ["Authorization", "Etag"], "credentials" => true, "cache" => 86400, "error" => function ($request, $response, $arguments) { $response->getBody()->write(get_class($this)); return $response; }, ]); $next = static function (ServerRequestInterface $request, ResponseInterface $response) { $response->getBody()->write("Foo"); return $response; }; $response = $cors($request, $response, $next); $this->assertSame(401, $response->getStatusCode()); $this->assertInstanceOf($response->getBody(), $cors); } public function testShouldCallInvokableErrorClass(): void { $request = (new ServerRequestFactory()) ->createServerRequest("OPTIONS", "https://example.com/api") ->withHeader("Origin", "http://www.example.com") ->withHeader("Access-Control-Request-Headers", "X-Nosuch") ->withHeader("Access-Control-Request-Method", "PUT"); $response = (new ResponseFactory())->createResponse(); $logger = new NullLogger(); $cors = new CorsMiddleware([ "logger" => $logger, "origin" => ["*"], "methods" => ["GET", "POST", "PUT", "PATCH", "DELETE"], "headers.allow" => ["Authorization", "If-Match", "If-Unmodified-Since"], "headers.expose" => ["Authorization", "Etag"], "credentials" => true, "cache" => 86400, "error" => new TestErrorHandler(), ]); $next = static function (ServerRequestInterface $request, ResponseInterface $response) { $response->getBody()->write("Foo"); return $response; }; $response = $cors($request, $response, $next); $this->assertSame(402, $response->getStatusCode()); $this->assertSame(TestErrorHandler::class, (string) $response->getBody()); } public function testShouldCallArrayNotationError(): void { $request = (new ServerRequestFactory()) ->createServerRequest("OPTIONS", "https://example.com/api") ->withHeader("Origin", "http://www.example.com") ->withHeader("Access-Control-Request-Headers", "X-Nosuch") ->withHeader("Access-Control-Request-Method", "PUT"); $response = (new ResponseFactory())->createResponse(); $logger = new NullLogger(); $cors = new CorsMiddleware([ "logger" => $logger, "origin" => ["*"], "methods" => ["GET", "POST", "PUT", "PATCH", "DELETE"], "headers.allow" => ["Authorization", "If-Match", "If-Unmodified-Since"], "headers.expose" => ["Authorization", "Etag"], "credentials" => true, "cache" => 86400, "error" => function ( ServerRequestInterface $request, ResponseInterface $response, array $arguments ): ResponseInterface { return TestErrorHandler::error($request, $response, $arguments); }, ]); $next = static function (ServerRequestInterface $request, ResponseInterface $response) { $response->getBody()->write("Foo"); return $response; }; $response = $cors($request, $response, $next); $this->assertSame(418, $response->getStatusCode()); $this->assertSame(TestErrorHandler::class, (string) $response->getBody()); } public function testShouldHandlePsr15(): void { $request = (new ServerRequestFactory()) ->createServerRequest("GET", "https://example.com/api") ->withHeader("Origin", "http://www.example.com"); $default = static function (ServerRequestInterface $request) { $response = (new ResponseFactory())->createResponse(); $response->getBody()->write("Success"); return $response; }; $collection = new MiddlewareCollection([ new CorsMiddleware([ "origin" => ["*"], "methods" => ["GET", "POST", "PUT", "PATCH", "DELETE"], "headers.allow" => ["Authorization", "If-Match", "If-Unmodified-Since"], "headers.expose" => ["Authorization", "Etag"], "credentials" => true, "cache" => 86400, ]), ]); $response = $collection->dispatch($request, $default); $this->assertSame("http://www.example.com", $response->getHeaderLine("Access-Control-Allow-Origin")); $this->assertSame("true", $response->getHeaderLine("Access-Control-Allow-Credentials")); $this->assertSame("Origin", $response->getHeaderLine("Vary")); $this->assertSame("Authorization,Etag", $response->getHeaderLine("Access-Control-Expose-Headers")); $this->assertSame("Success", (string) $response->getBody()); } }
php
MIT
e391075e2635f29bed258926f9b588d1418c4ee6
2026-01-05T05:16:15.421418Z
false
tuupola/cors-middleware
https://github.com/tuupola/cors-middleware/blob/e391075e2635f29bed258926f9b588d1418c4ee6/tests/TestMethodsHandler.php
tests/TestMethodsHandler.php
<?php /* Copyright (c) 2016-2022 Mika Tuupola 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. */ /** * @see https://github.com/tuupola/cors-middleware * @see https://github.com/neomerx/cors-psr7 * @see https://www.w3.org/TR/cors/ * @license https://www.opensource.org/licenses/mit-license.php */ namespace Tuupola\Middleware; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; class TestMethodsHandler { public function __invoke(ServerRequestInterface $request) { return ["GET", "POST", "DELETE"]; } public static function methods(ServerRequestInterface $request) { return ["GET", "POST", "DELETE"]; } }
php
MIT
e391075e2635f29bed258926f9b588d1418c4ee6
2026-01-05T05:16:15.421418Z
false
tuupola/cors-middleware
https://github.com/tuupola/cors-middleware/blob/e391075e2635f29bed258926f9b588d1418c4ee6/tests/TestErrorHandler.php
tests/TestErrorHandler.php
<?php /* Copyright (c) 2016-2022 Mika Tuupola 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. */ /** * @see https://github.com/tuupola/cors-middleware * @see https://github.com/neomerx/cors-psr7 * @see https://www.w3.org/TR/cors/ * @license https://www.opensource.org/licenses/mit-license.php */ namespace Tuupola\Middleware; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; class TestErrorHandler { public function __invoke( ServerRequestInterface $request, ResponseInterface $response, array $arguments ): ResponseInterface { $response->getBody()->write(self::class); return $response->withStatus(402); } public static function error( ServerRequestInterface $request, ResponseInterface $response, array $arguments ): ResponseInterface { $response->getBody()->write(self::class); return $response->withStatus(418); } }
php
MIT
e391075e2635f29bed258926f9b588d1418c4ee6
2026-01-05T05:16:15.421418Z
false
tuupola/cors-middleware
https://github.com/tuupola/cors-middleware/blob/e391075e2635f29bed258926f9b588d1418c4ee6/tests/SettingsTest.php
tests/SettingsTest.php
<?php /* Copyright (c) 2022 Pavlo Mikhailidi 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. */ declare(strict_types=1); namespace Tuupola\Middleware; use Generator; use PHPUnit\Framework\TestCase; class SettingsTest extends TestCase { /** @var Settings */ private $testObject; protected function setUp(): void { parent::setUp(); $this->testObject = new Settings(); } /** * @dataProvider wildcardOriginDataProvider */ public function testIsRequestOriginAllowed(string $origin, string $allowedOrigins, bool $expected): void { $this->testObject->setAllowedOrigins([$allowedOrigins]); $result = $this->testObject->isRequestOriginAllowed($origin); $this->assertSame($expected, $result); } public function wildcardOriginDataProvider(): Generator { /* Allow subdomain without wildcard */ yield ["https://www.example.com", "https://www.example.com", true]; /* Disallow wrong subdomain */ yield ["https://ws.example.com", "https://www.example.com", false]; /* Allow all */ yield ["https://ws.example.com", "*", true]; /* Allow subdomain wildcard */ yield ["https://ws.example.com", "https://*.example.com", true]; /* Allow without specifying protocol */ yield ["https://ws.example.com", "*.example.com", true]; /* Allow double subdomain for wildcard */ yield ["https://a.b.example.com", "*.example.com", true]; /* Disallow for incorrect domain wildcard */ yield ["https://a.example.com.evil.com", "*.example.com", false]; /* Allow subdomain in the middle */ yield ["a.b.example.com", "a.*.example.com", true]; /* Disallow wrong subdomain */ yield ["b.bc.example.com", "a.*.example.com", false]; /* Correctly handle dots */ yield ["exampleXcom", "example.com", false]; /* Allow subdomain and domain with one rule */ yield ["test.example.com", "*example*", true]; } }
php
MIT
e391075e2635f29bed258926f9b588d1418c4ee6
2026-01-05T05:16:15.421418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/LaravelConsoleWizardServiceProvider.php
src/LaravelConsoleWizardServiceProvider.php
<?php namespace Shomisha\LaravelConsoleWizard; use Illuminate\Support\ServiceProvider; use Shomisha\LaravelConsoleWizard\Command\Generators\GenerateWizardWizard; class LaravelConsoleWizardServiceProvider extends ServiceProvider { public function register() { $this->commands([ GenerateWizardWizard::class, ]); } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Templates/StepTemplate.php
src/Templates/StepTemplate.php
<?php namespace Shomisha\LaravelConsoleWizard\Templates; use Shomisha\LaravelConsoleWizard\DataTransfer\StepSpecification; use Shomisha\Stubless\ImperativeCode\InstantiateBlock; use Shomisha\Stubless\Utilities\Importable; use Shomisha\Stubless\Values\Value; class StepTemplate extends InstantiateBlock { public function __construct(StepSpecification $specification) { $class = new Importable($specification->getType()); $arguments = [ Value::string($specification->getQuestion()), ]; if ($specification->hasOptions()) { $arguments[] = Value::array($specification->getOptions()); } return parent::__construct($class, $arguments); } public static function bySpecification(StepSpecification $specification): self { return new self($specification); } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Templates/WizardTemplate.php
src/Templates/WizardTemplate.php
<?php namespace Shomisha\LaravelConsoleWizard\Templates; use Illuminate\Support\Str; use Shomisha\LaravelConsoleWizard\Command\Wizard; use Shomisha\LaravelConsoleWizard\Contracts\Step; use Shomisha\LaravelConsoleWizard\DataTransfer\StepSpecification; use Shomisha\LaravelConsoleWizard\DataTransfer\WizardSpecification; use Shomisha\Stubless\DeclarativeCode\Argument; use Shomisha\Stubless\ImperativeCode\Block; use Shomisha\Stubless\DeclarativeCode\ClassMethod; use Shomisha\Stubless\DeclarativeCode\ClassProperty; use Shomisha\Stubless\DeclarativeCode\ClassTemplate; use Shomisha\Stubless\References\Reference; use Shomisha\Stubless\Utilities\Importable; use Shomisha\Stubless\Values\Value; class WizardTemplate extends ClassTemplate { public function __construct(WizardSpecification $specification) { $name = $specification->getName(); parent::__construct($name); $this->initialize($specification); } public static function bySpecification(WizardSpecification $specification): self { return new self($specification); } private function initialize(WizardSpecification $specification): void { $this->setNamespace($specification->getNamespace()); $this->extends(new Importable(Wizard::class)); $this->addProperty( ClassProperty::name('signature')->value($specification->getSignature())->makeProtected() ); if ($description = $specification->getDescription()) { $this->addProperty( ClassProperty::name('description')->value($description)->makeProtected() ); } $this->initializeSteps($specification); $this->addMethod( $this->getCompletedMethod() ); } private function initializeSteps(WizardSpecification $specification): void { $this->addMethod( $method = ClassMethod::name('getSteps')->return('array') ); $steps = array_map(function (StepSpecification $stepSpecification) { $stepTemplate = StepTemplate::bySpecification($stepSpecification); if ($stepSpecification->hasTakingModifier()) { $this->addMethod( $this->createTakingModifier($stepSpecification) ); } if ($stepSpecification->hasAnsweredModifier()) { $this->addMethod( $this->createAnsweredModifier($stepSpecification) ); } return $stepTemplate; }, $specification->getSteps()); $method->body( Block::return(Value::array($steps)) ); } private function createTakingModifier(StepSpecification $specification): ClassMethod { $stepName = "taking" . Str::studly($specification->getName()); return ClassMethod::name($stepName)->addArgument( Argument::name('step')->type(new Importable(Step::class)) ); } private function createAnsweredModifier(StepSpecification $specification): ClassMethod { $stepName = "answered" . Str::studly($specification->getName()); $argumentName = Str::camel($specification->getName()); return ClassMethod::name($stepName)->withArguments([ Argument::name('step')->type(new Importable(Step::class)), Argument::name($argumentName) ])->body( Block::return(Reference::variable($argumentName)) ); } private function getCompletedMethod(): ClassMethod { return ClassMethod::name('completed')->body( Block::return( Block::invokeMethod( Reference::objectProperty(Reference::this(), 'answers'), 'all' ) ) ); } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Contracts/Step.php
src/Contracts/Step.php
<?php namespace Shomisha\LaravelConsoleWizard\Contracts; interface Step { public function take(Wizard $wizard); }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Contracts/ValidatesWizard.php
src/Contracts/ValidatesWizard.php
<?php namespace Shomisha\LaravelConsoleWizard\Contracts; interface ValidatesWizard { public function getRules(): array; public function onWizardInvalid(array $errors); }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Contracts/Wizard.php
src/Contracts/Wizard.php
<?php namespace Shomisha\LaravelConsoleWizard\Contracts; interface Wizard extends Step { }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Contracts/RepeatsInvalidSteps.php
src/Contracts/RepeatsInvalidSteps.php
<?php namespace Shomisha\LaravelConsoleWizard\Contracts; interface RepeatsInvalidSteps extends ValidatesWizardSteps { }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Contracts/ValidatesWizardSteps.php
src/Contracts/ValidatesWizardSteps.php
<?php namespace Shomisha\LaravelConsoleWizard\Contracts; interface ValidatesWizardSteps { public function getRules(): array; }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Exception/InvalidStepException.php
src/Exception/InvalidStepException.php
<?php namespace Shomisha\LaravelConsoleWizard\Exception; class InvalidStepException extends \Exception { }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Exception/InvalidClassSpecificationException.php
src/Exception/InvalidClassSpecificationException.php
<?php namespace Shomisha\LaravelConsoleWizard\Exception; class InvalidClassSpecificationException extends \Exception { public static function missingName(): self { return self::missingParameter('name'); } public static function missingSignature(): self { return self::missingParameter('signature'); } private static function missingParameter(string $parameter): self { return new self("The class specification is missing a parameter: {$parameter}"); } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Exception/SubwizardException.php
src/Exception/SubwizardException.php
<?php namespace Shomisha\LaravelConsoleWizard\Exception; class SubwizardException extends \Exception { public static function completedMethodShouldNotBeCalled(): self { return new self("Subwizard::completed() method should not be called."); } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Exception/AbortWizardException.php
src/Exception/AbortWizardException.php
<?php namespace Shomisha\LaravelConsoleWizard\Exception; use Throwable; class AbortWizardException extends \Exception { protected $message = "Wizard abortion initiated by client."; private ?string $userMessage = null; public function __construct(string $userMessage = null, $code = 0, Throwable $previous = null) { parent::__construct(null, $code, $previous); $this->userMessage = $userMessage; } public function getUserMessage() { return $this->userMessage; } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Exception/InvalidStepSpecificationException.php
src/Exception/InvalidStepSpecificationException.php
<?php namespace Shomisha\LaravelConsoleWizard\Exception; class InvalidStepSpecificationException extends \Exception { public static function missingName(): self { return self::missingParameter('name'); } public static function missingType(): self { return self::missingParameter('type'); } public static function missingQuestion(): self { return self::missingParameter('question'); } private static function missingParameter(string $parameter): self { return new self("The step specification is missing a parameter: {$parameter}"); } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/DataTransfer/Specification.php
src/DataTransfer/Specification.php
<?php namespace Shomisha\LaravelConsoleWizard\DataTransfer; use Illuminate\Support\Arr; abstract class Specification { private array $specification; public function __construct(array $specification) { $this->assertSpecificationIsValid($specification); $this->specification = $specification; } public static function fromArray(array $specification): self { return new static($specification); } abstract protected function assertSpecificationIsValid(array $specification); protected function extract(string $key) { return Arr::get($this->specification, $key); } protected function place(string $key, $value): self { $this->specification[$key] = $value; return $this; } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/DataTransfer/StepSpecification.php
src/DataTransfer/StepSpecification.php
<?php namespace Shomisha\LaravelConsoleWizard\DataTransfer; use Shomisha\LaravelConsoleWizard\Exception\InvalidStepSpecificationException; use Shomisha\LaravelConsoleWizard\Steps\ChoiceStep; use Shomisha\LaravelConsoleWizard\Steps\MultipleChoiceStep; use Shomisha\LaravelConsoleWizard\Steps\UniqueMultipleChoiceStep; class StepSpecification extends Specification { private const KEY_NAME = 'name'; private const KEY_QUESTION = 'question'; private const KEY_TYPE = 'type'; private const KEY_OPTIONS = 'step-data.options'; private const KEY_TAKING_MODIFIER = 'has_taking_modifier'; private const KEY_ANSWERED_MODIFIER = 'has_answered_modifier'; private const STEPS_WITH_OPTIONS = [ ChoiceStep::class, MultipleChoiceStep::class, UniqueMultipleChoiceStep::class, ]; public function getName(): string { return $this->extract(self::KEY_NAME); } public function getType(): string { return $this->extract(self::KEY_TYPE); } public function getQuestion(): string { return $this->extract(self::KEY_QUESTION); } public function hasOptions(): bool { if (empty($this->getOptions())) { return false; } return $this->stepShouldHaveOptions(); } public function stepShouldHaveOptions(): bool { return in_array($this->getType(), self::STEPS_WITH_OPTIONS); } public function getOptions(): ?array { return $this->extract(self::KEY_OPTIONS); } public function hasTakingModifier(): bool { return $this->extract(self::KEY_TAKING_MODIFIER); } public function hasAnsweredModifier(): bool { return $this->extract(self::KEY_ANSWERED_MODIFIER); } protected function assertSpecificationIsValid(array $specification): void { if (!array_key_exists(self::KEY_NAME, $specification)) { throw InvalidStepSpecificationException::missingName(); } if (!array_key_exists(self::KEY_TYPE, $specification)) { throw InvalidStepSpecificationException::missingType(); } if (!array_key_exists(self::KEY_QUESTION, $specification)) { throw InvalidStepSpecificationException::missingQuestion(); } } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/DataTransfer/WizardSpecification.php
src/DataTransfer/WizardSpecification.php
<?php namespace Shomisha\LaravelConsoleWizard\DataTransfer; use Shomisha\LaravelConsoleWizard\Command\GeneratorWizard; use Shomisha\LaravelConsoleWizard\Exception\InvalidClassSpecificationException; class WizardSpecification extends Specification { const KEY_NAMESPACE = 'namespace'; const KEY_CLASS_NAME = GeneratorWizard::NAME_STEP_NAME; const KEY_SIGNATURE = 'signature'; const KEY_DESCRIPTION = 'description'; private array $stepSpecifications; public function __construct(array $specification) { parent::__construct($specification); $this->initializeSteps($this->extract('steps')); } public function getName(): string { return $this->extract(self::KEY_CLASS_NAME); } public function setName(string $name): self { return $this->place(self::KEY_CLASS_NAME, $name); } public function getSignature(): string { return $this->extract(self::KEY_SIGNATURE); } public function getDescription(): ?string { return $this->extract(self::KEY_DESCRIPTION); } /** @return \Shomisha\LaravelConsoleWizard\DataTransfer\StepSpecification[] */ public function getSteps(): array { return $this->stepSpecifications; } public function getNamespace(): ?string { return $this->extract(self::KEY_NAMESPACE); } public function setNamespace(?string $namespace): self { return $this->place(self::KEY_NAMESPACE, $namespace); } protected function assertSpecificationIsValid(array $specification): void { if (!array_key_exists(self::KEY_CLASS_NAME, $specification)) { InvalidClassSpecificationException::missingName(); } if (!array_key_exists(self::KEY_SIGNATURE, $specification)) { InvalidClassSpecificationException::missingSignature(); } } private function initializeSteps(array $steps): void { $this->stepSpecifications = collect($steps)->mapWithKeys(function (array $step) { $specification = StepSpecification::fromArray($step); return [ $specification->getName() => $specification ]; })->toArray(); } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Concerns/WizardCore.php
src/Concerns/WizardCore.php
<?php namespace Shomisha\LaravelConsoleWizard\Concerns; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Str; use Illuminate\Validation\ValidationException; use Shomisha\LaravelConsoleWizard\Contracts\RepeatsInvalidSteps; use Shomisha\LaravelConsoleWizard\Contracts\Step; use Shomisha\LaravelConsoleWizard\Contracts\ValidatesWizard; use Shomisha\LaravelConsoleWizard\Contracts\ValidatesWizardSteps; use Shomisha\LaravelConsoleWizard\Contracts\Wizard; use Shomisha\LaravelConsoleWizard\Exception\AbortWizardException; use Shomisha\LaravelConsoleWizard\Exception\InvalidStepException; use Shomisha\LaravelConsoleWizard\Steps\RepeatStep; /** @mixin \Shomisha\LaravelConsoleWizard\Command\Wizard */ trait WizardCore { protected Collection $steps; protected Collection $taken; protected Collection $answers; protected Collection $followup; protected Collection $skipped; protected bool $inheritAnswersFromArguments = false; protected function initializeSteps() { $this->assertStepsAreValid($steps = $this->getSteps()); $this->steps = collect($steps); $this->taken = collect([]); $this->followup = collect([]); $this->skipped = collect([]); } final public function take(Wizard $wizard) { while ($this->steps->isNotEmpty()) { [$name, $step] = $this->getNextStep(); $this->taking($step, $name); $answer = $this->getStepAnswer($name, $step); if ($this->shouldValidateStep($name)) { try { $this->validateStep($name, $answer); } catch (ValidationException $e) { $this->handleInvalidAnswer($name, $step, $answer, $e); } } $this->answered($step, $name, $answer); } return $this->answers->toArray(); } final public function initializeWizard() { $this->initializeSteps(); $this->initializeAnswers(); } final protected function handleWizard() { $this->initializeWizard(); $this->take($this); if ($this->shouldValidateWizard()) { try { $this->validateWizard(); } catch (ValidationException $e) { $this->onWizardInvalid($e->errors()); } } } final protected function subWizard(Wizard $wizard) { $wizard->output = $this->output; $wizard->input = $this->input; $wizard->initializeWizard(); return $wizard; } final protected function repeat(Step $step) { return new RepeatStep($step); } final protected function followUp(string $name, Step $step) { $this->followup->put($name, $step); return $this; } final protected function repeatStep(string $name): ?Step { $step = $this->findStep($name); if ($step !== null) { $this->followUp($name, $step); } return $step; } final protected function skip(string $name) { $step = $this->steps->pull($name); if ($step !== null) { $this->skipped->put($name, $step); } } final protected function abort(string $message = null) { throw new AbortWizardException($message); } final protected function assertStepsAreValid(array $steps) { foreach ($steps as $step) { if (! ($step instanceof Step)) { $message = sprintf( "%s does not implement the %s interface", get_class($step), Step::class ); throw new InvalidStepException($message); } } } private function abortWizard(AbortWizardException $e): void { if ($message = $e->getUserMessage()) { $this->error($message); } } private function initializeAnswers() { $this->answers = collect([]); } private function getNextStep(): array { return [ $this->steps->keys()->first(), $this->steps->shift(), ]; } private function taking(Step $step, string $name) { if ($this->hasTakingModifier($name)) { $this->{$this->guessTakingModifier($name)}($step); } } private function hasTakingModifier(string $name) { return method_exists($this, $this->guessTakingModifier($name)); } private function guessTakingModifier(string $name) { return sprintf('taking%s', Str::studly($name)); } private function getStepAnswer(string $name, Step $step) { if ($this->inheritAnswersFromArguments) { if ($answer = $this->arguments()[$name] ?? null) { return $answer; } if ($answer = $this->options()[$name] ?? null) { return $answer; } } return $step->take($this); } private function answered(Step $step, string $name, $answer) { if ($this->hasAnsweredModifier($name)) { $answer = $this->{$this->guessAnsweredModifier($name)}($step, $answer); } $this->addAnswer($name, $answer); $this->moveStepToTaken($name, $step); $this->flushFollowups(); } private function hasAnsweredModifier(string $name) { return method_exists($this, $this->guessAnsweredModifier($name)); } private function guessAnsweredModifier(string $name) { return sprintf('answered%s', Str::studly($name)); } private function addAnswer(string $name, $answer) { $this->answers->put($name, $answer); } private function moveStepToTaken(string $name, Step $step) { $this->taken->put($name, $step); } private function flushFollowups() { $this->steps = collect(array_merge( $this->followup->reverse()->toArray(), $this->steps->toArray() )); $this->followup = collect([]); } private function shouldValidateWizard() { return $this instanceof ValidatesWizard; } private function validateWizard() { return $this->validate($this->answers->toArray(), $this->getRules()); } private function shouldValidateStep(string $name) { return $this instanceof ValidatesWizardSteps && array_key_exists($name, $this->getRules()); } private function validateStep(string $name, $answer) { return $this->validate( [$name => $answer], [$name => $this->getRules()[$name]] ); } private function handleInvalidAnswer(string $name, Step $step, $answer, ValidationException $e): void { if ($this->hasFailedValidationHandler($name)) { $this->runFailedValidationHandler($name, $e, $answer); return; } elseif ($this->shouldRepeatInvalidSteps()) { $this->error($e->errors()[$name][0]); $this->followUp($name, $step); return; } throw $e; } private function validate(array $data, array $rules) { return Validator::make($data, $rules)->validate(); } private function shouldRepeatInvalidSteps(): bool { return $this instanceof RepeatsInvalidSteps; } private function hasFailedValidationHandler(string $name) { return method_exists($this, $this->guessValidationFailedHandlerName($name)); } private function runFailedValidationHandler(string $name, ValidationException $exception, $answer): void { $this->{$this->guessValidationFailedHandlerName($name)}($answer, $exception->errors()[$name]); } private function guessValidationFailedHandlerName(string $name) { return sprintf("onInvalid%s", Str::studly($name)); } private function findStep(string $name): ?Step { $step = $this->taken->get($name); if ($step === null) { $step = $this->skipped->get($name); } return $step; } public function refill() { $this->initializeWizard(); } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Steps/UniqueMultipleChoiceStep.php
src/Steps/UniqueMultipleChoiceStep.php
<?php namespace Shomisha\LaravelConsoleWizard\Steps; use Shomisha\LaravelConsoleWizard\Contracts\Wizard; class UniqueMultipleChoiceStep extends BaseMultipleAnswerStep { private array $choices; public function __construct(string $text, array $choices, array $options = []) { parent::__construct($text, $options); $this->choices = $choices; } final public function take(Wizard $wizard) { $options = array_merge($this->choices, [$this->endKeyword]); $answers = $this->loop(function () use ($wizard, &$options) { $newAnswer = $wizard->choice($this->text, $options); $this->removeChoiceFromOptions($newAnswer, $options); return $newAnswer; }); if ($this->shouldRemoveEndKeyword($answers)) { array_pop($answers); } return $answers; } final protected function removeChoiceFromOptions($choice, &$options) { unset($options[array_search($choice, $options)]); } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Steps/BaseStep.php
src/Steps/BaseStep.php
<?php namespace Shomisha\LaravelConsoleWizard\Steps; use Shomisha\LaravelConsoleWizard\Contracts\Step; abstract class BaseStep implements Step { protected string $text; public function __construct(string $text) { $this->text = $text; } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Steps/ConfirmStep.php
src/Steps/ConfirmStep.php
<?php namespace Shomisha\LaravelConsoleWizard\Steps; use Shomisha\LaravelConsoleWizard\Contracts\Wizard; class ConfirmStep extends BaseStep { private $defaultAnswer; public function __construct(string $text, $defaultAnswer = false) { parent::__construct($text); $this->defaultAnswer = $defaultAnswer; } public function take(Wizard $wizard) { return $wizard->confirm($this->text, $this->getDefaultAnswer()); } private function getDefaultAnswer(): bool { if (is_callable($this->defaultAnswer)) { return (bool) ($this->defaultAnswer)(); } return (bool) $this->defaultAnswer; } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Steps/ChoiceStep.php
src/Steps/ChoiceStep.php
<?php namespace Shomisha\LaravelConsoleWizard\Steps; use Shomisha\LaravelConsoleWizard\Contracts\Wizard; class ChoiceStep extends BaseStep { private array $options; public function __construct(string $text, array $options) { parent::__construct($text); $this->options = $options; } final public function take(Wizard $wizard) { return $wizard->choice($this->text, $this->options); } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Steps/MultipleChoiceStep.php
src/Steps/MultipleChoiceStep.php
<?php namespace Shomisha\LaravelConsoleWizard\Steps; use Shomisha\LaravelConsoleWizard\Contracts\Wizard; class MultipleChoiceStep extends BaseMultipleAnswerStep { private array $choices; public function __construct(string $text, array $choices, array $options = []) { parent::__construct($text, $options); $this->choices = $choices; } final public function take(Wizard $wizard) { $options = array_merge($this->choices, [$this->endKeyword]); $answers = $this->loop(function () use ($wizard, $options) { return $wizard->choice($this->text, $options); }); if ($this->shouldRemoveEndKeyword($answers)) { array_pop($answers); } return $answers; } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Steps/OneTimeWizard.php
src/Steps/OneTimeWizard.php
<?php namespace Shomisha\LaravelConsoleWizard\Steps; use Shomisha\LaravelConsoleWizard\Command\Wizard; class OneTimeWizard extends Wizard { private array $multiValueSteps; public function __construct(array $steps) { parent::__construct(); $this->assertStepsAreValid($steps); $this->multiValueSteps = $steps; } function getSteps(): array { return $this->multiValueSteps; } function completed() { throw new \RuntimeException('One time wizard cannot reach the completed method.'); } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Steps/BaseMultipleAnswerStep.php
src/Steps/BaseMultipleAnswerStep.php
<?php namespace Shomisha\LaravelConsoleWizard\Steps; abstract class BaseMultipleAnswerStep extends BaseStep { protected string $endKeyword; protected bool $retainEndKeywordInAnswers; protected int $repetitions = 0; protected ?int $maxRepetitions = null; public function __construct(string $text, array $options = []) { parent::__construct($text); $this->endKeyword = $options['end_keyword'] ?? 'Done'; $this->retainEndKeywordInAnswers = $options['retain_end_keyword'] ?? false; $this->maxRepetitions = $options['max_repetitions'] ?? null; } protected function loop(callable $callback) { $answers = []; do { $newAnswer = $callback(); $answers[] = $newAnswer; $this->incrementRepetitions(); } while ($this->shouldKeepLooping($newAnswer)); return $answers; } protected function shouldKeepLooping($answer) { return strtolower($answer) !== strtolower($this->endKeyword) && !$this->hasExceededMaxRepetitions(); } protected function incrementRepetitions() { $this->repetitions++; return $this; } protected function hasExceededMaxRepetitions() { return $this->maxRepetitions !== null && $this->repetitions >= $this->maxRepetitions; } protected function shouldRemoveEndKeyword(array $answers) { return !$this->retainEndKeywordInAnswers && strtolower(last($answers)) === strtolower($this->endKeyword); } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Steps/TextStep.php
src/Steps/TextStep.php
<?php namespace Shomisha\LaravelConsoleWizard\Steps; use Shomisha\LaravelConsoleWizard\Contracts\Wizard; class TextStep extends BaseStep { final public function take(Wizard $wizard) { return $wizard->ask($this->text); } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Steps/MultipleAnswerTextStep.php
src/Steps/MultipleAnswerTextStep.php
<?php namespace Shomisha\LaravelConsoleWizard\Steps; use Shomisha\LaravelConsoleWizard\Contracts\Wizard; class MultipleAnswerTextStep extends BaseMultipleAnswerStep { final public function take(Wizard $wizard) { $wizard->line($this->text); $answers = $this->loop(function () use ($wizard) { return readline(); }); if ($this->shouldRemoveEndKeyword($answers)) { array_pop($answers); } return $answers; } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Steps/RepeatStep.php
src/Steps/RepeatStep.php
<?php namespace Shomisha\LaravelConsoleWizard\Steps; use Shomisha\LaravelConsoleWizard\Contracts\Step; use Shomisha\LaravelConsoleWizard\Contracts\Wizard; use Shomisha\LaravelConsoleWizard\Exception\InvalidStepException; class RepeatStep implements Step { private Wizard $wizard; private int $counter = 0; private $callback = null; private Step $step; private bool $excludeLast = false; public function __construct(Step $step) { $this->step = $step; } public function take(Wizard $wizard) { if ($this->callback === null) { throw new InvalidStepException( "The RepeatStep has not been properly initialized. Please call either RepeatStep::times() or RepeatStep::until() to initialize it." ); } $this->wizard = $wizard; $answers = []; $answer = null; while (call_user_func($this->callback, $answer)) { $answer = $this->step->take($this->wizard); $answers[] = $answer; $this->counter++; if ($this->shouldRefillStep()) { $this->refillStep(); } } if ($this->excludeLast) { array_pop($answers); } return $answers; } public function times(int $times) { return $this->until(function () use ($times) { return $this->counter == $times; }); } public function untilAnswerIs($answer, int $maxRepetitions = null) { return $this->until(function ($actualAnswer) use ($answer) { if ($this->isFirstRun()) { return false; } return $actualAnswer === $answer; }, $maxRepetitions); } public function withRepeatPrompt(string $question, bool $askOnFirstRun = false, bool $defaultAnswer = false) { return $this->until(function ($answer) use ($question, $askOnFirstRun, $defaultAnswer) { if ($this->isFirstRun() && !$askOnFirstRun) { return false; } return !(new ConfirmStep($question, $defaultAnswer))->take($this->wizard); }); } public function until(callable $callback, int $maxRepetitions = null) { $this->callback = function ($answer) use ($callback, $maxRepetitions) { if ($callback($answer)) { return false; } if ($this->hasExceededMaxRepetitions($maxRepetitions)) { return false; } return true; }; return $this; } public function withLastAnswer() { return $this->setExcludeLast(false); } public function withoutLastAnswer() { return $this->setExcludeLast(true); } public function setExcludeLast(bool $excludeLast) { $this->excludeLast = $excludeLast; return $this; } private function hasExceededMaxRepetitions($maxRepetitions) { return $maxRepetitions !== null && $this->counter >= $maxRepetitions; } private function shouldRefillStep() { return $this->step instanceof Wizard; } private function refillStep() { return $this->step->refill(); } private function isFirstRun() { return $this->counter === 0; } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Command/Subwizard.php
src/Command/Subwizard.php
<?php namespace Shomisha\LaravelConsoleWizard\Command; use Shomisha\LaravelConsoleWizard\Exception\SubwizardException; abstract class Subwizard extends Wizard { final function completed() { throw SubwizardException::completedMethodShouldNotBeCalled(); } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Command/GeneratorWizard.php
src/Command/GeneratorWizard.php
<?php namespace Shomisha\LaravelConsoleWizard\Command; use Illuminate\Console\GeneratorCommand; use Shomisha\LaravelConsoleWizard\Concerns\WizardCore; use Shomisha\LaravelConsoleWizard\Contracts\Step; use Shomisha\LaravelConsoleWizard\Contracts\Wizard as WizardContract; use Shomisha\LaravelConsoleWizard\Exception\AbortWizardException; abstract class GeneratorWizard extends GeneratorCommand implements Step, WizardContract { use WizardCore { initializeSteps as parentInitializeSteps; } const NAME_STEP_NAME = 'name_'; public function handle() { try { $this->handleWizard(); } catch (AbortWizardException $e) { return $this->abortWizard($e); } return parent::handle(); } protected function initializeSteps() { $this->parentInitializeSteps(); $this->steps->prepend($this->getNameStep(), self::NAME_STEP_NAME); } abstract protected function getNameStep(): Step; abstract protected function generateTarget(): string; final protected function getNameInput() { return $this->answers->get(self::NAME_STEP_NAME); } final protected function getClassFullName(): string { return $this->qualifyClass($this->getNameInput()); } final protected function getClassShortName(): string { $name = $this->getNameInput(); $class = str_replace($this->getNamespace($name).'\\', '', $name); return $class; } final protected function getClassNamespace(): string { return $this->getNamespace($this->getClassFullName()); } final protected function buildClass($name) { return $this->generateTarget(); } final protected function getStub() { return; } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Command/Wizard.php
src/Command/Wizard.php
<?php namespace Shomisha\LaravelConsoleWizard\Command; use Illuminate\Console\Command; use Shomisha\LaravelConsoleWizard\Concerns\WizardCore; use Shomisha\LaravelConsoleWizard\Contracts\Wizard as WizardContract; use Shomisha\LaravelConsoleWizard\Exception\AbortWizardException; abstract class Wizard extends Command implements WizardContract { use WizardCore; public function __construct() { parent::__construct(); } final public function handle() { try { $this->handleWizard(); } catch (AbortWizardException $e) { return $this->abortWizard($e); } $this->completed(); } abstract function getSteps(): array; abstract function completed(); }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Command/Generators/GenerateWizardWizard.php
src/Command/Generators/GenerateWizardWizard.php
<?php namespace Shomisha\LaravelConsoleWizard\Command\Generators; use Shomisha\LaravelConsoleWizard\Command\Generators\Subwizards\StepSubwizard; use Shomisha\LaravelConsoleWizard\Command\GeneratorWizard; use Shomisha\LaravelConsoleWizard\Contracts\Step; use Shomisha\LaravelConsoleWizard\DataTransfer\WizardSpecification; use Shomisha\LaravelConsoleWizard\Steps\TextStep; use Shomisha\LaravelConsoleWizard\Templates\WizardTemplate; class GenerateWizardWizard extends GeneratorWizard { protected $signature = 'wizard:generate'; protected $type = 'Wizard'; function getSteps(): array { return [ 'signature' => new TextStep("Enter the signature for your wizard"), 'description' => new TextStep("Enter the description for your wizard"), 'steps' => $this->repeat( $this->subWizard(new StepSubwizard()) )->withRepeatPrompt("Do you want to add a wizard step?", true), ]; } protected function getNameStep(): Step { return new TextStep("Enter the class name for your wizard"); } protected function generateTarget(): string { $specification = WizardSpecification::fromArray($this->answers->all()) ->setName($this->getClassShortName()) ->setNamespace($this->getClassNamespace()); return WizardTemplate::bySpecification($specification)->print(); } protected function getDefaultNamespace($rootNamespace) { return $rootNamespace . "\Console\Command"; } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Command/Generators/Subwizards/MultipleChoiceOptionsSubwizard.php
src/Command/Generators/Subwizards/MultipleChoiceOptionsSubwizard.php
<?php namespace Shomisha\LaravelConsoleWizard\Command\Generators\Subwizards; use Shomisha\LaravelConsoleWizard\Command\Subwizard; use Shomisha\LaravelConsoleWizard\Steps\TextStep; class MultipleChoiceOptionsSubwizard extends Subwizard { function getSteps(): array { return [ 'options' => $this->repeat(new TextStep("Add option for multiple choice (enter 'stop' to stop)"))->untilAnswerIs('stop')->withoutLastAnswer(), ]; } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/src/Command/Generators/Subwizards/StepSubwizard.php
src/Command/Generators/Subwizards/StepSubwizard.php
<?php namespace Shomisha\LaravelConsoleWizard\Command\Generators\Subwizards; use Shomisha\LaravelConsoleWizard\Command\Subwizard; use Shomisha\LaravelConsoleWizard\Contracts\Step; use Shomisha\LaravelConsoleWizard\Steps\ChoiceStep; use Shomisha\LaravelConsoleWizard\Steps\ConfirmStep; use Shomisha\LaravelConsoleWizard\Steps\MultipleAnswerTextStep; use Shomisha\LaravelConsoleWizard\Steps\MultipleChoiceStep; use Shomisha\LaravelConsoleWizard\Steps\TextStep; use Shomisha\LaravelConsoleWizard\Steps\UniqueMultipleChoiceStep; class StepSubwizard extends Subwizard { private array $stepTypes = [ 'Text step' => TextStep::class, 'Multiple answer text step' => MultipleAnswerTextStep::class, 'Choice step' => ChoiceStep::class, 'Multiple choice step' => MultipleChoiceStep::class, 'Unique multiple choice step' => UniqueMultipleChoiceStep::class, 'Confirm step' => ConfirmStep::class, ]; private array $stepSubwizards = [ ChoiceStep::class => MultipleChoiceOptionsSubwizard::class, MultipleChoiceStep::class => MultipleChoiceOptionsSubwizard::class, UniqueMultipleChoiceStep::class => MultipleChoiceOptionsSubwizard::class, ]; function getSteps(): array { return [ 'name' => new TextStep("Enter step name"), 'question' => new TextStep("Enter step question"), 'type' => new ChoiceStep("Choose step type", array_keys($this->stepTypes)), 'has_taking_modifier' => new ConfirmStep("Do you want a 'taking' modifier method for this step?"), 'has_answered_modifier' => new ConfirmStep("Do you want an 'answered' modifier method for this step?"), ]; } public function answeredType(Step $step, string $type) { $type = $this->stepTypes[$type]; if ($followUp = $this->guessFollowUp($type)) { $this->followUp( 'step-data', $this->subWizard($followUp) ); } return $type; } private function guessFollowUp(string $type): ?Subwizard { $followUpClass = $this->stepSubwizards[$type] ?? null; if ($followUpClass) { return new $followUpClass; } return null; } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/tests/LaravelConsoleWizardTestsServiceProvider.php
tests/LaravelConsoleWizardTestsServiceProvider.php
<?php namespace Shomisha\LaravelConsoleWizard\Test; use Illuminate\Support\ServiceProvider; use Shomisha\LaravelConsoleWizard\Command\Generators\GenerateWizardWizard; use Shomisha\LaravelConsoleWizard\Test\TestWizards\AbortWizardTest; use Shomisha\LaravelConsoleWizard\Test\TestWizards\BaseTestWizard; use Shomisha\LaravelConsoleWizard\Test\TestWizards\InheritAnswersTestWizard; use Shomisha\LaravelConsoleWizard\Test\TestWizards\RepeatsStepsTestWizard; use Shomisha\LaravelConsoleWizard\Test\TestWizards\StepValidationTestWizard; use Shomisha\LaravelConsoleWizard\Test\TestWizards\SubwizardTestWizard; use Shomisha\LaravelConsoleWizard\Test\TestWizards\WizardValidationTestWizard; use Shomisha\LaravelConsoleWizard\Test\TestWizards\WizardWithOneTimeSubwizard; class LaravelConsoleWizardTestsServiceProvider extends ServiceProvider { public function boot() { } public function register() { $this->commands( BaseTestWizard::class, SubwizardTestWizard::class, StepValidationTestWizard::class, WizardValidationTestWizard::class, WizardWithOneTimeSubwizard::class, GenerateWizardWizard::class, RepeatsStepsTestWizard::class, InheritAnswersTestWizard::class, AbortWizardTest::class, ); } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/tests/TestCase.php
tests/TestCase.php
<?php namespace Shomisha\LaravelConsoleWizard\Test; use Orchestra\Testbench\TestCase as OrchestraTestCase; use Shomisha\LaravelConsoleWizard\LaravelConsoleWizardServiceProvider; class TestCase extends OrchestraTestCase { protected function getPackageProviders($app) { return [ LaravelConsoleWizardTestsServiceProvider::class, ]; } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/tests/TestWizards/Subwizard.php
tests/TestWizards/Subwizard.php
<?php namespace Shomisha\LaravelConsoleWizard\Test\TestWizards; use Shomisha\LaravelConsoleWizard\Command\Wizard; use Shomisha\LaravelConsoleWizard\Steps\ConfirmStep; use Shomisha\LaravelConsoleWizard\Steps\TextStep; class Subwizard extends Wizard { function getSteps(): array { return [ 'age-legality' => new ConfirmStep("Are you older than 18?"), 'marital-legality' => new TextStep("Your marital status:"), ]; } function completed() { } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/tests/TestWizards/WizardValidationTestWizard.php
tests/TestWizards/WizardValidationTestWizard.php
<?php namespace Shomisha\LaravelConsoleWizard\Test\TestWizards; use Shomisha\LaravelConsoleWizard\Command\Wizard; use Shomisha\LaravelConsoleWizard\Contracts\ValidatesWizard; use Shomisha\LaravelConsoleWizard\Steps\TextStep; class WizardValidationTestWizard extends Wizard implements ValidatesWizard { protected $signature = 'console-wizard-test:wizard-validation'; public function getRules(): array { return [ 'favourite_band' => ['string', 'in:Kings of Leon,Milo Greene'], 'country' => ['string', 'in:Serbia,England,Croatia,France'], ]; } public function onWizardInvalid(array $errors) { $this->abort("Your wizard is invalid"); } function getSteps(): array { return [ 'name' => new TextStep('What is your name?'), 'favourite_band' => new TextStep('What is your favourite band?'), 'country' => new TextStep('Which country do you come from?'), ]; } function completed() { } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/tests/TestWizards/InheritAnswersTestWizard.php
tests/TestWizards/InheritAnswersTestWizard.php
<?php namespace Shomisha\LaravelConsoleWizard\Test\TestWizards; use Shomisha\LaravelConsoleWizard\Command\Wizard; use Shomisha\LaravelConsoleWizard\Steps\TextStep; class InheritAnswersTestWizard extends Wizard { protected $signature = "wizard-test:inherit-answers {name?} {--age=}"; protected bool $inheritAnswersFromArguments = true; function getSteps(): array { return [ 'name' => new TextStep('Name'), 'age' => new TextStep('Age'), ]; } function completed() { $this->info(sprintf( "%s is %s year(s) old", $this->answers->get('name'), $this->answers->get('age') )); } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/tests/TestWizards/StepValidationTestWizard.php
tests/TestWizards/StepValidationTestWizard.php
<?php namespace Shomisha\LaravelConsoleWizard\Test\TestWizards; use Shomisha\LaravelConsoleWizard\Command\Wizard; use Shomisha\LaravelConsoleWizard\Contracts\ValidatesWizardSteps; use Shomisha\LaravelConsoleWizard\Steps\TextStep; class StepValidationTestWizard extends Wizard implements ValidatesWizardSteps { protected $signature = 'console-wizard-test:step-validation'; public function getRules(): array { return [ 'age' => ['integer', 'min:18'], 'favourite_colour' => ['string', 'in:red,green,blue'], ]; } function getSteps(): array { return [ 'name' => new TextStep("What is your name?"), 'age' => new TextStep("How old are you?"), 'favourite_colour' => new TextStep("What is your favourite colour?"), ]; } public function onInvalidAge($answer, $errors) { $this->abort("The age you entered is invalid."); } function completed() { } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/tests/TestWizards/WizardWithOneTimeSubwizard.php
tests/TestWizards/WizardWithOneTimeSubwizard.php
<?php namespace Shomisha\LaravelConsoleWizard\Test\TestWizards; use Shomisha\LaravelConsoleWizard\Command\Wizard; use Shomisha\LaravelConsoleWizard\Steps\OneTimeWizard; use Shomisha\LaravelConsoleWizard\Steps\TextStep; class WizardWithOneTimeSubwizard extends Wizard { protected $signature = 'console-wizard-test:one-time-subwizard'; function getSteps(): array { return [ 'one-time-subwizard' => $this->subWizard(new OneTimeWizard([ 'first-question' => new TextStep('Answer the first step'), 'second-question' => new TextStep('Answer the second step'), ])), ]; } function completed() {} }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/tests/TestWizards/SubwizardTestWizard.php
tests/TestWizards/SubwizardTestWizard.php
<?php namespace Shomisha\LaravelConsoleWizard\Test\TestWizards; use Shomisha\LaravelConsoleWizard\Command\Wizard; use Shomisha\LaravelConsoleWizard\Steps\TextStep; class SubwizardTestWizard extends Wizard { protected $signature = 'console-wizard-test:subwizard'; function getSteps(): array { return [ 'name' => new TextStep("What's your name?"), 'legal-status' => $this->subWizard(new Subwizard()), ]; } function completed() { } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/tests/TestWizards/RepeatsStepsTestWizard.php
tests/TestWizards/RepeatsStepsTestWizard.php
<?php namespace Shomisha\LaravelConsoleWizard\Test\TestWizards; use Shomisha\LaravelConsoleWizard\Command\Wizard; use Shomisha\LaravelConsoleWizard\Contracts\RepeatsInvalidSteps; use Shomisha\LaravelConsoleWizard\Steps\TextStep; class RepeatsStepsTestWizard extends Wizard implements RepeatsInvalidSteps { protected $signature = "wizard-test:repeat-invalid"; function getSteps(): array { return [ 'age' => new TextStep("Enter age"), "birth_year" => new TextStep("Enter birth year"), ]; } public function getRules(): array { return [ "age" => ["integer", "min:10", "max:20"], "birth_year" => ["integer", "min:1990", "max:2000"], ]; } public function onInvalidBirthYear($step, $answer) { $this->error("Wrong answer, nimrod"); } function completed() { $this->info("Done"); } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/tests/TestWizards/BaseTestWizard.php
tests/TestWizards/BaseTestWizard.php
<?php namespace Shomisha\LaravelConsoleWizard\Test\TestWizards; use Shomisha\LaravelConsoleWizard\Command\Wizard; use Shomisha\LaravelConsoleWizard\Contracts\Step; use Shomisha\LaravelConsoleWizard\Steps\ChoiceStep; use Shomisha\LaravelConsoleWizard\Steps\TextStep; class BaseTestWizard extends Wizard { protected $signature = 'console-wizard-test:base'; function getSteps(): array { return [ 'name' => new TextStep("What's your name?"), 'age' => new TextStep("How old are you?"), 'preferred-language' => new ChoiceStep( 'Your favourite programming language', [ 'PHP', 'JavaScript', 'Python', 'Java', 'C#', 'Go', ] ), ]; } public function askingUnskippable() { $this->skip('unskippable'); } public function answeredUnskippable() { $this->skip('skip-me'); } public function takingRunAnother() { $this->followup('followup', new TextStep("I am a followup.")); } public function answeredRepeatAfterMe(Step $step, $shouldRepeat) { $this->repeatStep('repeat_me'); } public function takingMainStep() { $this->followup('pre-main-step', new TextStep('I am added before the main step')); } public function answeredMainStep() { $this->followup('post-main-step', new TextStep('I am added after the main step')); } public function takingName() { } public function takingAge() { } public function answeredAge(Step $question, $answer) { return $answer; } public function answeredPreferredLanguage(Step $question, $answer) { return $answer; } public function getAnswers() { return $this->answers; } function completed() { return $this->answers; } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/tests/TestWizards/AbortWizardTest.php
tests/TestWizards/AbortWizardTest.php
<?php namespace Shomisha\LaravelConsoleWizard\Test\TestWizards; use Shomisha\LaravelConsoleWizard\Command\Wizard; use Shomisha\LaravelConsoleWizard\Contracts\Step; use Shomisha\LaravelConsoleWizard\Steps\ConfirmStep; use Shomisha\LaravelConsoleWizard\Steps\TextStep; class AbortWizardTest extends Wizard { protected $signature = 'wizard:abort'; function getSteps(): array { return [ 'abort' => new ConfirmStep('Should I abort?'), 'why' => new TextStep("Why didn't you abort?"), ]; } public function answeredAbort(Step $step, bool $abort) { if ($abort) { $this->abort("I am aborting"); } return $abort; } function completed() { } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/tests/Unit/GenerateWizardWizardTest.php
tests/Unit/GenerateWizardWizardTest.php
<?php namespace Shomisha\LaravelConsoleWizard\Test\Unit; use Illuminate\Contracts\Filesystem\Filesystem; use Illuminate\Support\Facades\Storage; use Shomisha\LaravelConsoleWizard\Test\TestCase; class GenerateWizardWizardTest extends TestCase { private Filesystem $disk; protected function path(): string { return base_path('app'); } protected function setUp(): void { parent::setUp(); $this->disk = Storage::build([ 'driver' => 'local', 'root' => $this->path(), ]); } protected function tearDown(): void { $this->app['files']->deleteDirectory($this->path()); parent::tearDown(); } /** @test */ public function command_can_generate_wizard() { $this->artisan('wizard:generate') ->expectsQuestion("Enter the class name for your wizard", 'TestWizard') ->expectsQuestion("Enter the signature for your wizard", "wizard:test") ->expectsQuestion('Enter the description for your wizard', 'This is a test wizard.') ->expectsConfirmation("Do you want to add a wizard step?", 'no'); $generatedWizard = $this->disk->get('Console/Command/TestWizard.php'); $this->assertIsString($generatedWizard); $this->assertStringContainsString('namespace App\Console\Command;', $generatedWizard); $this->assertStringContainsString('use Shomisha\LaravelConsoleWizard\Command\Wizard;', $generatedWizard); $this->assertStringContainsString('class TestWizard extends Wizard', $generatedWizard); $this->assertStringContainsString("protected \$signature = 'wizard:test';", $generatedWizard); $this->assertStringContainsString("protected \$description = 'This is a test wizard.';", $generatedWizard); $this->assertStringContainsString("public function getSteps() : array\n {\n return array();\n }\n", $generatedWizard); $this->assertStringContainsString("public function completed()\n {\n return \$this->answers->all();\n }", $generatedWizard); } /** @test */ public function command_can_generate_wizard_with_steps() { $stepTypeChoices = [ 0 => 'Text step', 1 => 'Multiple answer text step', 2 => 'Choice step', 3 => 'Multiple choice step', 4 => 'Unique multiple choice step', 5 => 'Confirm step', ]; $this->artisan('wizard:generate') ->expectsQuestion('Enter the class name for your wizard', 'TestWizardWithSteps') ->expectsQuestion('Enter the signature for your wizard', 'wizard:test-with-steps') ->expectsQuestion('Enter the description for your wizard', 'This is a test wizard with steps.') ->expectsConfirmation('Do you want to add a wizard step?', 'yes') ->expectsQuestion('Enter step name', 'first-step') ->expectsQuestion('Enter step question', 'First question') ->expectsChoice('Choose step type', 'Text step', $stepTypeChoices) ->expectsConfirmation("Do you want a 'taking' modifier method for this step?", 'yes') ->expectsConfirmation("Do you want an 'answered' modifier method for this step?", 'no') ->expectsConfirmation('Do you want to add a wizard step?', 'yes') ->expectsQuestion('Enter step name', 'second-step') ->expectsQuestion('Enter step question', 'Second question') ->expectsChoice('Choose step type', 'Choice step', $stepTypeChoices) ->expectsQuestion("Add option for multiple choice (enter 'stop' to stop)", 'First option') ->expectsQuestion("Add option for multiple choice (enter 'stop' to stop)", 'Second option') ->expectsQuestion("Add option for multiple choice (enter 'stop' to stop)", 'Third option') ->expectsQuestion("Add option for multiple choice (enter 'stop' to stop)", 'stop') ->expectsConfirmation("Do you want a 'taking' modifier method for this step?", 'yes') ->expectsConfirmation("Do you want an 'answered' modifier method for this step?", 'yes') ->expectsConfirmation('Do you want to add a wizard step?', 'no'); $generatedWizard = $this->disk->get('Console/Command/TestWizardWithSteps.php'); $this->assertIsString($generatedWizard); $this->assertStringContainsString('namespace App\Console\Command;', $generatedWizard); $this->assertStringContainsString('use Shomisha\LaravelConsoleWizard\Command\Wizard;', $generatedWizard); $this->assertStringContainsString('use Shomisha\LaravelConsoleWizard\Steps\TextStep', $generatedWizard); $this->assertStringContainsString('use Shomisha\LaravelConsoleWizard\Steps\ChoiceStep', $generatedWizard); $this->assertStringContainsString('class TestWizardWithSteps extends Wizard', $generatedWizard); $this->assertStringContainsString("protected \$signature = 'wizard:test-with-steps';", $generatedWizard); $this->assertStringContainsString("protected \$description = 'This is a test wizard with steps.';", $generatedWizard); $this->assertStringContainsString( "public function getSteps() : array\n {\n return array('first-step' => new TextStep('First question'), 'second-step' => new ChoiceStep('Second question', array('First option', 'Second option', 'Third option')));\n }\n", $generatedWizard ); $this->assertStringContainsString("public function takingFirstStep(Step \$step)\n {\n }", $generatedWizard); $this->assertStringContainsString("public function takingSecondStep(Step \$step)\n {\n }", $generatedWizard); $this->assertStringContainsString("public function answeredSecondStep(Step \$step, \$secondStep)\n {\n return \$secondStep;\n }", $generatedWizard); $this->assertStringContainsString("public function completed()\n {\n return \$this->answers->all();\n }", $generatedWizard); } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
shomisha/laravel-console-wizard
https://github.com/shomisha/laravel-console-wizard/blob/8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc/tests/Unit/WizardTest.php
tests/Unit/WizardTest.php
<?php namespace Shomisha\LaravelConsoleWizard\Test\Unit; use Illuminate\Support\Collection; use Illuminate\Validation\ValidationException; use Shomisha\LaravelConsoleWizard\Exception\InvalidStepException; use Shomisha\LaravelConsoleWizard\Steps\ChoiceStep; use Shomisha\LaravelConsoleWizard\Steps\ConfirmStep; use Shomisha\LaravelConsoleWizard\Steps\OneTimeWizard; use Shomisha\LaravelConsoleWizard\Steps\RepeatStep; use Shomisha\LaravelConsoleWizard\Steps\TextStep; use Shomisha\LaravelConsoleWizard\Test\TestCase; use Shomisha\LaravelConsoleWizard\Test\TestWizards\BaseTestWizard; use Shomisha\LaravelConsoleWizard\Test\TestWizards\InheritAnswersTestWizard; use Shomisha\LaravelConsoleWizard\Test\TestWizards\RepeatsStepsTestWizard; use Shomisha\LaravelConsoleWizard\Test\TestWizards\StepValidationTestWizard; use Shomisha\LaravelConsoleWizard\Test\TestWizards\SubwizardTestWizard; use Shomisha\LaravelConsoleWizard\Test\TestWizards\WizardValidationTestWizard; use Shomisha\LaravelConsoleWizard\Test\TestWizards\WizardWithOneTimeSubwizard; class WizardTest extends TestCase { /** @var \ReflectionProperty */ protected $steps; /** @var \ReflectionProperty */ protected $taken; /** @var \ReflectionProperty */ protected $followup; /** @var \ReflectionProperty */ protected $answers; /** * @param string $wizardClass * @return \Shomisha\LaravelConsoleWizard\Command\Wizard */ protected function loadWizard(string $wizardClass) { $this->steps = tap(new \ReflectionProperty($wizardClass, 'steps')) ->setAccessible(true); $this->taken = tap(new \ReflectionProperty($wizardClass, 'taken')) ->setAccessible(true); $this->answers = tap(new \ReflectionProperty($wizardClass, 'answers')) ->setAccessible(true); $this->followup = tap(new \ReflectionProperty($wizardClass, 'followup')) ->setAccessible(true); $wizard = $this->app->get($wizardClass); $wizard->initializeWizard(); $this->app->instance($wizardClass, $wizard); return $wizard; } protected function partiallyMockWizard(string $class, array $methods) { $mock = \Mockery::mock(sprintf( '%s[%s]', $class, implode(',', $methods) )); $this->instance($class, $mock); return $mock; } protected function runBaseTestWizard() { $this->artisan('console-wizard-test:base') ->expectsQuestion("What's your name?", 'Misa') ->expectsQuestion("How old are you?", 25) ->expectsQuestion("Your favourite programming language", 0) ->run(); } /** @test */ public function wizard_will_initialize_steps_when_created() { $wizard = $this->loadWizard(BaseTestWizard::class); $steps = $this->steps->getValue($wizard); $this->assertInstanceOf(TextStep::class, $steps->get('name')); $this->assertInstanceOf(TextStep::class, $steps->get('age')); $this->assertInstanceOf(ChoiceStep::class, $steps->get('preferred-language')); } /** @test */ public function wizard_will_throw_an_exception_if_an_invalid_step_is_expected() { $mock = $this->partiallyMockWizard(BaseTestWizard::class, ['getSteps']); $mock->shouldReceive('getSteps')->once()->andReturn([ new TextStep("What's your name?"), new InvalidStepException(), ]); $this->expectException(InvalidStepException::class); $this->artisan('console-wizard-test:base'); } /** @test */ public function wizard_will_perform_no_actions_prior_to_asserting_all_steps_are_valid() { $this->expectException(InvalidStepException::class); $mock = $this->partiallyMockWizard(BaseTestWizard::class, ['getSteps', 'take', 'completed']); $mock->shouldReceive('getSteps')->once()->andReturn([ new TextStep("What's your name?"), new InvalidStepException(), ]); $mock->shouldNotReceive('take'); $mock->shouldNotReceive('completed'); $this->artisan('console-wizard-test:base'); } /** @test */ public function wizard_will_initialize_an_empty_collection_for_taken_steps() { $wizard = $this->loadWizard(BaseTestWizard::class); $taken = $this->taken->getValue($wizard); $this->assertInstanceOf(Collection::class, $taken); $this->assertEmpty($taken); } /** @test */ public function wizard_will_initialize_an_empty_collection_for_answers() { $wizard = $this->loadWizard(BaseTestWizard::class); $answers = $this->answers->getValue($wizard); $this->assertInstanceOf(Collection::class, $answers); $this->assertEmpty($answers); } /** @test */ public function wizard_will_initialize_an_empty_collection_for_followups() { $wizard = $this->loadWizard(BaseTestWizard::class); $followup = $this->followup->getValue($wizard); $this->assertInstanceOf(Collection::class, $followup); $this->assertEmpty($followup); } /** @test */ public function wizard_will_ask_all_the_defined_steps() { $this->runBaseTestWizard(); } /** @test */ public function wizard_can_override_steps_using_arguments() { $this->artisan("wizard-test:inherit-answers Misa") ->expectsQuestion("Age", 26) ->expectsOutput("Misa is 26 year(s) old"); } /** @test */ public function wizard_can_override_steps_using_options() { $this->artisan("wizard-test:inherit-answers --age=26") ->expectsQuestion("Name", "Misa") ->expectsOutput("Misa is 26 year(s) old"); } /** @test */ public function wizard_will_not_override_steps_using_arguments_if_that_feature_is_disabled() { $wizard = $this->loadWizard(InheritAnswersTestWizard::class); $shouldInherit = new \ReflectionProperty(get_class($wizard), 'inheritAnswersFromArguments'); $shouldInherit->setAccessible(true); $shouldInherit->setValue($wizard, false); $this->artisan("wizard-test:inherit-answers Misa --age=21") ->expectsQuestion("Name", "Natalija") ->expectsQuestion("Age", 26) ->expectsOutput("Natalija is 26 year(s) old"); } /** @test */ public function wizard_will_ask_all_the_steps_from_a_subwizard() { $this->artisan('console-wizard-test:subwizard') ->expectsQuestion("What's your name?", 'Misa') ->expectsQuestion("Are you older than 18?", "Yes") ->expectsQuestion("Your marital status:", 'single'); } /** @test */ public function subwizard_answers_will_be_present_as_a_subset_of_main_wizard_answers() { $wizard = $this->loadWizard(SubwizardTestWizard::class); $this->artisan('console-wizard-test:subwizard') ->expectsQuestion("What's your name?", 'Misa') ->expectsQuestion("Are you older than 18?", "Yes") ->expectsQuestion("Your marital status:", 'single'); $answers = $this->answers->getValue($wizard); $this->assertEquals([ 'name' => 'Misa', 'legal-status' => [ 'age-legality' => true, 'marital-legality' => 'single', ], ], $answers->toArray()); } /** @test */ public function wizard_can_use_one_time_wizard_as_subwizard() { $wizard = $this->loadWizard(WizardWithOneTimeSubwizard::class); $this->artisan('console-wizard-test:one-time-subwizard') ->expectsQuestion('Answer the first step', 'First answer') ->expectsQuestion('Answer the second step', 'Second answer'); $answers = $this->answers->getValue($wizard); $this->assertEquals([ 'one-time-subwizard' => [ 'first-question' => 'First answer', 'second-question' => 'Second answer', ] ], $answers->toArray()); } /** @test */ public function one_time_wizards_completed_method_cannot_be_invoked() { $this->expectException(\RuntimeException::class); $wizard = new OneTimeWizard([]); $wizard->completed(); } /** @test */ public function wizard_can_validate_answers_on_a_per_step_basis() { $mock = $this->partiallyMockWizard(StepValidationTestWizard::class, ['onInvalidAge', 'onInvalidFavouriteColour']); $invalidAgeHandlerExpectation = $mock->shouldReceive('onInvalidAge'); $invalidColourHandlerExpectation = $mock->shouldReceive('onInvalidFavouriteColour'); $this->artisan('console-wizard-test:step-validation') ->expectsQuestion('What is your name?', 'Misa') ->expectsQuestion('How old are you?', 13) ->expectsQuestion('What is your favourite colour?', 'red'); $invalidAgeHandlerExpectation->verify(); $invalidColourHandlerExpectation->verify(); } /** @test */ public function wizard_will_throw_a_validation_exception_if_a_validation_handler_is_missing() { $mock = $this->partiallyMockWizard(StepValidationTestWizard::class, ['onInvalidAge']); $mock->shouldReceive('onInvalidAge'); $this->expectException(ValidationException::class); $this->artisan('console-wizard-test:step-validation') ->expectsQuestion('What is your name?', 'Misa') ->expectsQuestion('How old are you?', 13) ->expectsQuestion('What is your favourite colour?', 'magenta'); } /** @test */ public function wizard_can_repeat_invalidly_answered_steps_automatically() { $this->artisan('wizard-test:repeat-invalid') ->expectsQuestion("Enter age", "9") ->expectsOutput("The age field must be at least 10.") ->expectsQuestion("Enter age", "21") ->expectsOutput("The age field must not be greater than 20.") ->expectsQuestion("Enter age", "13") ->expectsQuestion("Enter birth year", "1993") ->expectsOutput("Done"); } /** @test */ public function wizard_will_not_automatically_repeat_steps_if_they_have_handlers_defined() { $mock = $this->partiallyMockWizard(RepeatsStepsTestWizard::class, ['onInvalidIHaveAHandler']); $expectation = $mock->shouldReceive('onInvalidIHaveAHandler')->andReturn(true); $this->artisan("wizard-test:repeat-invalid") ->expectsQuestion("Enter age", "13") ->expectsQuestion("Enter birth year", "I will not") ->expectsOutput("Done"); $expectation->verify(); } /** @test */ public function wizard_can_validate_answers_on_a_complete_wizard_basis() { $mock = $this->partiallyMockWizard(WizardValidationTestWizard::class, ['onWizardInvalid']); $expectation = $mock->shouldReceive('onWizardInvalid')->once(); $this->artisan('console-wizard-test:wizard-validation') ->expectsQuestion("What is your name?", 'Misa') ->expectsQuestion("What is your favourite band?", 'Invalid answer') ->expectsQuestion("Which country do you come from?", "Another invalid answer"); $expectation->verify(); } /** @test */ public function wizard_will_invoke_existing_taking_modifiers() { $mock = $this->partiallyMockWizard(BaseTestWizard::class, ['takingName', 'takingAge']); $mock->shouldReceive('takingName')->once(); $mock->shouldReceive('takingAge')->once(); $this->runBaseTestWizard(); } /** @test */ public function wizard_will_not_invoke_non_existing_taking_modifiers() { $mock = $this->partiallyMockWizard(BaseTestWizard::class, ['takingPreferredLanguage']); $mock->shouldNotReceive('takingPreferredLanguage'); $this->runBaseTestWizard(); } /** @test */ public function wizard_will_invoke_existing_answered_modifiers() { $mock = $this->partiallyMockWizard(BaseTestWizard::class, ['answeredAge', 'answeredPreferredLanguage']); $mock->shouldReceive('answeredAge')->once(); $mock->shouldReceive('answeredPreferredLanguage')->once(); $this->runBaseTestWizard(); } /** @test */ public function answered_modifier_results_will_be_saved_as_answers() { $mock = $this->partiallyMockWizard(BaseTestWizard::class, ['answeredAge', 'answeredPreferredLanguage']); $mock->shouldReceive('answeredAge')->once()->andReturn('modified age'); $mock->shouldReceive('answeredPreferredLanguage')->once()->andReturn('modified programming language'); $this->runBaseTestWizard(); $answers = tap(new \ReflectionProperty(BaseTestWizard::class, 'answers')) ->setAccessible(true) ->getValue($mock); $this->assertEquals('modified age', $answers->get('age')); $this->assertEquals('modified programming language', $answers->get('preferred-language')); } /** @test */ public function wizard_will_not_invoke_non_existing_answered_modifiers() { $mock = $this->partiallyMockWizard(BaseTestWizard::class, ['answeredName']); $mock->shouldNotReceive('answeredName'); $this->runBaseTestWizard(); } /** @test */ public function wizard_can_followup_on_steps() { $mock = $this->partiallyMockWizard(BaseTestWizard::class, ['getSteps']); $mock->shouldReceive('getSteps')->once()->andReturn([ 'run-another' => new TextStep('Should I followup on this step?'), 'i-ran-another' => new TextStep('Is it OK I ran another step?'), ]); $this->artisan('console-wizard-test:base') ->expectsQuestion('Should I followup on this step?', 'Yes') ->expectsQuestion("I am a followup.", 'Cool') ->expectsQuestion('Is it OK I ran another step?', 'Totally'); } /** @test */ public function followups_will_be_asked_from_the_latest_to_the_earliest() { $mock = $this->partiallyMockWizard(BaseTestWizard::class, ['getSteps']); $mock->shouldReceive('getSteps')->once()->andReturn([ 'main-step' => new TextStep("I am the main step"), ]); $this->artisan('console-wizard-test:base') ->expectsQuestion('I am the main step', 'Cool') ->expectsQuestion('I am added after the main step', 'Yes, you are') ->expectsQuestion('I am added before the main step', 'Good for you'); } /** @test */ public function wizard_can_repeat_steps() { $mock = $this->partiallyMockWizard(BaseTestWizard::class, ['getSteps']); $mock->shouldReceive('getSteps')->once()->andReturn([ 'repeat_me' => new TextStep("I should be repeated"), 'repeat-after-me' => new ConfirmStep("Should I repeat him, though?"), ]); $this->artisan('console-wizard-test:base') ->expectsQuestion("I should be repeated", "Indeed you should") ->expectsConfirmation("Should I repeat him, though?", 'yes') ->expectsQuestion("I should be repeated", "And repeated you are."); } /** @test */ public function wizard_can_only_repeat_taken_or_skipped_tests() { $mock = $this->partiallyMockWizard(BaseTestWizard::class, ['getSteps']); $mock->shouldReceive('getSteps')->once()->andReturn([ 'repeat-after-me' => new TextStep("I really want to repeat a step"), 'second-step' => new TextStep("I'm just chilling here"), 'repeat_me' => new TextStep("Y U NO REPEAT ME"), ]); $this->artisan('console-wizard-test:base') ->expectsQuestion("I really want to repeat a step", "But you cannot") ->expectsQuestion("I'm just chilling here", "Good for you") ->expectsQuestion("Y U NO REPEAT ME", "Because you're too late"); } /** @test */ public function wizard_can_skip_steps() { $mock = $this->partiallyMockWizard(BaseTestWizard::class, ['getSteps']); $mock->shouldReceive('getSteps')->once()->andReturn([ 'unskippable' => new TextStep("I shouldn't be skipped"), 'skip-me' => new TextStep("I am to be skipped"), 'i-will-run' => new TextStep("Running"), ]); $this->artisan('console-wizard-test:base') ->expectsQuestion("I shouldn't be skipped", "That's right") ->expectsQuestion('Running', 'good for you'); } /** @test */ public function wizard_cannot_skip_a_step_that_is_already_running() { $mock = $this->partiallyMockWizard(BaseTestWizard::class, ['getSteps']); $mock->shouldReceive('getSteps')->once()->andReturn([ 'i-will-run' => new TextStep('Running'), 'unskippable' => new TextStep("I'm running too"), ]); $this->artisan('console-wizard-test:base') ->expectsQuestion('Running', 'Good for you') ->expectsQuestion("I'm running too", 'Yes you are'); } /** @test */ public function wizard_can_repeat_a_step_a_fixed_number_of_times() { $mock = $this->partiallyMockWizard(BaseTestWizard::class, ['getSteps']); $mock->shouldReceive('getSteps')->once()->andReturn([ 'repeated' => tap(new RepeatStep(new TextStep("I will run three times")))->times(3), ]); $this->artisan('console-wizard-test:base') ->expectsQuestion('I will run three times', "Yes you will") ->expectsQuestion('I will run three times', "That's right") ->expectsQuestion('I will run three times', "Okay, we get it"); } /** @test */ public function wizard_can_repeat_a_step_until_a_specified_answer_is_provided() { $mock = $this->partiallyMockWizard(BaseTestWizard::class, ['getSteps']); $mock->shouldReceive('getSteps')->once()->andReturn([ tap(new RepeatStep(new TextStep("Gimme 5 or I shall never stop")))->untilAnswerIs(5), ]); $this->artisan('console-wizard-test:base') ->expectsQuestion("Gimme 5 or I shall never stop", 3) ->expectsQuestion("Gimme 5 or I shall never stop", 2) ->expectsQuestion("Gimme 5 or I shall never stop", 7) ->expectsQuestion("Gimme 5 or I shall never stop", "You can't have 5") ->expectsQuestion("Gimme 5 or I shall never stop", 5); } public static function callbackRepetitionTests() { return [ [ function($answer) { return $answer === 'stop'; }, ['go on', 'keep running', 'continue', 'stop'], ], [ function($answer) { if ($answer === null) { return false; } return $answer > 20; }, [1, 7, 4, 12, 19, 55], ], [ function($answer) { if ($answer === null) { return false; } return !is_string($answer); }, ['go on', 'keep it up', 'this is the last time', false], ] ]; } /** * @test * @dataProvider callbackRepetitionTests */ public function wizard_can_repeat_a_step_until_a_specific_condition_is_met(callable $callback, array $promptAnswers) { $mock = $this->partiallyMockWizard(BaseTestWizard::class, ['getSteps']); $mock->shouldReceive('getSteps')->once()->andReturn([ 'repeated' => tap(new RepeatStep(new TextStep("Repeat me")))->until($callback), ]); $consoleExpectation = $this->artisan('console-wizard-test:base'); foreach ($promptAnswers as $answer) { $consoleExpectation->expectsQuestion("Repeat me", $answer); } } /** @test */ public function wizard_can_repeat_a_steps_as_long_as_the_user_requests_so() { $mock = $this->partiallyMockWizard(BaseTestWizard::class, ['getSteps']); $mock->shouldReceive('getSteps')->andReturn([ 'repeated' => tap(new RepeatStep(new TextStep('Repeat me')))->withRepeatPrompt('Repeat me again?'), ]); $this->artisan('console-wizard-test:base') ->expectsQuestion('Repeat me', 'I will') ->expectsConfirmation('Repeat me again?', 'yes') ->expectsQuestion('Repeat me', 'Okay') ->expectsConfirmation('Repeat me again?', 'yes') ->expectsQuestion('Repeat me', 'Once more') ->expectsConfirmation('Repeat me again?', 'yes') ->expectsQuestion('Repeat me', 'No more') ->expectsConfirmation('Repeat me again?', 'no'); $this->assertEquals([ 'I will', 'Okay', 'Once more', 'No more' ], $mock->getAnswers()->get('repeated')); } /** @test */ public function wizard_can_prompt_the_user_before_the_first_repetition() { $mock = $this->partiallyMockWizard(BaseTestWizard::class, ['getSteps']); $mock->shouldReceive('getSteps')->andReturn([ 'repeated' => tap(new RepeatStep(new TextStep('Repeat me')))->withRepeatPrompt('Repeat me again?', true), ]); $this->artisan('console-wizard-test:base') ->expectsConfirmation('Repeat me again?', 'yes') ->expectsQuestion('Repeat me', 'I will') ->expectsConfirmation('Repeat me again?', 'yes') ->expectsQuestion('Repeat me', 'Okay') ->expectsConfirmation('Repeat me again?', 'yes') ->expectsQuestion('Repeat me', 'Once more') ->expectsConfirmation('Repeat me again?', 'yes') ->expectsQuestion('Repeat me', 'No more') ->expectsConfirmation('Repeat me again?', 'no'); $this->assertEquals([ 'I will', 'Okay', 'Once more', 'No more' ], $mock->getAnswers()->get('repeated')); } /** @test */ public function repeated_step_answers_will_be_returned_as_an_array() { $mock = $this->partiallyMockWizard(BaseTestWizard::class, ['getSteps']); $mock->shouldReceive('getSteps')->once()->andReturn([ 'text-step' => new TextStep("My answer will be a string"), 'repeated' => tap(new RepeatStep(new TextStep("My answer will be an array with 3 elements")))->times(3), ]); $this->artisan('console-wizard-test:base') ->expectsQuestion("My answer will be a string", "Yes it will") ->expectsQuestion("My answer will be an array with 3 elements", "True that") ->expectsQuestion("My answer will be an array with 3 elements", "Here's the second element") ->expectsQuestion("My answer will be an array with 3 elements", "And I'm the third"); $answers = tap(new \ReflectionProperty(get_class($mock), 'answers'))->setAccessible(true)->getValue($mock); $this->assertEquals([ 'text-step' => 'Yes it will', 'repeated' => [ 'True that', "Here's the second element", "And I'm the third", ] ], $answers->toArray()); } /** @test */ public function repeated_step_can_exclude_the_last_answer() { $mock = $this->partiallyMockWizard(BaseTestWizard::class, ['getSteps']); $mock->shouldReceive('getSteps')->once()->andReturn([ 'repeated' => tap(new RepeatStep(new TextStep("Gimme 5 or I shall never stop")))->untilAnswerIs(5)->withoutLastAnswer(), ]); $this->artisan('console-wizard-test:base') ->expectsQuestion("Gimme 5 or I shall never stop", 3) ->expectsQuestion("Gimme 5 or I shall never stop", 2) ->expectsQuestion("Gimme 5 or I shall never stop", 7) ->expectsQuestion("Gimme 5 or I shall never stop", "You can't have 5") ->expectsQuestion("Gimme 5 or I shall never stop", 5); $answers = $mock->getAnswers(); $this->assertEquals([ 3, 2, 7, "You can't have 5", ], $answers->get('repeated')); } /** @test */ public function wizard_will_throw_an_exception_if_a_repeated_question_is_not_properly_initialized() { $mock = $this->partiallyMockWizard(BaseTestWizard::class, ['getSteps']); $mock->shouldReceive('getSteps')->once()->andReturn([ 'repeated' => new RepeatStep(new TextStep("I'll never be ran")), ]); $this->expectException(InvalidStepException::class); $this->artisan('console-wizard-test:base'); } /** @test */ public function wizard_will_store_all_the_answers() { $wizard = $this->loadWizard(BaseTestWizard::class); $this->runBaseTestWizard(); $answers = $this->answers->getValue($wizard); $this->assertEquals([ 'name' => 'Misa', 'age' => 25, 'preferred-language' => 0, ], $answers->toArray()); } /** @test */ public function wizard_will_move_taken_steps_to_the_taken_collection() { $wizard = $this->loadWizard(BaseTestWizard::class); $this->runBaseTestWizard(); $asked = $this->taken->getValue($wizard); $questions = $this->steps->getValue($wizard); $this->assertInstanceOf(TextStep::class, $asked->get('name')); $this->assertInstanceOf(TextStep::class, $asked->get('age')); $this->assertInstanceOf(ChoiceStep::class, $asked->get('preferred-language')); $this->assertInstanceOf(Collection::class, $questions); $this->assertEmpty($questions); } /** @test */ public function wizard_will_invoke_completed_upon_completion() { $mock = $this->partiallyMockWizard(BaseTestWizard::class, ['completed']); $mock->shouldNotReceive('completed')->once(); $this->runBaseTestWizard(); } /** @test */ public function wizard_can_be_aborted() { $this->artisan('wizard:abort') ->expectsConfirmation("Should I abort?", 'yes'); } }
php
MIT
8ea5e03e9cc9e25e685912f6b1e2adf32b9815cc
2026-01-05T05:16:24.488418Z
false
keboola/php-csv
https://github.com/keboola/php-csv/blob/a7e5828ceea0e2d8561bb07619c73091e6155c36/ignore-by-php-version.neon.php
ignore-by-php-version.neon.php
<?php declare(strict_types=1); use PHPStan\DependencyInjection\NeonAdapter; $adapter = new NeonAdapter(); $config = []; if (PHP_VERSION_ID >= 80000) { $config = array_merge_recursive($config, $adapter->load(__DIR__ . '/phpstan-baseline-8+.neon')); } else { $config = array_merge_recursive($config, $adapter->load(__DIR__ . '/phpstan-baseline.neon')); } $config['parameters']['phpVersion'] = PHP_VERSION_ID; return $config;
php
MIT
a7e5828ceea0e2d8561bb07619c73091e6155c36
2026-01-05T05:16:34.451181Z
false
keboola/php-csv
https://github.com/keboola/php-csv/blob/a7e5828ceea0e2d8561bb07619c73091e6155c36/src/UTF8BOMHelper.php
src/UTF8BOMHelper.php
<?php declare(strict_types=1); namespace Keboola\Csv; class UTF8BOMHelper { /** * @param array $header * @return array */ public static function detectAndRemoveBOM($header) { if (!is_array($header) || empty($header) || $header[0] === null) { return $header; } $utf32BigEndianBom = chr(0x00) . chr(0x00) . chr(0xFE) . chr(0xFF); $utf32LittleEndianBom = chr(0xFF) . chr(0xFE) . chr(0x00) . chr(0x00); $utf16BigEndianBom = chr(0xFE) . chr(0xFF); $utf16LittleEndianBom = chr(0xFF) . chr(0xFE); $utf8Bom = chr(0xEF) . chr(0xBB) . chr(0xBF); foreach ([ $utf32BigEndianBom, $utf32LittleEndianBom, $utf16BigEndianBom, $utf16LittleEndianBom, $utf8Bom, ] as $bomString) { if (strpos($header[0], $bomString) === 0) { $header[0] = trim(substr($header[0], strlen($bomString)), '"'); break; } } return $header; } }
php
MIT
a7e5828ceea0e2d8561bb07619c73091e6155c36
2026-01-05T05:16:34.451181Z
false
keboola/php-csv
https://github.com/keboola/php-csv/blob/a7e5828ceea0e2d8561bb07619c73091e6155c36/src/AbstractCsvFile.php
src/AbstractCsvFile.php
<?php namespace Keboola\Csv; abstract class AbstractCsvFile { /** * @deprecated use Keboola\Csv\CsvOptions::DEFAULT_DELIMITER */ const DEFAULT_DELIMITER = CsvOptions::DEFAULT_DELIMITER; /** * @deprecated use Keboola\Csv\CsvOptions::DEFAULT_ENCLOSURE */ const DEFAULT_ENCLOSURE = CsvOptions::DEFAULT_ENCLOSURE; /** * @var string */ protected $fileName; /** * @var resource */ protected $filePointer; /** * @var CsvOptions */ protected $options; /** * @return string */ public function getDelimiter() { return $this->options->getDelimiter(); } /** * @return string */ public function getEnclosure() { return $this->options->getEnclosure(); } public function __destruct() { $this->closeFile(); } protected function closeFile() { if ($this->fileName && is_resource($this->filePointer)) { fclose($this->filePointer); } } /** * @param string|resource $file */ protected function setFile($file) { if (is_string($file)) { $this->openCsvFile($file); $this->fileName = $file; } elseif (is_resource($file)) { $this->filePointer = $file; } else { throw new InvalidArgumentException('Invalid file: ' . var_export($file, true)); } } abstract protected function openCsvFile($fileName); /** * @return resource */ protected function getFilePointer() { return $this->filePointer; } }
php
MIT
a7e5828ceea0e2d8561bb07619c73091e6155c36
2026-01-05T05:16:34.451181Z
false
keboola/php-csv
https://github.com/keboola/php-csv/blob/a7e5828ceea0e2d8561bb07619c73091e6155c36/src/CsvOptions.php
src/CsvOptions.php
<?php namespace Keboola\Csv; class CsvOptions { const DEFAULT_DELIMITER = ','; const DEFAULT_ENCLOSURE = '"'; const DEFAULT_ESCAPED_BY = ''; /** * @var string */ private $delimiter; /** * @var string */ private $enclosure; /** * @var string */ private $escapedBy; /** * @param string $delimiter * @param string $enclosure * @param string $escapedBy * @throws InvalidArgumentException */ public function __construct( $delimiter = self::DEFAULT_DELIMITER, $enclosure = self::DEFAULT_ENCLOSURE, $escapedBy = self::DEFAULT_ESCAPED_BY ) { $this->escapedBy = $escapedBy; $this->validateDelimiter($delimiter); $this->delimiter = $delimiter; $this->validateEnclosure($enclosure); $this->enclosure = $enclosure; } /** * @param string $enclosure * @throws InvalidArgumentException */ protected function validateEnclosure($enclosure) { if (strlen($enclosure) > 1) { throw new InvalidArgumentException( 'Enclosure must be a single character. ' . json_encode($enclosure) . ' received', Exception::INVALID_PARAM, ); } } /** * @param string $delimiter * @throws InvalidArgumentException */ protected function validateDelimiter($delimiter) { if (strlen($delimiter) > 1) { throw new InvalidArgumentException( 'Delimiter must be a single character. ' . json_encode($delimiter) . ' received', Exception::INVALID_PARAM, ); } if (strlen($delimiter) === 0) { throw new InvalidArgumentException( 'Delimiter cannot be empty.', Exception::INVALID_PARAM, ); } } /** * @return string */ public function getEscapedBy() { return $this->escapedBy; } /** * @return string */ public function getDelimiter() { return $this->delimiter; } /** * @return string */ public function getEnclosure() { return $this->enclosure; } }
php
MIT
a7e5828ceea0e2d8561bb07619c73091e6155c36
2026-01-05T05:16:34.451181Z
false
keboola/php-csv
https://github.com/keboola/php-csv/blob/a7e5828ceea0e2d8561bb07619c73091e6155c36/src/CsvReader.php
src/CsvReader.php
<?php declare(strict_types=1); namespace Keboola\Csv; use Iterator; use ReturnTypeWillChange; class CsvReader extends AbstractCsvFile implements Iterator { /** * @deprecated use Keboola\Csv\CsvOptions::DEFAULT_ENCLOSURE */ const DEFAULT_ESCAPED_BY = CsvOptions::DEFAULT_ESCAPED_BY; const SAMPLE_SIZE = 10000; /** * @var int */ private $skipLines; /** * @var int */ private $rowCounter = 0; /** * @var array|null|false */ private $currentRow; /** * @var array */ private $header; /** * @var string */ private $lineBreak; /** * CsvFile constructor. * @param string|resource $file * @param string $delimiter * @param string $enclosure * @param string $escapedBy * @param int $skipLines * @throws Exception */ public function __construct( $file, $delimiter = CsvOptions::DEFAULT_DELIMITER, $enclosure = CsvOptions::DEFAULT_ENCLOSURE, $escapedBy = CsvOptions::DEFAULT_ESCAPED_BY, $skipLines = 0 ) { $this->options = new CsvOptions($delimiter, $enclosure, $escapedBy); $this->setSkipLines($skipLines); $this->setFile($file); $this->lineBreak = $this->detectLineBreak(); $this->validateLineBreak(); rewind($this->filePointer); $header = UTF8BOMHelper::detectAndRemoveBOM($this->readLine()); if (is_array($header) && $header[0] === null) { $header = []; } $this->header = $header; $this->rewind(); } /** * @param integer $skipLines * @return CsvReader * @throws InvalidArgumentException */ protected function setSkipLines($skipLines) { $this->validateSkipLines($skipLines); $this->skipLines = $skipLines; return $this; } /** * @param integer $skipLines * @throws InvalidArgumentException */ protected function validateSkipLines($skipLines) { if (!is_int($skipLines) || $skipLines < 0) { throw new InvalidArgumentException( "Number of lines to skip must be a positive integer. \"$skipLines\" received.", Exception::INVALID_PARAM, ); } } /** * @param $fileName * @throws Exception */ protected function openCsvFile($fileName) { if (!is_file($fileName)) { throw new Exception( 'Cannot open file ' . $fileName, Exception::FILE_NOT_EXISTS, ); } $this->filePointer = @fopen($fileName, 'r'); if (!$this->filePointer) { throw new Exception( "Cannot open file {$fileName} " . error_get_last()['message'], Exception::FILE_NOT_EXISTS, ); } } /** * @return string */ protected function detectLineBreak() { @rewind($this->getFilePointer()); $sample = @fread($this->getFilePointer(), self::SAMPLE_SIZE); if (substr((string) $sample, -1) === "\r") { // we might have hit the file in the middle of CR+LF, only getting CR @rewind($this->getFilePointer()); $sample = @fread($this->getFilePointer(), self::SAMPLE_SIZE+1); } return LineBreaksHelper::detectLineBreaks($sample, $this->getEnclosure(), $this->getEscapedBy()); } /** * @return array|false|null * @throws Exception * @throws InvalidArgumentException */ protected function readLine() { // allow empty enclosure hack $enclosure = !$this->getEnclosure() ? chr(0) : $this->getEnclosure(); $escapedBy = !$this->getEscapedBy() ? chr(0) : $this->getEscapedBy(); return @fgetcsv($this->getFilePointer(), null, $this->getDelimiter(), $enclosure, $escapedBy); } /** * @return string * @throws InvalidArgumentException */ protected function validateLineBreak() { $lineBreak = $this->getLineBreak(); if (in_array($lineBreak, ["\r\n", "\n"])) { return $lineBreak; } throw new InvalidArgumentException( "Invalid line break. Please use unix \\n or win \\r\\n line breaks.", Exception::INVALID_PARAM, ); } /** * @return string */ public function getLineBreak() { return $this->lineBreak; } /** * @inheritdoc */ #[ReturnTypeWillChange] public function rewind() { rewind($this->getFilePointer()); for ($i = 0; $i < $this->skipLines; $i++) { $this->readLine(); } $this->currentRow = $this->readLine(); $this->rowCounter = 0; } /** * @return string */ public function getEscapedBy() { return $this->options->getEscapedBy(); } /** * @return int */ public function getColumnsCount() { return count($this->getHeader()); } /** * @return array */ public function getHeader() { if ($this->header) { return $this->header; } return []; } /** * @return string */ public function getLineBreakAsText() { return trim(json_encode($this->getLineBreak()), '"'); } /** * @inheritdoc */ #[ReturnTypeWillChange] public function current() { return $this->currentRow; } /** * @inheritdoc */ #[ReturnTypeWillChange] public function next() { $this->currentRow = $this->readLine(); $this->rowCounter++; } /** * @inheritdoc */ #[ReturnTypeWillChange] public function key() { return $this->rowCounter; } /** * @inheritdoc */ #[ReturnTypeWillChange] public function valid() { return $this->currentRow !== false; } }
php
MIT
a7e5828ceea0e2d8561bb07619c73091e6155c36
2026-01-05T05:16:34.451181Z
false
keboola/php-csv
https://github.com/keboola/php-csv/blob/a7e5828ceea0e2d8561bb07619c73091e6155c36/src/LineBreaksHelper.php
src/LineBreaksHelper.php
<?php declare(strict_types=1); namespace Keboola\Csv; class LineBreaksHelper { const REGEXP_DELIMITER = '~'; /** * Detect line-breaks style in CSV file * @param string $sample * @param string $enclosure * @param string $escapedBy * @return string */ public static function detectLineBreaks($sample, $enclosure, $escapedBy) { $cleared = self::clearCsvValues($sample, $enclosure, $escapedBy); $possibleLineBreaks = [ "\r\n", // win "\r", // mac "\n", // unix ]; $lineBreaksPositions = []; foreach ($possibleLineBreaks as $lineBreak) { $position = strpos($cleared, $lineBreak); if ($position === false) { continue; } $lineBreaksPositions[$lineBreak] = $position; } asort($lineBreaksPositions); reset($lineBreaksPositions); return empty($lineBreaksPositions) ? "\n" : key($lineBreaksPositions); } /** * Clear enclosured values in CSV eg. "abc" to "", * because these values can contain line breaks eg, "abc\n\r\n\r\r\r\r", * and this makes it difficult to detect line breaks style in CSV, * if are another line breaks present in first line. * @internal Should be used only in detectLineBreaks, public for easier testing. * @param string $sample * @param string $enclosure * @param string $escapedBy eg. empty string or \ * @return string */ public static function clearCsvValues($sample, $enclosure, $escapedBy) { if (empty($enclosure)) { return $sample; } // Usually an enclosure character is escaped by doubling it, however, the escapeBy can be used $doubleEnclosure = $enclosure . $enclosure; $escapedEnclosure = empty($escapedBy) ? $doubleEnclosure : $escapedBy . $enclosure; $escapedEscape = empty($escapedBy) ? null : $escapedBy . $escapedBy; /* * Regexp examples: * enclosure: |"|, escapedBy: none, regexp: ~"(?>(?>"")|[^"])*"~ * enclosure: |"|, escapedBy: |\|, regexp: ~"(?>(?>\\"|\\\\)|[^"])*"~ */ // @formatter:off $regexp = // regexp start self::REGEXP_DELIMITER . // enclosure start preg_quote($enclosure, self::REGEXP_DELIMITER) . /* * Once-only group => if there is a match, do not try other alternatives * See: https://www.php.net/manual/en/regexp.reference.onlyonce.php * Without once-only group will be |"abc\"| false positive, * because |\| is matched by group and |"| at the end of regexp. */ // repeated once-only group start '(?>' . // once-only group start '(?>' . // escaped enclosure preg_quote($escapedEnclosure, self::REGEXP_DELIMITER) . // OR escaped escape char ($escapedEscape ? '|' . preg_quote($escapedEscape, self::REGEXP_DELIMITER) : '') . // group end ')' . // OR not enclosure '|[^' . preg_quote($enclosure, self::REGEXP_DELIMITER) . ']' . // group end ')*' . // enclosure end preg_quote($enclosure, self::REGEXP_DELIMITER) . // regexp end self::REGEXP_DELIMITER; // @formatter:on return preg_replace($regexp, $doubleEnclosure, (string) $sample); } }
php
MIT
a7e5828ceea0e2d8561bb07619c73091e6155c36
2026-01-05T05:16:34.451181Z
false
keboola/php-csv
https://github.com/keboola/php-csv/blob/a7e5828ceea0e2d8561bb07619c73091e6155c36/src/CsvWriter.php
src/CsvWriter.php
<?php namespace Keboola\Csv; use TypeError; use ValueError; class CsvWriter extends AbstractCsvFile { /** * @var string */ private $lineBreak; /** * CsvFile constructor. * @param string|resource $file * @param string $delimiter * @param string $enclosure * @param string $lineBreak * @throws Exception * @throws InvalidArgumentException */ public function __construct( $file, $delimiter = CsvOptions::DEFAULT_DELIMITER, $enclosure = CsvOptions::DEFAULT_ENCLOSURE, $lineBreak = "\n" ) { $this->options = new CsvOptions($delimiter, $enclosure); $this->setLineBreak($lineBreak); $this->setFile($file); } /** * @param string $lineBreak */ private function setLineBreak($lineBreak) { $this->validateLineBreak($lineBreak); $this->lineBreak = $lineBreak; } /** * @param string $lineBreak */ private function validateLineBreak($lineBreak) { $allowedLineBreaks = [ "\r\n", // win "\r", // mac "\n", // unix ]; if (!in_array($lineBreak, $allowedLineBreaks)) { throw new Exception( 'Invalid line break: ' . json_encode($lineBreak) . ' allowed line breaks: ' . json_encode($allowedLineBreaks), Exception::INVALID_PARAM, ); } } /** * @param string $fileName * @throws Exception */ protected function openCsvFile($fileName) { try { $this->filePointer = @fopen($fileName, 'w'); } catch (ValueError $e) { throw new Exception( "Cannot open file {$fileName} " . $e->getMessage(), Exception::FILE_NOT_EXISTS, $e, ); } if (!$this->filePointer) { throw new Exception( "Cannot open file {$fileName} " . error_get_last()['message'], Exception::FILE_NOT_EXISTS, ); } } /** * @param array $row * @throws Exception */ public function writeRow(array $row) { $str = $this->rowToStr($row); try { $ret = @fwrite($this->getFilePointer(), $str); } catch (TypeError $e) { throw new Exception( 'Cannot write to CSV file ' . $this->fileName . 'Error: ' . $e->getMessage() . ' Return: false' . ' To write: ' . strlen($str) . ' Written: 0', Exception::WRITE_ERROR, $e, ); } /* According to http://php.net/fwrite the fwrite() function should return false on error. However not writing the full string (which may occur e.g. when disk is full) is not considered as an error. Therefore both conditions are necessary. */ if (($ret === false) || (($ret === 0) && (strlen($str) > 0))) { throw new Exception( 'Cannot write to CSV file ' . $this->fileName . ($ret === false && error_get_last() ? 'Error: ' . error_get_last()['message'] : '') . ' Return: ' . json_encode($ret) . ' To write: ' . strlen($str) . ' Written: ' . (int) $ret, Exception::WRITE_ERROR, ); } } /** * @param array $row * @return string * @throws Exception */ public function rowToStr(array $row) { $return = []; foreach ($row as $column) { if (!( is_scalar($column) || is_null($column) || ( is_object($column) && method_exists($column, '__toString') ) )) { throw new Exception( 'Cannot write data into column: ' . var_export($column, true), Exception::WRITE_ERROR, ); } $enclosure = $this->getEnclosure(); $escapedEnclosure = str_repeat($enclosure, 2); $columnValue = ($column === false) ? '0' : ($column ?? ''); $escapedColumn = str_replace($enclosure, $escapedEnclosure, $columnValue); $return[] = sprintf('%s%s%s', $enclosure, $escapedColumn, $enclosure); } return implode($this->getDelimiter(), $return) . $this->lineBreak; } }
php
MIT
a7e5828ceea0e2d8561bb07619c73091e6155c36
2026-01-05T05:16:34.451181Z
false
keboola/php-csv
https://github.com/keboola/php-csv/blob/a7e5828ceea0e2d8561bb07619c73091e6155c36/src/Exception.php
src/Exception.php
<?php declare(strict_types=1); namespace Keboola\Csv; use Exception as CoreException; class Exception extends CoreException { const FILE_NOT_EXISTS = 1; const INVALID_PARAM = 2; const WRITE_ERROR = 3; }
php
MIT
a7e5828ceea0e2d8561bb07619c73091e6155c36
2026-01-05T05:16:34.451181Z
false
keboola/php-csv
https://github.com/keboola/php-csv/blob/a7e5828ceea0e2d8561bb07619c73091e6155c36/src/InvalidArgumentException.php
src/InvalidArgumentException.php
<?php declare(strict_types=1); namespace Keboola\Csv; class InvalidArgumentException extends Exception { }
php
MIT
a7e5828ceea0e2d8561bb07619c73091e6155c36
2026-01-05T05:16:34.451181Z
false
keboola/php-csv
https://github.com/keboola/php-csv/blob/a7e5828ceea0e2d8561bb07619c73091e6155c36/tests/StringObject.php
tests/StringObject.php
<?php declare(strict_types=1); namespace Keboola\Csv\Tests; class StringObject { public function __toString() { return 'me string'; } }
php
MIT
a7e5828ceea0e2d8561bb07619c73091e6155c36
2026-01-05T05:16:34.451181Z
false
keboola/php-csv
https://github.com/keboola/php-csv/blob/a7e5828ceea0e2d8561bb07619c73091e6155c36/tests/CsvWriteTest.php
tests/CsvWriteTest.php
<?php declare(strict_types=1); namespace Keboola\Csv\Tests; use Keboola\Csv\CsvOptions; use Keboola\Csv\CsvWriter; use Keboola\Csv\Exception; use PHPUnit\Framework\Constraint\LogicalOr; use PHPUnit\Framework\Constraint\StringContains; use PHPUnit\Framework\TestCase; use stdClass; class CsvWriteTest extends TestCase { public function testNewFileShouldBeCreated() { $fileName = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid('csv-test'); self::assertInstanceOf(CsvWriter::class, new CsvWriter($fileName)); } public function testAccessors() { $csvFile = new CsvWriter(sys_get_temp_dir() . '/test-write.csv'); self::assertEquals('"', $csvFile->getEnclosure()); self::assertEquals(',', $csvFile->getDelimiter()); } public function testWrite() { $fileName = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid('csv-test'); $csvFile = new CsvWriter($fileName); $rows = [ [ 'col1', 'col2', ], [ 'line without enclosure', 'second column', ], [ 'enclosure " in column', 'hello \\', ], [ 'line with enclosure', 'second column', ], [ 'column with enclosure ", and comma inside text', 'second column enclosure in text "', ], [ "columns with\nnew line", "columns with\ttab", ], [ 'column with \n \t \\\\', 'second col', ], [ 1, true, ], [ 2, false, ], [ 3, null, ], [ 'true', 1.123, ], [ '1', 'null', ], ]; foreach ($rows as $row) { $csvFile->writeRow($row); } $data = file_get_contents($fileName); self::assertEquals( implode( "\n", [ '"col1","col2"', '"line without enclosure","second column"', '"enclosure "" in column","hello \\"', '"line with enclosure","second column"', '"column with enclosure "", and comma inside text","second column enclosure in text """', "\"columns with\nnew line\",\"columns with\ttab\"", '"column with \\n \\t \\\\","second col"', '"1","1"', '"2","0"', '"3",""', '"true","1.123"', '"1","null"', '', ], ), $data, ); } public function testWriteInvalidObject() { $fileName = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid('csv-test'); $csvFile = new CsvWriter($fileName); $rows = [ [ 'col1', 'col2', ], [ '1', new stdClass(), ], ]; $csvFile->writeRow($rows[0]); try { $csvFile->writeRow($rows[1]); self::fail('Expected exception was not thrown.'); } catch (Exception $e) { // Exception message differs between PHP versions. $or = new LogicalOr(); $or->setConstraints([ new StringContains('Cannot write data into column: stdClass::'), new StringContains("Cannot write data into column: (object) array(\n)"), ]); self::assertThat($e->getMessage(), $or); } } public function testWriteValidObject() { $fileName = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid('csv-test'); $csvFile = new CsvWriter($fileName); $rows = [ [ 'col1', 'col2', ], [ '1', new StringObject(), ], ]; $csvFile->writeRow($rows[0]); $csvFile->writeRow($rows[1]); $data = file_get_contents($fileName); self::assertEquals( implode( "\n", [ '"col1","col2"' , '"1","me string"', '', ], ), $data, ); } /** * @dataProvider invalidFilenameProvider * @param string $filename * @param string $message */ public function testInvalidFileName($filename, $message) { self::expectException(Exception::class); self::expectExceptionMessage($message); new CsvWriter($filename); } public function invalidFileNameProvider() { if (PHP_VERSION_ID < 80000) { return [ ['', 'Filename cannot be empty'], ["\0", 'fopen() expects parameter 1 to be a valid path, string given'], ]; } return [ ['', 'Path cannot be empty'], ["\0", 'Argument #1 ($filename) must not contain any null bytes'], ]; } public function testNonStringWrite() { $fileName = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid('csv-test'); $csvFile = new CsvWriter($fileName); $row = [['nested']]; self::expectException(Exception::class); self::expectExceptionMessage('Cannot write data into column: array'); $csvFile->writeRow($row); } public function testWritePointer() { $fileName = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid('csv-test'); $file = fopen($fileName, 'w'); $csvFile = new CsvWriter($file); $rows = [['col1', 'col2']]; $csvFile->writeRow($rows[0]); // check that the file pointer remains valid unset($csvFile); fwrite($file, 'foo,bar'); $data = file_get_contents($fileName); self::assertEquals( implode( "\n", [ '"col1","col2"' , 'foo,bar', ], ), $data, ); } public function testInvalidPointer() { $fileName = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid('csv-test'); touch($fileName); $pointer = fopen($fileName, 'r'); $csvFile = new CsvWriter($pointer); $rows = [['col1', 'col2']]; try { $csvFile->writeRow($rows[0]); self::fail('Expected exception was not thrown.'); } catch (Exception $e) { // Exception message differs between PHP versions. $or = new LogicalOr(); $or->setConstraints([ new StringContains( 'Cannot write to CSV file Return: 0 To write: 14 Written: 0', ), new StringContains( 'Cannot write to CSV file Error: fwrite(): ' . 'write of 14 bytes failed with errno=9 Bad file descriptor Return: false To write: 14 Written: 0', ), new StringContains( 'Cannot write to CSV file Error: fwrite(): ' . 'Write of 14 bytes failed with errno=9 Bad file descriptor Return: false To write: 14 Written: 0', ), ]); self::assertThat($e->getMessage(), $or); } } public function testInvalidPointer2() { $fileName = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid('csv-test'); touch($fileName); $pointer = fopen($fileName, 'r'); $csvFile = new CsvWriter($pointer); fclose($pointer); $rows = [['col1', 'col2']]; self::expectException(Exception::class); self::expectExceptionMessage( 'a valid stream resource Return: false To write: 14 Written: ', ); $csvFile->writeRow($rows[0]); } public function testInvalidFile() { self::expectException(Exception::class); self::expectExceptionMessage('Invalid file: array'); /** @noinspection PhpParamsInspection */ new CsvWriter(['dummy']); } public function testWriteLineBreak() { $fileName = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid('csv-test'); $csvFile = new CsvWriter( $fileName, CsvOptions::DEFAULT_DELIMITER, CsvOptions::DEFAULT_ENCLOSURE, "\r\n", ); $rows = [ [ 'col1', 'col2', ], [ 'val1', 'val2', ], ]; foreach ($rows as $row) { $csvFile->writeRow($row); } $data = file_get_contents($fileName); self::assertEquals( implode( "\r\n", [ '"col1","col2"', '"val1","val2"', '', ], ), $data, ); } }
php
MIT
a7e5828ceea0e2d8561bb07619c73091e6155c36
2026-01-05T05:16:34.451181Z
false
keboola/php-csv
https://github.com/keboola/php-csv/blob/a7e5828ceea0e2d8561bb07619c73091e6155c36/tests/UTF8BOMHelperTest.php
tests/UTF8BOMHelperTest.php
<?php declare(strict_types=1); namespace Keboola\Csv\Tests; use Keboola\Csv\CsvReader; use Keboola\Csv\UTF8BOMHelper; use PHPUnit\Framework\TestCase; class UTF8BOMHelperTest extends TestCase { /** * @dataProvider bomProvider * @param string $bomFile */ public function testDetectAndRemoveBOM($bomFile) { $file = __DIR__ . '/data/bom/' . $bomFile . '.csv'; $reader = new CsvReader($file); $firstLine = $reader->current(); $this->assertNotSame(['id', 'name'], $firstLine); $this->assertSame(['id', 'name'], UTF8BOMHelper::detectAndRemoveBOM($firstLine)); } public function testDetectAndRemoveBOMEdgeCases(): void { $this->assertSame([null], UTF8BOMHelper::detectAndRemoveBOM([null])); $this->assertSame([], UTF8BOMHelper::detectAndRemoveBOM([])); $this->assertSame(null, UTF8BOMHelper::detectAndRemoveBOM(null)); // @phpstan-ignore-line } public function bomProvider() { return [ ['utf32BigEndianBom'], ['utf32LittleEndianBom'], ['utf16BigEndianBom'], ['utf16LittleEndianBom'], ['utf8Bom'], ]; } }
php
MIT
a7e5828ceea0e2d8561bb07619c73091e6155c36
2026-01-05T05:16:34.451181Z
false
keboola/php-csv
https://github.com/keboola/php-csv/blob/a7e5828ceea0e2d8561bb07619c73091e6155c36/tests/CsvOptionsTest.php
tests/CsvOptionsTest.php
<?php declare(strict_types=1); namespace Keboola\Csv\Tests; use Keboola\Csv\CsvOptions; use Keboola\Csv\InvalidArgumentException; use PHPUnit\Framework\TestCase; class CsvOptionsTest extends TestCase { public function testAccessors() { $csvFile = new CsvOptions(); self::assertEquals('"', $csvFile->getEnclosure()); self::assertEquals('', $csvFile->getEscapedBy()); self::assertEquals(',', $csvFile->getDelimiter()); } public function testInvalidDelimiter() { self::expectException(InvalidArgumentException::class); self::expectExceptionMessage('Delimiter must be a single character. ",," received'); new CsvOptions(',,'); } public function testInvalidDelimiterEmpty() { self::expectException(InvalidArgumentException::class); self::expectExceptionMessage('Delimiter cannot be empty.'); new CsvOptions(''); } public function testInvalidEnclosure() { self::expectException(InvalidArgumentException::class); self::expectExceptionMessage('Enclosure must be a single character. ",," received'); new CsvOptions(CsvOptions::DEFAULT_DELIMITER, ',,'); } }
php
MIT
a7e5828ceea0e2d8561bb07619c73091e6155c36
2026-01-05T05:16:34.451181Z
false
keboola/php-csv
https://github.com/keboola/php-csv/blob/a7e5828ceea0e2d8561bb07619c73091e6155c36/tests/CsvReadTest.php
tests/CsvReadTest.php
<?php namespace Keboola\Csv\Tests; use Keboola\Csv\CsvOptions; use Keboola\Csv\CsvReader; use Keboola\Csv\CsvWriter; use Keboola\Csv\Exception; use Keboola\Csv\InvalidArgumentException; use PHPUnit\Framework\TestCase; class CsvReadTest extends TestCase { public function testExistingFileShouldBeCreated() { self::assertInstanceOf(CsvReader::class, new CsvReader(__DIR__ . '/data/test-input.csv')); } public function testAccessors() { $csvFile = new CsvReader(__DIR__ . '/data/test-input.csv'); self::assertEquals('"', $csvFile->getEnclosure()); self::assertEquals('', $csvFile->getEscapedBy()); self::assertEquals(',', $csvFile->getDelimiter()); } public function testColumnsCount() { $csv = new CsvReader(__DIR__ . '/data/test-input.csv'); self::assertEquals(9, $csv->getColumnsCount()); } public function testNewlineDetectionEdgecaseWithCrLf() { $this->expectNotToPerformAssertions(); // this used to throw "Invalid line break. Please use unix \n or win \r\n line breaks." before the fix new CsvReader(__DIR__ . '/data/test-input-edgecase.crlf.csv'); } /** * @dataProvider validCsvFiles * @param string $fileName * @param string $delimiter */ public function testRead($fileName, $delimiter) { $csvFile = new CsvReader(__DIR__ . '/data/' . $fileName, $delimiter, '"'); $expected = [ 'id', 'idAccount', 'date', 'totalFollowers', 'followers', 'totalStatuses', 'statuses', 'kloutScore', 'timestamp', ]; self::assertEquals($expected, $csvFile->getHeader()); } public function validCsvFiles() { return [ ['test-input.csv', ','], ['test-input.win.csv', ','], ['test-input.tabs.csv', "\t"], ['test-input.tabs.csv', ' '], ]; } public function testParse() { $csvFile = new CsvReader(__DIR__ . '/data/escaping.csv', ',', '"'); $rows = []; foreach ($csvFile as $row) { $rows[] = $row; } $expected = [ [ 'col1', 'col2', ], [ 'line without enclosure', 'second column', ], [ 'enclosure " in column', 'hello \\', ], [ 'line with enclosure', 'second column', ], [ 'column with enclosure ", and comma inside text', 'second column enclosure in text "', ], [ "columns with\nnew line", "columns with\ttab", ], [ "Columns with WINDOWS\r\nnew line", 'second', ], [ 'column with \n \t \\\\', 'second col', ], ]; self::assertEquals($expected, $rows); } public function testParseEscapedBy() { $csvFile = new CsvReader(__DIR__ . '/data/escapingEscapedBy.csv', ',', '"', '\\'); $expected = [ [ 'col1', 'col2', ], [ 'line without enclosure', 'second column', ], [ 'enclosure \" in column', 'hello \\\\', ], [ 'line with enclosure', 'second column', ], [ 'column with enclosure \", and comma inside text', 'second column enclosure in text \"', ], [ "columns with\nnew line", "columns with\ttab", ], [ "Columns with WINDOWS\r\nnew line", 'second', ], [ 'column with \n \t \\\\', 'second col', ], ]; self::assertEquals($expected, iterator_to_array($csvFile)); } /** * @dataProvider bomProvider */ public function testUtf8BOM($bomFile) { $csvFile = new CsvReader(__DIR__ . '/data/bom/' . $bomFile . '.csv'); self::assertEquals(['id', 'name',], $csvFile->getHeader()); } public function bomProvider() { return [ ['utf32BigEndianBom'], ['utf32LittleEndianBom'], ['utf16BigEndianBom'], ['utf16LittleEndianBom'], ['utf8Bom'], ]; } public function testParseMacLineEndsInField() { $csvFile = new CsvReader(__DIR__ . '/data/test-input.lineBreaks.csv', ',', '"', '\\'); $expected = [ [ 'test', "some text\rwith\r\\r line breaks\rinside\rbut\rrows\rare\rusing \\n \\\"line\\\" break\r", ], [ 'name', 'data', ], ]; self::assertEquals($expected, iterator_to_array($csvFile)); } public function testEmptyCsv(): void { $csvFile = new CsvReader(__DIR__ . '/data/test-input.empty.csv', ',', '"'); self::assertEquals([], $csvFile->getHeader()); } public function testEmptyHeader(): void { $csvFile = new CsvReader(__DIR__ . '/data/test-input.emptyHeader.csv', ',', '"'); self::assertEquals([], $csvFile->getHeader()); } public function testInitInvalidFileShouldThrowException() { $this->expectException(Exception::class); $this->expectExceptionMessage('Cannot open file'); new CsvReader(__DIR__ . '/data/dafadfsafd.csv'); } /** * @param string $file * @param string $lineBreak * @param string $lineBreakAsText * @dataProvider validLineBreaksData */ public function testLineEndingsDetection($file, $lineBreak, $lineBreakAsText) { $csvFile = new CsvReader(__DIR__ . '/data/' . $file); self::assertEquals($lineBreak, $csvFile->getLineBreak()); self::assertEquals($lineBreakAsText, $csvFile->getLineBreakAsText()); } public function validLineBreaksData() { return [ ['test-input.csv', "\n", '\n'], ['test-input.win.csv', "\r\n", '\r\n'], ['escaping.csv', "\n", '\n'], ['just-header.csv', "\n", '\n'], // default ]; } public function testInvalidLineBreak() { self::expectException(InvalidArgumentException::class); self::expectExceptionMessage('Invalid line break. Please use unix \n or win \r\n line breaks.'); new CsvReader(__DIR__ . '/data/test-input.mac.csv'); } public function testIterator() { $csvFile = new CsvReader(__DIR__ . '/data/test-input.csv'); $expected = [ 'id', 'idAccount', 'date', 'totalFollowers', 'followers', 'totalStatuses', 'statuses', 'kloutScore', 'timestamp', ]; // header line $csvFile->rewind(); self::assertEquals($expected, $csvFile->current()); // first line $csvFile->next(); self::assertTrue($csvFile->valid()); // second line $csvFile->next(); self::assertTrue($csvFile->valid()); // file end $csvFile->next(); self::assertFalse($csvFile->valid()); } public function testSkipsHeaders() { $fileName = __DIR__ . '/data/simple.csv'; $csvFile = new CsvReader( $fileName, CsvOptions::DEFAULT_DELIMITER, CsvOptions::DEFAULT_ENCLOSURE, CsvOptions::DEFAULT_ESCAPED_BY, 1, ); self::assertEquals(['id', 'isImported'], $csvFile->getHeader()); self::assertEquals([ ['15', '0'], ['18', '0'], ['19', '0'], ], iterator_to_array($csvFile)); } public function testSkipNoLines() { $fileName = __DIR__ . '/data/simple.csv'; $csvFile = new CsvReader( $fileName, CsvOptions::DEFAULT_DELIMITER, CsvOptions::DEFAULT_ENCLOSURE, CsvOptions::DEFAULT_ESCAPED_BY, 0, ); self::assertEquals(['id', 'isImported'], $csvFile->getHeader()); self::assertEquals([ ['id', 'isImported'], ['15', '0'], ['18', '0'], ['19', '0'], ], iterator_to_array($csvFile)); } public function testSkipsMultipleLines() { $fileName = __DIR__ . '/data/simple.csv'; $csvFile = new CsvReader( $fileName, CsvOptions::DEFAULT_DELIMITER, CsvOptions::DEFAULT_ENCLOSURE, CsvOptions::DEFAULT_ESCAPED_BY, 3, ); self::assertEquals(['id', 'isImported'], $csvFile->getHeader()); self::assertEquals([ ['19', '0'], ], iterator_to_array($csvFile)); } public function testSkipsOverflow() { $fileName = __DIR__ . '/data/simple.csv'; $csvFile = new CsvReader( $fileName, CsvOptions::DEFAULT_DELIMITER, CsvOptions::DEFAULT_ENCLOSURE, CsvOptions::DEFAULT_ESCAPED_BY, 100, ); self::assertEquals(['id', 'isImported'], $csvFile->getHeader()); self::assertEquals([], iterator_to_array($csvFile)); } public function testException() { try { $csv = new CsvReader(__DIR__ . '/nonexistent.csv'); $csv->getHeader(); self::fail('Must throw exception.'); } catch (Exception $e) { self::assertStringContainsString('Cannot open file', $e->getMessage()); self::assertEquals(1, $e->getCode()); } } /** * @dataProvider invalidDelimiterProvider * @param string $delimiter * @param string $message */ public function testInvalidDelimiter($delimiter, $message) { self::expectException(InvalidArgumentException::class); self::expectExceptionMessage($message); new CsvReader(__DIR__ . '/data/test-input.csv', $delimiter); } public function invalidDelimiterProvider() { return [ ['aaaa', 'Delimiter must be a single character. "aaaa" received'], ['🎁', 'Delimiter must be a single character. "\ud83c\udf81" received'], [",\n", 'Delimiter must be a single character. ",\n" received'], ['', 'Delimiter cannot be empty.'], ]; } /** * @dataProvider invalidEnclosureProvider * @param string $enclosure * @param string $message */ public function testInvalidEnclosureShouldThrowException($enclosure, $message) { self::expectException(InvalidArgumentException::class); self::expectExceptionMessage($message); new CsvReader(__DIR__ . '/data/test-input.csv', ',', $enclosure); } public function invalidEnclosureProvider() { return [ ['aaaa', 'Enclosure must be a single character. "aaaa" received'], ['ob g', 'Enclosure must be a single character. "ob g" received'], ]; } /** * @dataProvider invalidSkipLinesProvider * @param mixed $skipLines * @param string $message */ public function testInvalidSkipLines($skipLines, $message) { self::expectException(Exception::class); self::expectExceptionMessage($message); new CsvReader( 'dummy', CsvOptions::DEFAULT_DELIMITER, CsvOptions::DEFAULT_ENCLOSURE, CsvOptions::DEFAULT_ENCLOSURE, $skipLines, ); } public function invalidSkipLinesProvider() { return [ ['invalid', 'Number of lines to skip must be a positive integer. "invalid" received.'], [-123, 'Number of lines to skip must be a positive integer. "-123" received.'], ]; } public function testValidWithoutRewind() { $fileName = __DIR__ . '/data/simple.csv'; $csvFile = new CsvReader($fileName); self::assertTrue($csvFile->valid()); } public function testHeaderNoRewindOnGetHeader() { $fileName = __DIR__ . '/data/simple.csv'; $csvFile = new CsvReader($fileName); $csvFile->rewind(); self::assertEquals(['id', 'isImported'], $csvFile->current()); $csvFile->next(); self::assertEquals(['15', '0'], $csvFile->current()); self::assertEquals(['id', 'isImported'], $csvFile->getHeader()); self::assertEquals(['15', '0'], $csvFile->current()); } public function testLineBreakWithoutRewind() { $fileName = __DIR__ . '/data/simple.csv'; $csvFile = new CsvReader($fileName); self::assertEquals("\n", $csvFile->getLineBreak()); self::assertEquals(['id', 'isImported'], $csvFile->current()); } public function testWriteReadInTheMiddle() { $fileName = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid('csv-test'); $writer = new CsvWriter($fileName); $reader = new CsvReader($fileName); self::assertEquals([], $reader->getHeader()); $rows = [ [ 'col1', 'col2', ], [ '1', 'first', ], [ '2', 'second', ], ]; $writer->writeRow($rows[0]); $reader->next(); self::assertEquals(false, $reader->current(), 'Reader must be at end of file'); $writer->writeRow($rows[1]); $writer->writeRow($rows[2]); $reader->rewind(); $reader->next(); self::assertEquals(['1', 'first'], $reader->current()); $reader->next(); self::assertEquals(['2', 'second'], $reader->current()); $data = file_get_contents($fileName); self::assertEquals( implode( "\n", [ '"col1","col2"' , '"1","first"', '"2","second"', '', ], ), $data, ); } public function testReadPointer() { $fileName = __DIR__ . '/data/simple.csv'; $file = fopen($fileName, 'r'); $csvFile = new CsvReader($file); self::assertEquals(['id', 'isImported'], $csvFile->getHeader()); self::assertEquals([ ['id', 'isImported'], ['15', '0'], ['18', '0'], ['19', '0'], ], iterator_to_array($csvFile)); // check that the file pointer remains valid unset($csvFile); rewind($file); $data = fread($file, 13); self::assertEquals('id,isImported', $data); } public function testInvalidPointer() { $fileName = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid('csv-test'); $file = fopen($fileName, 'w'); $csvFile = new CsvReader($file); self::assertEquals([], $csvFile->getHeader()); self::assertEquals([], iterator_to_array($csvFile)); } public function testInvalidFile() { self::expectException(Exception::class); self::expectExceptionMessage('Invalid file: array'); new CsvReader(['bad']); } /** * @dataProvider getPerformanceTestInputs * @param string $fileContent * @param int $expectedRows * @param float $maxDuration */ public function testPerformance($fileContent, $expectedRows, $maxDuration) { self::markTestSkipped( 'Run this test only manually. Because the duration is very different in local CI environment.', ); try { $fileName = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid('perf-test'); file_put_contents($fileName, $fileContent); $startTime = microtime(true); $reader = new CsvReader($fileName); $rows = 0; foreach ($reader as $line) { $rows++; } $duration = microtime(true) - $startTime; self::assertSame($expectedRows, $rows); self::assertLessThanOrEqual($maxDuration, $duration); } finally { @unlink($fileName); } } public function getPerformanceTestInputs() { yield '1M-simple-rows' => [ str_repeat("abc,def,\"xyz\"\n", 1000000), 1000000, 8.0, ]; yield '1M-empty-lines-n' => [ str_repeat("\n", 1000000), 1000000, 8.0, ]; yield '1M-no-separators' => [ str_repeat(md5('abc') . "\n", 1000000), 1000000, 8.0, ]; } }
php
MIT
a7e5828ceea0e2d8561bb07619c73091e6155c36
2026-01-05T05:16:34.451181Z
false
keboola/php-csv
https://github.com/keboola/php-csv/blob/a7e5828ceea0e2d8561bb07619c73091e6155c36/tests/LineBreaksHelperTest.php
tests/LineBreaksHelperTest.php
<?php declare(strict_types=1); namespace Keboola\Csv\Tests; use Keboola\Csv\LineBreaksHelper; use PHPUnit\Framework\TestCase; class LineBreaksHelperTest extends TestCase { /** * @dataProvider getDataSet * @param string $enclosure * @param string $escapedBy * @param string $input * @param string $expectedOutput * @param string $expectedLineBreak */ public function testLineBreaksDetection($enclosure, $escapedBy, $input, $expectedOutput, $expectedLineBreak) { // Test clear CSV values $output = LineBreaksHelper::clearCsvValues($input, $enclosure, $escapedBy); self::assertSame($expectedOutput, $output); // The same result must be returned when used multiple times $output2 = LineBreaksHelper::clearCsvValues($output, $enclosure, $escapedBy); self::assertSame($expectedOutput, $output2); // Test line breaks detection self::assertSame( json_encode($expectedLineBreak), json_encode(LineBreaksHelper::detectLineBreaks($input, $enclosure, $escapedBy)), ); } public function getDataSet() { $lineEnds = [ 'n' => "\n", 'r' => "\r", 'r-n' => "\r\n", ]; yield 'empty' => [ '"', '', '', '', "\n", ]; yield 'empty-enclosure' => [ '', '', 'col1|col2', 'col1|col2', "\n", ]; yield 'empty-escaped-by' => [ '"', '\\', '', '', "\n", ]; foreach ($lineEnds as $prefix => $lineEnd) { yield "$prefix-empty-enclosure" => [ '', '', implode($lineEnd, [ 'col1,col2', 'abc,def', ]), implode($lineEnd, [ 'col1,col2', 'abc,def', ]), $lineEnd, ]; yield "$prefix-simple" => [ '"', '', implode($lineEnd, [ 'col1,col2', 'line without enclosure,second column', '"enclosure "" in column","hello \"', '"line with enclosure","second column"', '"column with enclosure "", and comma inside text","second column enclosure in text """', ]), implode($lineEnd, [ 'col1,col2', 'line without enclosure,second column', '"",""', '"",""', '"",""', ]), $lineEnd, ]; yield "$prefix-simple-escaped-by" => [ '"', '\\', implode($lineEnd, [ 'col1,col2', 'line without enclosure,second column', '"enclosure \" in column","hello \\\\"', '"line with enclosure","second column"', '"column with enclosure \", and comma inside text","second column enclosure in text \""', ]), implode($lineEnd, [ 'col1,col2', 'line without enclosure,second column', '"",""', '"",""', '"",""', ]), $lineEnd, ]; yield "$prefix-multiline-n" => [ '"', '', implode($lineEnd, [ "\"xyz\",\"\n\n\nabc\n\n\n\"\"\n\n\nxyz\n\n\n\"", '"abc","def"', ]), implode($lineEnd, [ '"",""', '"",""', ]), $lineEnd, ]; yield "$prefix-multiline-r" => [ '"', '', implode($lineEnd, [ "\"xyz\",\"\r\r\rabc\r\r\r\"\"\r\r\rxyz\r\r\r\"", '"abc","def"', ]), implode($lineEnd, [ '"",""', '"",""', ]), $lineEnd, ]; yield "$prefix-multiline-r-n" => [ '"', '', implode($lineEnd, [ "\"xyz\",\"\r\n\r\n\r\nabc\r\n\r\n\r\n\"\"\r\n\r\n\r\nxyz\r\n\r\n\r\n\"", '"abc","def"', ]), implode($lineEnd, [ '"",""', '"",""', ]), $lineEnd, ]; } } }
php
MIT
a7e5828ceea0e2d8561bb07619c73091e6155c36
2026-01-05T05:16:34.451181Z
false
keboola/php-csv
https://github.com/keboola/php-csv/blob/a7e5828ceea0e2d8561bb07619c73091e6155c36/tests/bootstrap.php
tests/bootstrap.php
<?php declare(strict_types=1); ini_set('display_errors', 'true'); error_reporting(-1); require_once __DIR__ . '/../vendor/autoload.php';
php
MIT
a7e5828ceea0e2d8561bb07619c73091e6155c36
2026-01-05T05:16:34.451181Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/LaravelSettingPro.php
src/LaravelSettingPro.php
<?php namespace Sajadsdi\LaravelSettingPro; use Sajadsdi\ArrayDotNotation\Exceptions\ArrayKeyNotFoundException; use Sajadsdi\ArrayDotNotation\Traits\MultiDotNotationTrait; use Sajadsdi\LaravelSettingPro\Concerns\DeleteCallbacksTrait; use Sajadsdi\LaravelSettingPro\Concerns\GetCallbacksTrait; use Sajadsdi\LaravelSettingPro\Concerns\ProcessTrait; use Sajadsdi\LaravelSettingPro\Concerns\SetCallbacksTrait; use Sajadsdi\LaravelSettingPro\Exceptions\SettingKeyNotFoundException; use Sajadsdi\LaravelSettingPro\Exceptions\SettingNotFoundException; use Sajadsdi\LaravelSettingPro\Exceptions\SettingNotSelectedException; use Sajadsdi\LaravelSettingPro\Services\SettingStore; /** * Class LaravelSettingPro * This Class provides methods to get and set settings using array dot notation. * @package Sajadsdi\LaravelSettingPro\LaravelSettingPro */ class LaravelSettingPro { private array $settings = []; private SettingStore $store; private array $config; use ProcessTrait, MultiDotNotationTrait, GetCallbacksTrait, SetCallbacksTrait, DeleteCallbacksTrait; /** * Constructor for Laravel Setting Pro class. * * @param SettingStore $store Instance of SettingStore for storing settings. */ public function __construct(array $config, SettingStore $store) { $this->config = $config; $this->store = $store; } /** * Get the value of a setting using array dot notation. * * @param string $settingName Name of the setting to get. * @param mixed $Keys Keys to access nested values in the setting. * @param mixed|null $default Default value to return if the setting or key is not found. * @param bool $throw flag to disable 'NotFound' exceptions * @return mixed Value of the setting. * * @throws SettingKeyNotFoundException If the specified key is not found in the setting. * @throws SettingNotFoundException If the specified setting is not found. * @throws SettingNotSelectedException If no setting is selected. */ public function get(string $settingName, mixed $Keys = [], mixed $default = null, bool $throw = true): mixed { $this->load($settingName, 'get'); try { return $this->getByDotMulti( $this->getSetting($settingName), $this->getArrayKeys($Keys), $default, $this->getCallbackDefaultValueOperation($settingName) ); } catch (ArrayKeyNotFoundException $exception) { if ($throw) { if ($this->settings[$settingName]) { throw new SettingKeyNotFoundException($exception->key, $exception->keysPath, $settingName); } else { throw new SettingNotFoundException($settingName); } } } return null; } /** * Set the value of a setting using array dot notation. * * @param string $settingName Name of the setting to set. * @param array $keyValue Associative array of keys and values to set in the setting. * @return void * * @throws SettingNotSelectedException If no setting is selected. */ public function set(string $settingName, array $keyValue): void { $this->load($settingName, 'set'); $this->setByDotMulti($this->settings[$settingName], $keyValue, $this->getCallbackSetOperation($settingName)); } /** * Delete the keys of a setting using array dot notation. * * @param string $settingName Name of the setting to delete. * @param array|string|int $keys keys to delete in the setting. * @return void * * @throws ArrayKeyNotFoundException * @throws SettingNotSelectedException If no setting is selected. */ public function delete(string $settingName, mixed $keys = []): void { $this->load($settingName, 'delete'); $aKeys = $this->getArrayKeys($keys); if (!$aKeys) { $this->setSetting($settingName, []); $this->addToDelete($settingName, $aKeys); $this->removeFromSet($settingName); } else { $this->deleteByDotMulti($this->settings[$settingName], $aKeys, false, $this->getCallbackDeleteOperation($settingName)); } } /** * Has key(S) on selected setting. * * @param string $settingName Name of the setting. * @param mixed $keys to check has exists on setting. * @return bool * * @throws SettingNotSelectedException */ public function has(string $settingName, mixed $keys = []): bool { $this->load($settingName, 'has'); return $this->issetAll($this->getSetting($settingName), $this->getArrayKeys($keys)); } /** * Load a setting and validate that it exists. * * @param string $setting Name of the setting to load. * @param string $operation Name of the operation being performed (get or set or delete). * @return void * * @throws SettingNotSelectedException If no setting is selected. */ private function load(string $setting, string $operation): void { if (!$setting) { throw new SettingNotSelectedException($operation); } if ($this->isSetSetting($setting)) { $this->setSetting($setting, $this->store->get($setting) ?? []); } } /** * Set the value of a setting. * * @param string $name Name of the setting to set. * @param mixed $data Value to set in the setting. * @return void */ private function setSetting(string $name, mixed $data): void { $this->settings[$name] = $data; } /** * Get the value of a setting. * * @param string $name Name of the setting to get. * @return mixed Value of the setting. */ private function getSetting(string $name): mixed { return $this->settings[$name] ?? $this->settings[$name] = []; } /** * check Setting name is seated. * @param string $setting * @return bool */ private function isSetSetting(string $setting): bool { return !isset($this->settings[$setting]); } }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Jobs/DeleteSettingJob.php
src/Jobs/DeleteSettingJob.php
<?php namespace Sajadsdi\LaravelSettingPro\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Sajadsdi\ArrayDotNotation\Exceptions\ArrayKeyNotFoundException; use Sajadsdi\ArrayDotNotation\Traits\MultiDotNotationTrait; use Sajadsdi\LaravelSettingPro\Events\DeleteSettingEvent; use Sajadsdi\LaravelSettingPro\Services\SettingStore; class DeleteSettingJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, MultiDotNotationTrait; /** * Create a new job instance. */ public function __construct(public string $settingName, public array $keys, public bool $cacheEnabled, public bool $triggerEvent, string $queue) { $this->onQueue($queue); } /** * Execute the job. * @throws ArrayKeyNotFoundException */ public function handle(SettingStore $store): void { $oldData = $store->getSetting($this->settingName) ?? []; $data = $oldData; if (!$this->keys) { $store->delete($this->settingName); } else { $store->set($this->settingName, $this->deleteByDotMulti($data, $this->keys)); } if ($this->cacheEnabled) { $store->cache()->clear($this->settingName); } if ($this->triggerEvent) { DeleteSettingEvent::dispatch($this->settingName, $this->keys, $oldData); } } }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false
sajadsdi/laravel-setting-pro
https://github.com/sajadsdi/laravel-setting-pro/blob/20036746f3ed7650ae6ee2a0c4b99ce22382deb9/src/Jobs/UpdateSettingJob.php
src/Jobs/UpdateSettingJob.php
<?php namespace Sajadsdi\LaravelSettingPro\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Sajadsdi\ArrayDotNotation\Traits\MultiDotNotationTrait; use Sajadsdi\LaravelSettingPro\Events\UpdateSettingEvent; use Sajadsdi\LaravelSettingPro\Services\SettingStore; class UpdateSettingJob implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, MultiDotNotationTrait; /** * Create a new job instance. */ public function __construct(public string $settingName, public array $keyValue, public bool $cacheEnabled, public bool $triggerEvent, string $queue) { $this->onQueue($queue); } /** * Execute the job. */ public function handle(SettingStore $store): void { $oldData = $store->getSetting($this->settingName) ?? []; $data = $oldData; $store->set($this->settingName, $this->setByDotMulti($data, $this->keyValue)); if ($this->cacheEnabled) { $store->cache()->clear($this->settingName); } if ($this->triggerEvent) { UpdateSettingEvent::dispatch($this->settingName, $this->keyValue, $oldData); } } }
php
MIT
20036746f3ed7650ae6ee2a0c4b99ce22382deb9
2026-01-05T05:16:47.821511Z
false