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 |
|---|---|---|---|---|---|---|---|---|
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2022_07_07_203511_convert_settings_to_json.php | database/migrations/2022_07_07_203511_convert_settings_to_json.php | <?php
use App\Models\Setting;
use Illuminate\Database\Migrations\Migration;
return new class extends Migration
{
public function up(): void
{
Setting::all()->each(static function (Setting $setting): void {
$setting->value = unserialize($setting->getRawOriginal('value'));
$setting->save();
});
}
};
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2015_11_23_074723_create_playlists_table.php | database/migrations/2015_11_23_074723_create_playlists_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePlaylistsTable extends Migration
{
public function up(): void
{
Schema::create('playlists', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('name');
$table->timestamps();
});
Schema::table('playlists', static function (Blueprint $table): void {
$table->foreign('user_id')->references('id')->on('users');
});
}
public function down(): void
{
Schema::drop('playlists');
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2024_03_26_094029_add_playlist_folder_playlist_table.php | database/migrations/2024_03_26_094029_add_playlist_folder_playlist_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('playlist_playlist_folder', static function (Blueprint $table): void {
$table->string('folder_id', 36)->nullable(false);
$table->string('playlist_id', 36)->nullable(false);
});
Schema::table('playlist_playlist_folder', static function (Blueprint $table): void {
$table->foreign('folder_id')
->references('id')
->on('playlist_folders')
->cascadeOnDelete()
->cascadeOnUpdate();
$table->foreign('playlist_id')
->references('id')
->on('playlists')
->cascadeOnDelete()
->cascadeOnUpdate();
$table->unique(['folder_id', 'playlist_id']);
});
DB::table('playlists')->whereNotNull('folder_id')->get()->each(static function ($playlist): void {
// There might be some data inconsistency, so we need to check if the folder exists first.
if (DB::table('playlist_folders')->find($playlist->folder_id) === null) {
return;
}
DB::table('playlist_playlist_folder')->insert([
'folder_id' => $playlist->folder_id,
'playlist_id' => $playlist->id,
]);
});
Schema::table('playlists', static function (Blueprint $table): void {
Schema::withoutForeignKeyConstraints(static function () use ($table): void {
$table->dropForeign(['folder_id']);
$table->dropColumn('folder_id');
});
});
}
};
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2025_06_07_160704_add_transcodes_table.php | database/migrations/2025_06_07_160704_add_transcodes_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('transcodes', static function (Blueprint $table): void {
$table->string('id', 36)->primary();
$table->string('song_id')->index();
$table->integer('bit_rate');
$table->text('location');
$table->string('hash', 32);
$table->unique(['song_id', 'bit_rate']);
$table->timestamps();
$table->foreign('song_id')->references('id')->on('songs')->cascadeOnDelete()->cascadeOnUpdate();
});
}
};
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2024_01_16_223632_add_timestamps_and_user_id_into_playlist_song_table.php | database/migrations/2024_01_16_223632_add_timestamps_and_user_id_into_playlist_song_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up(): void
{
Schema::disableForeignKeyConstraints();
Schema::table('playlist_song', static function (Blueprint $table): void {
$table->unsignedInteger('user_id')->nullable()->index();
$table->foreign('user_id')->references('id')->on('users')->cascadeOnDelete()->cascadeOnUpdate();
$table->timestamps();
});
DB::table('playlists')->get()->each(static function ($playlist): void {
DB::table('playlist_song')->where('playlist_id', $playlist->id)->update([
'user_id' => $playlist->user_id,
'created_at' => now(),
'updated_at' => now(),
]);
});
Schema::table('playlist_song', static function (Blueprint $table): void {
$table->unsignedInteger('user_id')->nullable(false)->change();
});
Schema::enableForeignKeyConstraints();
}
};
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2024_02_24_085736_add_playlist_cover.php | database/migrations/2024_02_24_085736_add_playlist_cover.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('playlists', static function (Blueprint $table): void {
$table->string('cover')->nullable();
});
}
};
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2023_08_20_122210_support_user_invitation.php | database/migrations/2023_08_20_122210_support_user_invitation.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
return new class extends Migration
{
public function up(): void
{
Schema::table('users', static function (Blueprint $table): void {
$table->string('invitation_token', 36)->nullable()->index();
$table->timestamp('invited_at')->nullable();
$table->timestamp('invitation_accepted_at')->nullable();
$table->unsignedInteger('invited_by_id')->nullable();
$table->foreign('invited_by_id')->references('id')->on('users')->nullOnDelete();
});
}
};
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2015_12_22_092542_add_image_to_artists_table.php | database/migrations/2015_12_22_092542_add_image_to_artists_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddImageToArtistsTable extends Migration
{
public function up(): void
{
Schema::table('artists', static function (Blueprint $table): void {
$table->string('image')->nullable()->after('name');
});
}
public function down(): void
{
Schema::table('artists', static function (Blueprint $table): void {
$table->dropColumn('image');
});
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2024_01_16_215642_use_uuids_for_playlists.php | database/migrations/2024_01_16_215642_use_uuids_for_playlists.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
return new class extends Migration {
public function up(): void
{
Schema::disableForeignKeyConstraints();
if (DB::getDriverName() !== 'sqlite') {
Schema::table('playlist_song', static function (Blueprint $table): void {
$table->dropForeign(['playlist_id']);
});
}
Schema::table('playlists', static function (Blueprint $table): void {
$table->string('id', 36)->change();
});
Schema::table('playlist_song', static function (Blueprint $table): void {
$table->string('playlist_id', 36)->change();
$table->foreign('playlist_id')->references('id')->on('playlists')->cascadeOnDelete()->cascadeOnUpdate();
});
DB::table('playlists')->get()->each(static function (object $playlist): void {
$oldId = $playlist->id;
$newId = Str::uuid()->toString();
DB::table('playlists')->where('id', $oldId)->update(['id' => $newId]);
DB::table('playlist_song')->where('playlist_id', $oldId)->update(['playlist_id' => $newId]);
});
Schema::enableForeignKeyConstraints();
}
};
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2022_10_18_064917_add_index_to_postgresql.php | database/migrations/2022_10_18_064917_add_index_to_postgresql.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up(): void
{
Schema::table('songs', static function (Blueprint $table): void {
if (DB::getDriverName() === 'pgsql') {
$table->index('album_id');
}
});
}
};
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2025_09_21_063859_create_default_roles_and_permissions.php | database/migrations/2025_09_21_063859_create_default_roles_and_permissions.php | <?php
use App\Enums\Acl\Permission;
use App\Enums\Acl\Role;
use Illuminate\Database\Migrations\Migration;
use Spatie\Permission\Models\Permission as PermissionModel;
use Spatie\Permission\Models\Role as RoleModel;
return new class extends Migration {
public function up(): void
{
foreach (Permission::cases() as $permission) {
PermissionModel::findOrCreate($permission->value);
}
RoleModel::findOrCreate(Role::ADMIN->value)
->givePermissionTo(Permission::cases());
RoleModel::findOrCreate(Role::MANAGER->value)
->givePermissionTo([
Permission::MANAGE_USERS,
Permission::MANAGE_PODCASTS,
Permission::MANAGE_SONGS,
Permission::MANAGE_RADIO_STATIONS,
]);
RoleModel::findOrCreate(Role::USER->value);
}
};
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2015_11_23_074713_create_songs_table.php | database/migrations/2015_11_23_074713_create_songs_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateSongsTable extends Migration
{
public function up(): void
{
Schema::create('songs', static function (Blueprint $table): void {
$table->string('id', 32)->primary();
$table->integer('album_id')->unsigned();
$table->string('title');
$table->float('length');
$table->text('lyrics');
$table->text('path');
$table->integer('mtime');
$table->timestamps();
});
Schema::table('songs', static function (Blueprint $table): void {
$table->foreign('album_id')->references('id')->on('albums');
});
}
public function down(): void
{
Schema::drop('songs');
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2025_07_20_165510_promote_public_ids.php | database/migrations/2025_07_20_165510_promote_public_ids.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up(): void
{
Schema::disableForeignKeyConstraints();
if (DB::getDriverName() === 'mysql' || DB::getDriverName() === 'mariadb') {
DB::statement("SET sql_mode = ''");
}
DB::dropForeignKeyIfExists('albums', 'artist_id');
DB::dropForeignKeyIfExists('songs', 'artist_id');
DB::dropForeignKeyIfExists('songs', 'album_id');
if (DB::getDriverName() === 'sqlite') {
// SQLite does not support dropping columns directly, so we need to
// 1. create a new table with the same structure but with the new primary key
// 2. copy the data from the old table to the new table
// 3. drop the old table
// 4. rename the new table to the old table name
Schema::create('artists_new', static function (Blueprint $table): void {
$table->string('id', 26)->primary();
$table->string('name');
$table->string('image')->nullable();
$table->foreignId('user_id')->constrained('users')->cascadeOnDelete()->cascadeOnUpdate();
$table->timestamps();
});
DB::table('artists_new')->insert(DB::table('artists')->get()->map(static function ($artist) {
return [
'id' => $artist->public_id,
'name' => $artist->name,
'image' => $artist->image,
'user_id' => $artist->user_id,
'created_at' => $artist->created_at,
'updated_at' => $artist->updated_at,
];
})->toArray());
Schema::dropIfExists('artists');
Schema::rename('artists_new', 'artists');
// Same for albums
Schema::create('albums_new', static function (Blueprint $table): void {
$table->string('id', 26)->primary();
$table->string('name');
$table->string('cover')->nullable();
$table->string('artist_id', 26);
$table->string('artist_name', 26)->nullable();
$table->smallInteger('year')->nullable();
$table->foreignId('user_id')->constrained('users')->cascadeOnDelete()->cascadeOnUpdate();
$table->timestamps();
});
DB::table('albums_new')->insert(DB::table('albums')->get()->map(static function ($album) {
return [
'id' => $album->public_id,
'name' => $album->name,
'cover' => $album->cover,
'artist_id' => $album->artist_ulid,
'artist_name' => $album->artist_name,
'year' => $album->year,
'user_id' => $album->user_id,
'created_at' => $album->created_at,
'updated_at' => $album->updated_at,
];
})->toArray());
Schema::dropIfExists('albums');
Schema::rename('albums_new', 'albums');
} else {
// For other databases, we can just rename the column
Schema::table('artists', static function (Blueprint $table): void {
$table->dropColumn('id');
$table->renameColumn('public_id', 'id');
$table->primary('id');
});
Schema::table('albums', static function (Blueprint $table): void {
$table->dropColumn(['id', 'artist_id']);
});
Schema::table('albums', static function (Blueprint $table): void {
$table->renameColumn('public_id', 'id');
$table->renameColumn('artist_ulid', 'artist_id');
});
Schema::table('albums', static function (Blueprint $table): void {
$table->primary('id');
});
}
// Now we can add the foreign key back
Schema::table('albums', static function (Blueprint $table): void {
$table->foreign('artist_id')->references('id')->on('artists')->cascadeOnDelete()->cascadeOnUpdate();
});
Schema::table('songs', static function (Blueprint $table): void {
// since SQLite doesn't support dropping indexed columns, we need to drop the foreign keys first
if (DB::getDriverName() === 'sqlite') {
$table->dropForeign(['artist_id']);
$table->dropForeign(['album_id']);
}
$table->dropColumn(['artist_id', 'album_id']);
$table->renameColumn('artist_ulid', 'artist_id');
$table->renameColumn('album_ulid', 'album_id');
// add the foreign keys back for SQLite
if (DB::getDriverName() === 'sqlite') {
$table->foreign('artist_id')->references('id')->on('artists')->cascadeOnDelete()->cascadeOnUpdate();
$table->foreign('album_id')->references('id')->on('albums')->cascadeOnDelete()->cascadeOnUpdate();
}
});
Schema::table('songs', static function (Blueprint $table): void {
$table->foreign('artist_id')->references('id')->on('artists')->cascadeOnDelete()->cascadeOnUpdate();
$table->foreign('album_id')->references('id')->on('albums')->cascadeOnDelete()->cascadeOnUpdate();
});
Schema::enableForeignKeyConstraints();
}
};
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2024_05_08_094243_create_podcast_related_tables.php | database/migrations/2024_05_08_094243_create_podcast_related_tables.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('podcasts', static function (Blueprint $table): void {
$table->string('id', 36)->primary();
$table->string('url')->unique()->comment('The URL to the podcast feed')->unique();
$table->string('link')->comment('The link to the podcast website');
$table->text('title');
$table->text('image');
$table->string('author')->nullable();
$table->text('description');
$table->json('categories');
$table->boolean('explicit');
$table->string('language');
$table->json('metadata');
$table->unsignedInteger('added_by')->nullable();
$table->timestamp('last_synced_at');
$table->timestamps();
});
Schema::table('podcasts', static function (Blueprint $table): void {
$table->foreign('added_by')->references('id')->on('users')->nullOnDelete();
});
Schema::table('songs', static function (Blueprint $table): void {
$table->unsignedInteger('artist_id')->nullable()->change();
$table->unsignedInteger('album_id')->nullable()->change();
$table->unsignedInteger('owner_id')->nullable()->change();
$table->string('podcast_id', 36)->nullable();
$table->string('episode_guid')->nullable()->unique();
$table->json('episode_metadata')->nullable();
$table->foreign('podcast_id')->references('id')->on('podcasts')->cascadeOnDelete();
});
Schema::create('podcast_user', static function (Blueprint $table): void {
$table->id();
$table->unsignedInteger('user_id');
$table->string('podcast_id', 36);
$table->json('state')->nullable();
$table->timestamps();
});
Schema::table('podcast_user', static function (Blueprint $table): void {
$table->foreign('user_id')->references('id')->on('users')->cascadeOnDelete();
$table->foreign('podcast_id')->references('id')->on('podcasts')->cascadeOnDelete();
});
}
};
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2025_09_04_055648_add_description_to_playlists_table.php | database/migrations/2025_09_04_055648_add_description_to_playlists_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('playlists', static function (Blueprint $table): void {
$table->text('description')->default('')->after('name');
});
}
};
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2015_11_23_074709_create_albums_table.php | database/migrations/2015_11_23_074709_create_albums_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAlbumsTable extends Migration
{
public function up(): void
{
Schema::create('albums', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('artist_id')->unsigned();
$table->string('name');
$table->string('cover')->default('');
$table->timestamps();
});
Schema::table('albums', static function (Blueprint $table): void {
$table->foreign('artist_id')->references('id')->on('artists')->onDelete('cascade');
});
}
public function down(): void
{
Schema::drop('albums');
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2025_07_20_165224_migrate_foreign_keys_to_ulid.php | database/migrations/2025_07_20_165224_migrate_foreign_keys_to_ulid.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up(): void
{
Schema::table('albums', static function (Blueprint $table): void {
$table->string('artist_ulid', 26)->nullable()->after('artist_id');
});
Schema::table('songs', static function (Blueprint $table): void {
$table->string('artist_ulid', 26)->nullable()->after('artist_id');
$table->string('album_ulid', 26)->nullable()->after('album_id');
});
}
};
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2017_11_27_184010_add_disc_into_songs.php | database/migrations/2017_11_27_184010_add_disc_into_songs.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddDiscIntoSongs extends Migration
{
public function up(): void
{
Schema::table('songs', static function (Blueprint $table): void {
$table->integer('disc')->after('track')->default(1);
});
}
public function down(): void
{
Schema::table('songs', static function (Blueprint $table): void {
$table->dropColumn('disc');
});
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2016_06_16_134516_cascade_delete_user.php | database/migrations/2016_06_16_134516_cascade_delete_user.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class CascadeDeleteUser extends Migration
{
public function up(): void
{
Schema::table('playlists', static function (Blueprint $table): void {
if (DB::getDriverName() !== 'sqlite') { // @phpstan-ignore-line
$table->dropForeign('playlists_user_id_foreign');
}
$table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
});
}
public function down(): void
{
Schema::table('playlists', static function (Blueprint $table): void {
if (DB::getDriverName() !== 'sqlite') { // @phpstan-ignore-line
$table->dropForeign('playlists_user_id_foreign');
}
$table->foreign('user_id')->references('id')->on('users');
});
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2016_04_15_121215_add_is_complilation_into_albums.php | database/migrations/2016_04_15_121215_add_is_complilation_into_albums.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddIsComplilationIntoAlbums extends Migration
{
/**
* Run the migrations.
*
*/
public function up(): void
{
Schema::table('albums', static function (Blueprint $table): void {
$table->boolean('is_compilation')->nullable()->default(false)->after('cover');
});
}
/**
* Reverse the migrations.
*
*/
public function down(): void
{
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2018_11_03_182520_add_rules_into_playlists.php | database/migrations/2018_11_03_182520_add_rules_into_playlists.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddRulesIntoPlaylists extends Migration
{
public function up(): void
{
Schema::table('playlists', static function (Blueprint $table): void {
$table->text('rules')->after('name')->nullable();
});
}
public function down(): void
{
Schema::table('playlists', static function (Blueprint $table): void {
$table->dropColumn('rules');
});
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2021_12_06_164648_increase_string_columns_length.php | database/migrations/2021_12_06_164648_increase_string_columns_length.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class IncreaseStringColumnsLength extends Migration
{
public function up(): void
{
Schema::table('artists', static function (Blueprint $table): void {
$table->dropUnique('artists_name_unique');
});
Schema::table('artists', static function (Blueprint $table): void {
$table->string('name', (2 ** 12) - 32)->change();
});
Schema::table('albums', static function (Blueprint $table): void {
$table->string('name', (2 ** 12) - 32)->change();
});
Schema::table('playlists', static function (Blueprint $table): void {
$table->string('name', (2 ** 12) - 32)->change();
});
Schema::table('songs', static function (Blueprint $table): void {
$table->string('title', (2 ** 12) - 32)->change();
});
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2024_02_05_171703_add_storage_into_songs_table.php | database/migrations/2024_02_05_171703_add_storage_into_songs_table.php | <?php
use App\Enums\SongStorageType;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('songs', static function (Blueprint $table): void {
$table->string('storage')->nullable()->index();
});
DB::table('songs')->where('path', 'like', 's3://%')->update([
'storage' => SongStorageType::S3_LAMBDA->value,
]);
}
};
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2024_01_03_104241_support_multi_tenant.php | database/migrations/2024_01_03_104241_support_multi_tenant.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up(): void
{
Schema::table('songs', static function (Blueprint $table): void {
$table->unsignedInteger('owner_id')->nullable();
$table->foreign('owner_id')->references('id')->on('users')->cascadeOnUpdate()->cascadeOnDelete();
$table->boolean('is_public')->default(false)->index();
});
Schema::table('songs', static function (): void {
$firstAdmin = DB::table('users')->oldest()->first();
if (!$firstAdmin) {
return;
}
// make sure all existing songs are accessible by all users and assuming the first admin "owns" them
DB::table('songs')->update([
'owner_id' => $firstAdmin->id,
'is_public' => true,
]);
});
}
};
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2025_07_18_105237_favorites.php | database/migrations/2025_07_18_105237_favorites.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
if (DB::getDriverName() === 'mysql' || DB::getDriverName() === 'mariadb') {
DB::statement("SET sql_mode = ''");
}
Schema::create('favorites', static function (Blueprint $table): void {
$table->id();
$table->unsignedInteger('user_id');
$table->string('favoriteable_id', 36);
$table->string('favoriteable_type')->default('playable');
$table->timestamp('created_at')->useCurrent();
$table->unique(['user_id', 'favoriteable_id', 'favoriteable_type']);
$table->index(['user_id', 'favoriteable_type']);
});
DB::table('interactions')
->where('liked', true)
->orderBy('created_at')
->each(static function (object $favorite): void {
DB::table('favorites')
->insert([
'user_id' => $favorite->user_id,
'favoriteable_id' => $favorite->song_id,
'favoriteable_type' => 'playable',
'created_at' => $favorite->created_at,
]);
});
Schema::table('interactions', static function (Blueprint $table): void {
$table->dropColumn('liked');
});
Schema::table('favorites', static function (Blueprint $table): void {
$table->foreign('user_id')->references('id')->on('users');
});
}
};
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2015_12_18_072523_add_preferences_to_users_table.php | database/migrations/2015_12_18_072523_add_preferences_to_users_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddPreferencesToUsersTable extends Migration
{
public function up(): void
{
Schema::table('users', static function (Blueprint $table): void {
$table->text('preferences')->after('is_admin')->nullable();
});
}
public function down(): void
{
Schema::table('users', static function (Blueprint $table): void {
$table->dropColumn('preferences');
});
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2025_05_15_172148_create_audits_table.php | database/migrations/2025_05_15_172148_create_audits_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAuditsTable extends Migration
{
public function up(): void
{
$connection = config('audit.drivers.database.connection', config('database.default'));
$table = config('audit.drivers.database.table', 'audits');
Schema::connection($connection)->create($table, static function (Blueprint $table): void {
$morphPrefix = config('audit.user.morph_prefix', 'user');
$table->bigIncrements('id');
$table->string($morphPrefix . '_type')->nullable();
$table->unsignedBigInteger($morphPrefix . '_id')->nullable();
$table->string('event');
$table->morphs('auditable');
$table->text('old_values')->nullable();
$table->text('new_values')->nullable();
$table->text('url')->nullable();
$table->ipAddress('ip_address')->nullable();
$table->string('user_agent', 1023)->nullable();
$table->string('tags')->nullable();
$table->timestamps();
$table->index([$morphPrefix . '_id', $morphPrefix . '_type']);
});
}
public function down(): void
{
$connection = config('audit.drivers.database.connection', config('database.default'));
$table = config('audit.drivers.database.table', 'audits');
Schema::connection($connection)->drop($table);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2024_03_19_204549_add_user_avatar.php | database/migrations/2024_03_19_204549_add_user_avatar.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('users', static function (Blueprint $table): void {
$table->string('avatar')->nullable();
});
}
};
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2025_05_28_125915_add_hash_to_folders_table.php | database/migrations/2025_05_28_125915_add_hash_to_folders_table.php | <?php
use App\Models\Folder;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('folders', static function (Blueprint $table): void {
$table->string('hash', 32)->unique()->nullable();
});
Folder::all()->each(static function (Folder $folder): void {
$folder->hash = simple_hash($folder->path);
$folder->save();
});
}
};
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2024_01_12_101606_add_own_songs_only_into_playlists_table.php | database/migrations/2024_01_12_101606_add_own_songs_only_into_playlists_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('playlists', static function (Blueprint $table): void {
$table->boolean('own_songs_only')->default(false);
});
}
};
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2015_11_25_033351_create_settings_table.php | database/migrations/2015_11_25_033351_create_settings_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateSettingsTable extends Migration
{
public function up(): void
{
Schema::create('settings', static function (Blueprint $table): void {
$table->string('key');
$table->text('value');
$table->primary('key');
});
}
public function down(): void
{
Schema::drop('settings');
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2019_12_14_000001_create_personal_access_tokens_table.php | database/migrations/2019_12_14_000001_create_personal_access_tokens_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePersonalAccessTokensTable extends Migration
{
public function up(): void
{
Schema::create('personal_access_tokens', static function (Blueprint $table): void {
$table->bigIncrements('id');
$table->morphs('tokenable');
$table->string('name');
$table->string('token', 64)->unique();
$table->text('abilities')->nullable();
$table->timestamp('last_used_at')->nullable();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('personal_access_tokens');
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2017_04_21_092159_copy_artist_to_contributing_artist.php | database/migrations/2017_04_21_092159_copy_artist_to_contributing_artist.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
class CopyArtistToContributingArtist extends Migration
{
public function up(): void
{
DB::table('songs')
->join('albums', 'songs.album_id', '=', 'albums.id')
->join('artists', 'albums.artist_id', '=', 'artists.id')
->get(['songs.id', 'songs.contributing_artist_id', 'artists.id as artist_id'])
->each(static function ($song): void {
if (!$song->contributing_artist_id) {
DB::table('songs')
->where('id', $song->id)
->update(['contributing_artist_id' => $song->artist_id]);
}
});
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2025_09_12_133454_add_embeds_table.php | database/migrations/2025_09_12_133454_add_embeds_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('embeds', static function (Blueprint $table): void {
$table->string('id', 26)->primary();
$table->unsignedInteger('user_id');
$table->string('embeddable_id', 36)->index();
$table->string('embeddable_type');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->cascadeOnDelete()->cascadeOnUpdate();
});
}
};
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2024_03_28_132619_add_user_sso_provider.php | database/migrations/2024_03_28_132619_add_user_sso_provider.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('users', static function (Blueprint $table): void {
$table->string('sso_provider')->nullable();
});
}
};
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2024_01_17_104332_create_playlist_collaboration_tokens_table.php | database/migrations/2024_01_17_104332_create_playlist_collaboration_tokens_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('playlist_collaboration_tokens', static function (Blueprint $table): void {
$table->id();
$table->string('playlist_id', 36)->nullable(false);
$table->string('token', 36)->unique();
$table->timestamps();
});
Schema::table('playlist_collaboration_tokens', static function (Blueprint $table): void {
$table->foreign('playlist_id')->references('id')->on('playlists')->cascadeOnDelete()->cascadeOnUpdate();
});
}
};
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2025_07_11_100738_remove_own_songs_only_setting.php | database/migrations/2025_07_11_100738_remove_own_songs_only_setting.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('playlists', static function (Blueprint $table): void {
$table->dropColumn('own_songs_only');
});
}
};
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2025_08_27_144419_add_hash_to_songs_table.php | database/migrations/2025_08_27_144419_add_hash_to_songs_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('songs', static function (Blueprint $table): void {
$table->string('hash')->nullable()->after('path');
});
}
};
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2024_01_27_171649_add_position_into_playlists_table.php | database/migrations/2024_01_27_171649_add_position_into_playlists_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('playlist_song', static function (Blueprint $table): void {
$table->unsignedInteger('position')->index()->default(0);
});
}
};
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/migrations/2021_06_04_153259_convert_user_preferences_from_array_to_json.php | database/migrations/2021_06_04_153259_convert_user_preferences_from_array_to_json.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
class ConvertUserPreferencesFromArrayToJson extends Migration
{
public function up(): void
{
DB::table('users')
->get()
->each(static function ($user): void {
rescue(static function () use ($user): void {
$preferences = unserialize($user->preferences);
if (!is_array($preferences)) {
$preferences = [];
}
DB::table('users')
->where('id', $user->id)
->update(['preferences' => json_encode($preferences)]);
});
});
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/seeders/DatabaseSeeder.php | database/seeders/DatabaseSeeder.php | <?php
namespace Database\Seeders;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
public function run(): void
{
Model::unguard();
$this->call(SettingTableSeeder::class);
Model::reguard();
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/database/seeders/SettingTableSeeder.php | database/seeders/SettingTableSeeder.php | <?php
namespace Database\Seeders;
use App\Models\Setting;
use Illuminate\Database\Seeder;
class SettingTableSeeder extends Seeder
{
public function run(): void
{
Setting::set('media_path', '');
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/resources/lang/en/passwords.php | resources/lang/en/passwords.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Password Reminder 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 | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/resources/lang/en/pagination.php | 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' => '« Previous',
'next' => 'Next »',
];
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/resources/lang/en/validation.php | 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.',
'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.',
'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.',
'email' => 'The :attribute must be a valid email address.',
'exists' => 'The selected :attribute is invalid.',
'filled' => 'The :attribute field is required.',
'image' => 'The :attribute must be an image.',
'in' => 'The selected :attribute is invalid.',
'integer' => 'The :attribute must be an integer.',
'ip' => 'The :attribute must be a valid IP 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.',
'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.',
'numeric' => 'The :attribute must be a number.',
'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.',
'url' => 'The :attribute format is invalid.',
'path' => [
'valid' => 'The :attribute is not a valid or readable path.',
],
'uploaded' => 'The :attribute failed to upload.',
/*
|--------------------------------------------------------------------------
| 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' => [
],
/*
|--------------------------------------------------------------------------
| 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' => [],
];
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/resources/lang/en/auth.php | 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 | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/resources/lang/es/passwords.php | resources/lang/es/passwords.php | <?php
return [
/*
|--------------------------------------------------------------------------
| Password Reminder 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' => 'Las contraseñas deben tener al menos seis caracteres y coincidir con la confirmación.',
'reset' => '¡Tu contraseña ha sido reestablecida!',
'sent' => '¡Hemos enviado por correo electrónico el enlace para reestablecer contraseña!',
'token' => 'Este token de reestablecimiento de contraseña no es válido.',
'user' => 'No podemos encontrar un usuario con ese correo electrónico.',
];
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/resources/lang/es/pagination.php | resources/lang/es/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' => '« Anterior',
'next' => 'Siguiente »',
];
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/resources/lang/es/validation.php | resources/lang/es/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' => 'El :attribute debe ser aceptado.',
'active_url' => 'El :attribute no es una URL válida.',
'after' => 'El :attribute debe ser una fecha posterior a :date.',
'alpha' => 'El :attribute solo puede contener letras.',
'alpha_dash' => 'El :attribute solo puede contener letras, números y guiones.',
'alpha_num' => 'El :attribute solo puede contener letras y números.',
'array' => 'El :attribute debe ser un arreglo.',
'before' => 'El :attribute debe ser una fecha anterior a :date.',
'between' => [
'numeric' => 'El :attribute debe estar entre :min y :max.',
'file' => 'El :attribute debe estar entre :min y :max kilobytes.',
'string' => 'El :attribute must be between :min y :max caracteres.',
'array' => 'El :attribute debe tener entre :min y :max elementos.',
],
'boolean' => 'El campo :attribute debe ser verdadero o falso.',
'confirmed' => 'El :attribute confirmación no coincide.',
'date' => 'El :attribute no es una fecha válida.',
'date_format' => 'El :attribute no coincide con el formato :format.',
'different' => 'El :attribute y :other deben ser diferentes.',
'digits' => 'El :attribute debe ser de :digits dígitos.',
'digits_between' => 'El :attribute debe estar entre :min y :max dígitos.',
'email' => 'El :attribute debe ser un correo electrónico válido.',
'exists' => 'El :attribute seleccionado no es válido.',
'filled' => 'El campo :attribute es requerido.',
'image' => 'El :attribute debe ser una imagen.',
'in' => 'El :attribute seleccionado no es válido.',
'integer' => 'El :attribute debe ser un entero.',
'ip' => 'El :attribute debe ser una dirección IP válida.',
'json' => 'El :attribute debe ser una cadena JSON válida.',
'max' => [
'numeric' => 'El :attribute no puede ser mayor que :max.',
'file' => 'El :attribute no puede ser mayor que :max kilobytes.',
'string' => 'El :attribute no puede ser mayor que :max caracteres.',
'array' => 'El :attribute no puede tener mas de :max elementos.',
],
'mimes' => 'El :attribute debe ser un archivo de tipo: :values.',
'min' => [
'numeric' => 'El :attribute debe ser al menos de :min.',
'file' => 'El :attribute debe ser al menos de :min kilobytes.',
'string' => 'El :attribute debe ser al menos de :min caracteres.',
'array' => 'El :attribute debe tener al menos :min elementos.',
],
'not_in' => 'El :attribute seleccionado no es válido.',
'numeric' => 'El :attribute debe ser numérico.',
'regex' => 'El formato de :attribute no es válido.',
'required' => 'El campo :attribute es requerido.',
'required_if' => 'El campo :attribute es requerido cuando :other es :value.',
'required_unless' => 'El campo :attribute es requerido a menos que :other exista en :values.',
'required_with' => 'El campo :attribute es requerido cuando :values está presente.',
'required_with_all' => 'El campo :attribute es requerido cuando :values está presente.',
'required_without' => 'El campo :attribute es requerido cuando :values no está presente.',
'required_without_all' => 'El campo :attribute es requerido cuando ninguno de :values están presentes.',
'same' => 'El :attribute y :other deben coincidir.',
'size' => [
'numeric' => 'El :attribute debe ser de :size.',
'file' => 'El :attribute debe ser de :size kilobytes.',
'string' => 'El :attribute debe ser de :size caracteres.',
'array' => 'El :attribute debe contener :size elementos.',
],
'string' => 'El :attribute debe ser una cadena.',
'timezone' => 'El :attribute debe ser una zona válida.',
'unique' => 'El :attribute ya ha sido tomado.',
'url' => 'El formato de :attribute no es válido.',
'path' => [
'valid' => 'El :attribute no es una ruta válida o legible.',
],
/*
|--------------------------------------------------------------------------
| 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' => [
],
/*
|--------------------------------------------------------------------------
| 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' => [],
];
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/resources/lang/es/auth.php | resources/lang/es/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' => 'Estas credenciales no coinciden con nuestros registros.',
'throttle' => 'Demasiados intentos de inicio de sesión. Por favor intente de nuevo en :seconds segundos.',
];
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/resources/views/sso-callback.blade.php | resources/views/sso-callback.blade.php | <!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SSO Callback | Koel</title>
<script>
window.opener.postMessage(@json($token), '*')
window.close()
</script>
</head>
</html>
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/resources/views/index.blade.php | resources/views/index.blade.php | @extends('base')
@section('title', koel_branding('name'))
@push('scripts')
<script>
window.MAILER_CONFIGURED = @json(mailer_configured());
window.SSO_PROVIDERS = @json(collect_sso_providers());
window.ACCEPTED_AUDIO_EXTENSIONS = @json(collect_accepted_audio_extensions());
@if (session()->has('demo_account'))
window.DEMO_ACCOUNT = @json(session('demo_account'));
@elseif (isset($token))
window.AUTH_TOKEN = @json($token);
@endif
</script>
@vite(['resources/assets/js/app.ts'])
@endpush
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/resources/views/remote.blade.php | resources/views/remote.blade.php | @extends('base')
@section('title', koel_branding('name') . ' - Remote Controller')
@push('scripts')
@vite(['resources/assets/js/remote/app.ts'])
@endpush
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/resources/views/base.blade.php | resources/views/base.blade.php | <!DOCTYPE html>
<html lang="en">
<head>
<title>@yield('title')</title>
<meta name="description" content="{{ config('app.tagline') }}">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="mobile-web-app-capable" content="yes">
<meta name="theme-color" content="#282828">
<meta name="msapplication-navbutton-color" content="#282828">
<link rel="manifest" href="{{ static_url('manifest.json') }}" />
<meta name="msapplication-config" content="{{ static_url('browserconfig.xml') }}" />
<link rel="icon" type="image/x-icon" href="{{ koel_branding('logo') ?? static_url('img/favicon.ico') }}" />
<link rel="icon" href="{{ koel_branding('logo') ?? static_url('img/icon.png') }}">
<link rel="apple-touch-icon" href="{{ koel_branding('logo') ?? static_url('img/icon.png') }}">
@unless(License::isPlus())
<script src="https://app.lemonsqueezy.com/js/lemon.js" defer></script>
@endunless
<script>
// Work around for "global is not defined" error with local-storage.js
window.global = window
</script>
</head>
<body class="text-k-fg-70">
<div id="app"></div>
<script>
window.BASE_URL = @json(base_url());
window.IS_DEMO = @json(config('koel.misc.demo'));
window.PUSHER_APP_KEY = @json(config('broadcasting.connections.pusher.key'));
window.PUSHER_APP_CLUSTER = @json(config('broadcasting.connections.pusher.options.cluster'));
window.BRANDING = @json(koel_branding());
</script>
@stack('scripts')
</body>
</html>
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/resources/views/errors/503.blade.php | resources/views/errors/503.blade.php | @extends('errors.template')
@section('title', 'Service Unavailable')
@section('details', 'Koel will be right back.')
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/resources/views/errors/template.blade.php | resources/views/errors/template.blade.php | <!DOCTYPE html>
<html>
<head>
<title>@yield('title')</title>
<style>
html, body {
height: 100%;
}
body {
margin: 0;
padding: 0;
width: 100%;
background: #181818;
display: table;
font-size: 24px;
font-family: system, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
color: #a0a0a0;
}
.container {
display: table-cell;
vertical-align: middle;
}
.content {
padding: 76px;
}
.title {
font-weight: 100;
font-size: 48px;
margin-bottom: 40px;
color: #fff;
}
</style>
</head>
<body>
<div class="container">
<div class="content">
<div class="title">@yield('title')</div>
<div class="details">@yield('details')</div>
</div>
</div>
</body>
</html>
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/resources/views/errors/404.blade.php | resources/views/errors/404.blade.php | @extends('errors.template')
@section('title', 'Not Found')
@section('details', $exception->getMessage())
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/resources/views/emails/users/invite.blade.php | resources/views/emails/users/invite.blade.php | <x-mail::message>
Hey hey,
{{ $invitee->invitedBy->name }} has invited you to join them on {{ config('app.name') }}.
Click the button below to accept the invitation.
<x-mail::button :url="$url">
Accept Invitation
</x-mail::button>
Enjoy!
</x-mail::message>
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/resources/views/lastfm/callback.blade.php | resources/views/lastfm/callback.blade.php | <!DOCTYPE html>
<html lang="en">
<head>
<title>Authentication successful!</title>
<meta charset="utf-8">
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
}
</style>
</head>
<body>
<h3>Perfecto!</h3>
<p>Koel has successfully connected to your Last.fm account and is now restarting for the exciting features.</p>
<p>This window will automatically close in 3 seconds.</p>
<script>
window.opener.onbeforeunload = function () {
}
window.opener.location.reload(false)
window.setTimeout(function () {
window.close()
}, 3000)
</script>
</body>
</html>
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/.php-cs-fixer.php | .php-cs-fixer.php | <?php
$header = <<<EOF
This file is part of Composer.
(c) Nils Adermann <naderman@naderman.de>
Jordi Boggiano <j.boggiano@seld.be>
For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
EOF;
$finder = PhpCsFixer\Finder::create()
->files()
->in(__DIR__.'/src')
->in(__DIR__.'/tests')
->name('*.php')
->notPath('Fixtures')
->notPath('Composer/Autoload/ClassLoader.php')
->notPath('Composer/InstalledVersions.php')
->notPath('Composer/Test/Autoload/MinimumVersionSupport')
;
$config = new PhpCsFixer\Config();
return $config
->setParallelConfig(PhpCsFixer\Runner\Parallel\ParallelConfigFactory::detect())
->setRules([
'@PSR2' => true,
'binary_operator_spaces' => true,
'blank_line_before_statement' => ['statements' => ['declare', 'return']],
'cast_spaces' => ['space' => 'single'],
'header_comment' => ['header' => $header],
'statement_indentation' => ['stick_comment_to_next_continuous_control_statement' => true],
'include' => true,
'class_attributes_separation' => ['elements' => ['method' => 'one', 'trait_import' => 'none']],
'no_blank_lines_after_class_opening' => true,
'no_blank_lines_after_phpdoc' => true,
'no_empty_statement' => true,
'no_extra_blank_lines' => true,
'no_leading_namespace_whitespace' => true,
'no_trailing_comma_in_singleline' => true,
'no_whitespace_in_blank_line' => true,
'object_operator_without_whitespace' => true,
//'phpdoc_align' => true,
'phpdoc_indent' => true,
'no_empty_comment' => true,
'no_empty_phpdoc' => true,
'phpdoc_no_access' => true,
'phpdoc_no_package' => true,
//'phpdoc_order' => true,
'phpdoc_scalar' => true,
'phpdoc_trim' => true,
'phpdoc_types' => true,
'psr_autoloading' => true,
'blank_lines_before_namespace' => true,
'standardize_not_equals' => true,
'ternary_operator_spaces' => true,
'trailing_comma_in_multiline' => ['elements' => ['arrays']],
'unary_operator_spaces' => true,
// imports
'no_unused_imports' => true,
'fully_qualified_strict_types' => true,
'single_line_after_imports' => true,
//'global_namespace_import' => ['import_classes' => true],
'no_leading_import_slash' => true,
'single_import_per_statement' => true,
// PHP 7.2 migration
'array_syntax' => true,
'list_syntax' => true,
'regular_callable_call' => true,
'static_lambda' => true,
'nullable_type_declaration_for_default_null_value' => true,
'explicit_indirect_variable' => true,
'visibility_required' => ['elements' => ['property', 'method', 'const']],
'non_printable_character' => true,
'combine_nested_dirname' => true,
'random_api_migration' => true,
'ternary_to_null_coalescing' => true,
'phpdoc_to_param_type' => false,
'declare_strict_types' => true,
'no_superfluous_phpdoc_tags' => [
'allow_mixed' => true,
],
// TODO php 7.4 migration (one day..)
// 'phpdoc_to_property_type' => true,
])
->setUsingCache(true)
->setRiskyAllowed(true)
->setFinder($finder)
;
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/bootstrap.php | src/bootstrap.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Composer\Autoload\ClassLoader;
function includeIfExists(string $file): ?ClassLoader
{
return file_exists($file) ? include $file : null;
}
if ((!$loader = includeIfExists(__DIR__.'/../vendor/autoload.php')) && (!$loader = includeIfExists(__DIR__.'/../../../autoload.php'))) {
echo 'You must set up the project dependencies using `composer install`'.PHP_EOL.
'See https://getcomposer.org/download/ for instructions on installing Composer'.PHP_EOL;
exit(1);
}
return $loader;
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/InstalledVersions.php | src/Composer/InstalledVersions.php | <?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer;
use Composer\Autoload\ClassLoader;
use Composer\Semver\VersionParser;
/**
* This class is copied in every Composer installed project and available to all
*
* See also https://getcomposer.org/doc/07-runtime.md#installed-versions
*
* To require its presence, you can require `composer-runtime-api ^2.0`
*
* @final
*/
class InstalledVersions
{
/**
* @var string|null if set (by reflection by Composer), this should be set to the path where this class is being copied to
* @internal
*/
private static $selfDir = null;
/**
* @var mixed[]|null
* @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}|array{}|null
*/
private static $installed;
/**
* @var bool
*/
private static $installedIsLocalDir;
/**
* @var bool|null
*/
private static $canGetVendors;
/**
* @var array[]
* @psalm-var array<string, array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
private static $installedByVendor = array();
/**
* Returns a list of all package names which are present, either by being installed, replaced or provided
*
* @return string[]
* @psalm-return list<string>
*/
public static function getInstalledPackages()
{
$packages = array();
foreach (self::getInstalled() as $installed) {
$packages[] = array_keys($installed['versions']);
}
if (1 === \count($packages)) {
return $packages[0];
}
return array_keys(array_flip(\call_user_func_array('array_merge', $packages)));
}
/**
* Returns a list of all package names with a specific type e.g. 'library'
*
* @param string $type
* @return string[]
* @psalm-return list<string>
*/
public static function getInstalledPackagesByType($type)
{
$packagesByType = array();
foreach (self::getInstalled() as $installed) {
foreach ($installed['versions'] as $name => $package) {
if (isset($package['type']) && $package['type'] === $type) {
$packagesByType[] = $name;
}
}
}
return $packagesByType;
}
/**
* Checks whether the given package is installed
*
* This also returns true if the package name is provided or replaced by another package
*
* @param string $packageName
* @param bool $includeDevRequirements
* @return bool
*/
public static function isInstalled($packageName, $includeDevRequirements = true)
{
foreach (self::getInstalled() as $installed) {
if (isset($installed['versions'][$packageName])) {
return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false;
}
}
return false;
}
/**
* Checks whether the given package satisfies a version constraint
*
* e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call:
*
* Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3')
*
* @param VersionParser $parser Install composer/semver to have access to this class and functionality
* @param string $packageName
* @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package
* @return bool
*/
public static function satisfies(VersionParser $parser, $packageName, $constraint)
{
$constraint = $parser->parseConstraints((string) $constraint);
$provided = $parser->parseConstraints(self::getVersionRanges($packageName));
return $provided->matches($constraint);
}
/**
* Returns a version constraint representing all the range(s) which are installed for a given package
*
* It is easier to use this via isInstalled() with the $constraint argument if you need to check
* whether a given version of a package is installed, and not just whether it exists
*
* @param string $packageName
* @return string Version constraint usable with composer/semver
*/
public static function getVersionRanges($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
$ranges = array();
if (isset($installed['versions'][$packageName]['pretty_version'])) {
$ranges[] = $installed['versions'][$packageName]['pretty_version'];
}
if (array_key_exists('aliases', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']);
}
if (array_key_exists('replaced', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']);
}
if (array_key_exists('provided', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']);
}
return implode(' || ', $ranges);
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
*/
public static function getVersion($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['version'])) {
return null;
}
return $installed['versions'][$packageName]['version'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
*/
public static function getPrettyVersion($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['pretty_version'])) {
return null;
}
return $installed['versions'][$packageName]['pretty_version'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference
*/
public static function getReference($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['reference'])) {
return null;
}
return $installed['versions'][$packageName]['reference'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path.
*/
public static function getInstallPath($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null;
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @return array
* @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}
*/
public static function getRootPackage()
{
$installed = self::getInstalled();
return $installed[0]['root'];
}
/**
* Returns the raw installed.php data for custom implementations
*
* @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect.
* @return array[]
* @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}
*/
public static function getRawData()
{
@trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED);
if (null === self::$installed) {
// only require the installed.php file if this file is loaded from its dumped location,
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
if (substr(__DIR__, -8, 1) !== 'C') {
self::$installed = include __DIR__ . '/installed.php';
} else {
self::$installed = array();
}
}
return self::$installed;
}
/**
* Returns the raw data of all installed.php which are currently loaded for custom implementations
*
* @return array[]
* @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
public static function getAllRawData()
{
return self::getInstalled();
}
/**
* Lets you reload the static array from another file
*
* This is only useful for complex integrations in which a project needs to use
* this class but then also needs to execute another project's autoloader in process,
* and wants to ensure both projects have access to their version of installed.php.
*
* A typical case would be PHPUnit, where it would need to make sure it reads all
* the data it needs from this class, then call reload() with
* `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure
* the project in which it runs can then also use this class safely, without
* interference between PHPUnit's dependencies and the project's dependencies.
*
* @param array[] $data A vendor/composer/installed.php data set
* @return void
*
* @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $data
*/
public static function reload($data)
{
self::$installed = $data;
self::$installedByVendor = array();
// when using reload, we disable the duplicate protection to ensure that self::$installed data is
// always returned, but we cannot know whether it comes from the installed.php in __DIR__ or not,
// so we have to assume it does not, and that may result in duplicate data being returned when listing
// all installed packages for example
self::$installedIsLocalDir = false;
}
/**
* @return string
*/
private static function getSelfDir()
{
if (self::$selfDir === null) {
self::$selfDir = strtr(__DIR__, '\\', '/');
}
return self::$selfDir;
}
/**
* @return array[]
* @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
private static function getInstalled()
{
if (null === self::$canGetVendors) {
self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders');
}
$installed = array();
$copiedLocalDir = false;
if (self::$canGetVendors) {
$selfDir = self::getSelfDir();
foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) {
$vendorDir = strtr($vendorDir, '\\', '/');
if (isset(self::$installedByVendor[$vendorDir])) {
$installed[] = self::$installedByVendor[$vendorDir];
} elseif (is_file($vendorDir.'/composer/installed.php')) {
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
$required = require $vendorDir.'/composer/installed.php';
self::$installedByVendor[$vendorDir] = $required;
$installed[] = $required;
if (self::$installed === null && $vendorDir.'/composer' === $selfDir) {
self::$installed = $required;
self::$installedIsLocalDir = true;
}
}
if (self::$installedIsLocalDir && $vendorDir.'/composer' === $selfDir) {
$copiedLocalDir = true;
}
}
}
if (null === self::$installed) {
// only require the installed.php file if this file is loaded from its dumped location,
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
if (substr(__DIR__, -8, 1) !== 'C') {
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
$required = require __DIR__ . '/installed.php';
self::$installed = $required;
} else {
self::$installed = array();
}
}
if (self::$installed !== array() && !$copiedLocalDir) {
$installed[] = self::$installed;
}
return $installed;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Composer.php | src/Composer/Composer.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer;
use Composer\Package\Locker;
use Composer\Pcre\Preg;
use Composer\Plugin\PluginManager;
use Composer\Downloader\DownloadManager;
use Composer\Autoload\AutoloadGenerator;
use Composer\Package\Archiver\ArchiveManager;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author Konstantin Kudryashiv <ever.zet@gmail.com>
* @author Nils Adermann <naderman@naderman.de>
*/
class Composer extends PartialComposer
{
/*
* Examples of the following constants in the various configurations they can be in
*
* You are probably better off using Composer::getVersion() though as that will always return something usable
*
* releases (phar):
* const VERSION = '1.8.2';
* const BRANCH_ALIAS_VERSION = '';
* const RELEASE_DATE = '2019-01-29 15:00:53';
* const SOURCE_VERSION = '';
*
* snapshot builds (phar):
* const VERSION = 'd3873a05650e168251067d9648845c220c50e2d7';
* const BRANCH_ALIAS_VERSION = '1.9-dev';
* const RELEASE_DATE = '2019-02-20 07:43:56';
* const SOURCE_VERSION = '';
*
* source (git clone):
* const VERSION = '@package_version@';
* const BRANCH_ALIAS_VERSION = '@package_branch_alias_version@';
* const RELEASE_DATE = '@release_date@';
* const SOURCE_VERSION = '1.8-dev+source';
*
* @see getVersion()
*/
public const VERSION = '@package_version@';
public const BRANCH_ALIAS_VERSION = '@package_branch_alias_version@';
public const RELEASE_DATE = '@release_date@';
public const SOURCE_VERSION = '2.9.999-dev+source';
/**
* Version number of the internal composer-runtime-api package
*
* This is used to version features available to projects at runtime
* like the platform-check file, the Composer\InstalledVersions class
* and possibly others in the future.
*
* @var string
*/
public const RUNTIME_API_VERSION = '2.2.2';
public static function getVersion(): string
{
// no replacement done, this must be a source checkout
if (self::VERSION === '@package_version'.'@') {
return self::SOURCE_VERSION;
}
// we have a branch alias and version is a commit id, this must be a snapshot build
if (self::BRANCH_ALIAS_VERSION !== '' && Preg::isMatch('{^[a-f0-9]{40}$}', self::VERSION)) {
return self::BRANCH_ALIAS_VERSION.'+'.self::VERSION;
}
return self::VERSION;
}
/**
* @var Locker
*/
private $locker;
/**
* @var DownloadManager
*/
private $downloadManager;
/**
* @var PluginManager
*/
private $pluginManager;
/**
* @var AutoloadGenerator
*/
private $autoloadGenerator;
/**
* @var ArchiveManager
*/
private $archiveManager;
public function setLocker(Locker $locker): void
{
$this->locker = $locker;
}
public function getLocker(): Locker
{
return $this->locker;
}
public function setDownloadManager(DownloadManager $manager): void
{
$this->downloadManager = $manager;
}
public function getDownloadManager(): DownloadManager
{
return $this->downloadManager;
}
public function setArchiveManager(ArchiveManager $manager): void
{
$this->archiveManager = $manager;
}
public function getArchiveManager(): ArchiveManager
{
return $this->archiveManager;
}
public function setPluginManager(PluginManager $manager): void
{
$this->pluginManager = $manager;
}
public function getPluginManager(): PluginManager
{
return $this->pluginManager;
}
public function setAutoloadGenerator(AutoloadGenerator $autoloadGenerator): void
{
$this->autoloadGenerator = $autoloadGenerator;
}
public function getAutoloadGenerator(): AutoloadGenerator
{
return $this->autoloadGenerator;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Compiler.php | src/Composer/Compiler.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer;
use Composer\Json\JsonFile;
use Composer\CaBundle\CaBundle;
use Composer\Pcre\Preg;
use Composer\Util\Git;
use Composer\Util\ProcessExecutor;
use Symfony\Component\Finder\Finder;
use Seld\PharUtils\Timestamps;
use Seld\PharUtils\Linter;
/**
* The Compiler class compiles composer into a phar
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class Compiler
{
/** @var string */
private $version;
/** @var string */
private $branchAliasVersion = '';
/** @var \DateTime */
private $versionDate;
/**
* Compiles composer into a single phar file
*
* @param string $pharFile The full path to the file to create
*
* @throws \RuntimeException
*/
public function compile(string $pharFile = 'composer.phar'): void
{
if (file_exists($pharFile)) {
unlink($pharFile);
}
$process = new ProcessExecutor();
$command = Git::buildRevListCommand($process, ['-n1', '--format=%H', 'HEAD']);
if (0 !== $process->execute($command, $output, dirname(__DIR__, 2))) {
throw new \RuntimeException('Can\'t run git rev-list. You must ensure to run compile from composer git repository clone and that git binary is available.');
}
$this->version = trim(Git::parseRevListOutput($output, $process));
$command = Git::buildRevListCommand($process, ['-n1', '--format=%ci', 'HEAD']);
if (0 !== $process->execute($command, $output, dirname(__DIR__, 2))) {
throw new \RuntimeException('Can\'t run git rev-list. You must ensure to run compile from composer git repository clone and that git binary is available.');
}
$this->versionDate = new \DateTime(trim(Git::parseRevListOutput($output, $process)));
$this->versionDate->setTimezone(new \DateTimeZone('UTC'));
if (0 === $process->execute(['git', 'describe', '--tags', '--exact-match', 'HEAD'], $output, dirname(__DIR__, 2))) {
$this->version = trim($output);
} else {
// get branch-alias defined in composer.json for dev-main (if any)
$localConfig = __DIR__.'/../../composer.json';
$file = new JsonFile($localConfig);
$localConfig = $file->read();
if (isset($localConfig['extra']['branch-alias']['dev-main'])) {
$this->branchAliasVersion = $localConfig['extra']['branch-alias']['dev-main'];
}
}
if ('' === $this->version) {
throw new \UnexpectedValueException('Version detection failed');
}
$phar = new \Phar($pharFile, 0, 'composer.phar');
$phar->setSignatureAlgorithm(\Phar::SHA512);
$phar->startBuffering();
$finderSort = static function ($a, $b): int {
return strcmp(strtr($a->getRealPath(), '\\', '/'), strtr($b->getRealPath(), '\\', '/'));
};
// Add Composer sources
$finder = new Finder();
$finder->files()
->ignoreVCS(true)
->name('*.php')
->notName('Compiler.php')
->notName('ClassLoader.php')
->notName('InstalledVersions.php')
->in(__DIR__.'/..')
->sort($finderSort)
;
foreach ($finder as $file) {
$this->addFile($phar, $file);
}
// Add runtime utilities separately to make sure they retains the docblocks as these will get copied into projects
$this->addFile($phar, new \SplFileInfo(__DIR__ . '/Autoload/ClassLoader.php'), false);
$this->addFile($phar, new \SplFileInfo(__DIR__ . '/InstalledVersions.php'), false);
// Add Composer resources
$finder = new Finder();
$finder->files()
->in(__DIR__.'/../../res')
->sort($finderSort)
;
foreach ($finder as $file) {
$this->addFile($phar, $file, false);
}
// Add vendor files
$finder = new Finder();
$finder->files()
->ignoreVCS(true)
->notPath('/\/(composer\.(?:json|lock)|[A-Z]+\.md(?:own)?|\.gitignore|appveyor.yml|phpunit\.xml\.dist|phpstan\.neon\.dist|phpstan-config\.neon|phpstan-baseline\.neon|UPGRADE.*\.(?:md|txt))$/')
->notPath('/bin\/(jsonlint|validate-json|simple-phpunit|phpstan|phpstan\.phar)(\.bat)?$/')
->notPath('justinrainbow/json-schema/demo/')
->notPath('justinrainbow/json-schema/dist/')
->notPath('composer/pcre/extension.neon')
->notPath('composer/LICENSE')
->exclude('Tests')
->exclude('tests')
->exclude('docs')
->in(__DIR__.'/../../vendor/')
->sort($finderSort)
;
$extraFiles = [];
foreach ([
__DIR__ . '/../../vendor/composer/installed.json',
__DIR__ . '/../../vendor/composer/spdx-licenses/res/spdx-exceptions.json',
__DIR__ . '/../../vendor/composer/spdx-licenses/res/spdx-licenses.json',
CaBundle::getBundledCaBundlePath(),
__DIR__ . '/../../vendor/symfony/console/Resources/bin/hiddeninput.exe',
__DIR__ . '/../../vendor/symfony/console/Resources/completion.bash',
] as $file) {
$extraFiles[$file] = realpath($file);
if (!file_exists($file)) {
throw new \RuntimeException('Extra file listed is missing from the filesystem: '.$file);
}
}
$unexpectedFiles = [];
foreach ($finder as $file) {
if (false !== ($index = array_search($file->getRealPath(), $extraFiles, true))) {
unset($extraFiles[$index]);
} elseif (!Preg::isMatch('{(^LICENSE(?:\.txt)?$|\.php$)}', $file->getFilename())) {
$unexpectedFiles[] = (string) $file;
}
if (Preg::isMatch('{\.php[\d.]*$}', $file->getFilename())) {
$this->addFile($phar, $file);
} else {
$this->addFile($phar, $file, false);
}
}
if (count($extraFiles) > 0) {
throw new \RuntimeException('These files were expected but not added to the phar, they might be excluded or gone from the source package:'.PHP_EOL.var_export($extraFiles, true));
}
if (count($unexpectedFiles) > 0) {
throw new \RuntimeException('These files were unexpectedly added to the phar, make sure they are excluded or listed in $extraFiles:'.PHP_EOL.var_export($unexpectedFiles, true));
}
// Add bin/composer
$this->addComposerBin($phar);
// Stubs
$phar->setStub($this->getStub());
$phar->stopBuffering();
// disabled for interoperability with systems without gzip ext
// $phar->compressFiles(\Phar::GZ);
$this->addFile($phar, new \SplFileInfo(__DIR__.'/../../LICENSE'), false);
unset($phar);
// re-sign the phar with reproducible timestamp / signature
$util = new Timestamps($pharFile);
$util->updateTimestamps($this->versionDate);
$util->save($pharFile, \Phar::SHA512);
Linter::lint($pharFile, [
'vendor/symfony/console/Attribute/AsCommand.php',
'vendor/symfony/polyfill-intl-grapheme/bootstrap80.php',
'vendor/symfony/polyfill-intl-normalizer/bootstrap80.php',
'vendor/symfony/polyfill-mbstring/bootstrap80.php',
'vendor/symfony/polyfill-php73/Resources/stubs/JsonException.php',
'vendor/symfony/service-contracts/Attribute/SubscribedService.php',
'vendor/symfony/polyfill-php84/Resources/stubs/Deprecated.php',
'vendor/symfony/polyfill-php84/bootstrap82.php',
]);
}
private function getRelativeFilePath(\SplFileInfo $file): string
{
$realPath = $file->getRealPath();
$pathPrefix = dirname(__DIR__, 2).DIRECTORY_SEPARATOR;
$pos = strpos($realPath, $pathPrefix);
$relativePath = ($pos !== false) ? substr_replace($realPath, '', $pos, strlen($pathPrefix)) : $realPath;
return strtr($relativePath, '\\', '/');
}
private function addFile(\Phar $phar, \SplFileInfo $file, bool $strip = true): void
{
$path = $this->getRelativeFilePath($file);
$content = file_get_contents((string) $file);
if ($strip) {
$content = $this->stripWhitespace($content);
} elseif ('LICENSE' === $file->getFilename()) {
$content = "\n".$content."\n";
}
if ($path === 'src/Composer/Composer.php') {
$content = strtr(
$content,
[
'@package_version@' => $this->version,
'@package_branch_alias_version@' => $this->branchAliasVersion,
'@release_date@' => $this->versionDate->format('Y-m-d H:i:s'),
]
);
$content = Preg::replace('{SOURCE_VERSION = \'[^\']+\';}', 'SOURCE_VERSION = \'\';', $content);
}
$phar->addFromString($path, $content);
}
private function addComposerBin(\Phar $phar): void
{
$content = file_get_contents(__DIR__.'/../../bin/composer');
$content = Preg::replace('{^#!/usr/bin/env php\s*}', '', $content);
$phar->addFromString('bin/composer', $content);
}
/**
* Removes whitespace from a PHP source string while preserving line numbers.
*
* @param string $source A PHP string
* @return string The PHP string with the whitespace removed
*/
private function stripWhitespace(string $source): string
{
if (!function_exists('token_get_all')) {
return $source;
}
$output = '';
foreach (token_get_all($source) as $token) {
if (is_string($token)) {
$output .= $token;
} elseif (in_array($token[0], [T_COMMENT, T_DOC_COMMENT])) {
$output .= str_repeat("\n", substr_count($token[1], "\n"));
} elseif (T_WHITESPACE === $token[0]) {
// reduce wide spaces
$whitespace = Preg::replace('{[ \t]+}', ' ', $token[1]);
// normalize newlines to \n
$whitespace = Preg::replace('{(?:\r\n|\r|\n)}', "\n", $whitespace);
// trim leading spaces
$whitespace = Preg::replace('{\n +}', "\n", $whitespace);
$output .= $whitespace;
} else {
$output .= $token[1];
}
}
return $output;
}
private function getStub(): string
{
$stub = <<<'EOF'
#!/usr/bin/env php
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view
* the license that is located at the bottom of this file.
*/
// Avoid APC causing random fatal errors per https://github.com/composer/composer/issues/264
if (extension_loaded('apc') && filter_var(ini_get('apc.enable_cli'), FILTER_VALIDATE_BOOLEAN) && filter_var(ini_get('apc.cache_by_default'), FILTER_VALIDATE_BOOLEAN)) {
if (version_compare(phpversion('apc'), '3.0.12', '>=')) {
ini_set('apc.cache_by_default', 0);
} else {
fwrite(STDERR, 'Warning: APC <= 3.0.12 may cause fatal errors when running composer commands.'.PHP_EOL);
fwrite(STDERR, 'Update APC, or set apc.enable_cli or apc.cache_by_default to 0 in your php.ini.'.PHP_EOL);
}
}
if (!class_exists('Phar')) {
echo 'PHP\'s phar extension is missing. Composer requires it to run. Enable the extension or recompile php without --disable-phar then try again.' . PHP_EOL;
exit(1);
}
Phar::mapPhar('composer.phar');
EOF;
// add warning once the phar is older than 60 days
if (Preg::isMatch('{^[a-f0-9]+$}', $this->version)) {
$warningTime = ((int) $this->versionDate->format('U')) + 60 * 86400;
$stub .= "define('COMPOSER_DEV_WARNING_TIME', $warningTime);\n";
}
return $stub . <<<'EOF'
require 'phar://composer.phar/bin/composer';
__HALT_COMPILER();
EOF;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Config.php | src/Composer/Config.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer;
use Composer\Advisory\Auditor;
use Composer\Config\ConfigSourceInterface;
use Composer\Downloader\TransportException;
use Composer\IO\IOInterface;
use Composer\Pcre\Preg;
use Composer\Util\Platform;
use Composer\Util\ProcessExecutor;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class Config
{
public const SOURCE_DEFAULT = 'default';
public const SOURCE_COMMAND = 'command';
public const SOURCE_UNKNOWN = 'unknown';
public const RELATIVE_PATHS = 1;
/** @var array<string, mixed> */
public static $defaultConfig = [
'process-timeout' => 300,
'use-include-path' => false,
'allow-plugins' => [],
'use-parent-dir' => 'prompt',
'preferred-install' => 'dist',
'audit' => ['ignore' => [], 'abandoned' => Auditor::ABANDONED_FAIL],
'notify-on-install' => true,
'github-protocols' => ['https', 'ssh', 'git'],
'gitlab-protocol' => null,
'vendor-dir' => 'vendor',
'bin-dir' => '{$vendor-dir}/bin',
'cache-dir' => '{$home}/cache',
'data-dir' => '{$home}',
'cache-files-dir' => '{$cache-dir}/files',
'cache-repo-dir' => '{$cache-dir}/repo',
'cache-vcs-dir' => '{$cache-dir}/vcs',
'cache-ttl' => 15552000, // 6 months
'cache-files-ttl' => null, // fallback to cache-ttl
'cache-files-maxsize' => '300MiB',
'cache-read-only' => false,
'bin-compat' => 'auto',
'discard-changes' => false,
'autoloader-suffix' => null,
'sort-packages' => false,
'optimize-autoloader' => false,
'classmap-authoritative' => false,
'apcu-autoloader' => false,
'prepend-autoloader' => true,
'update-with-minimal-changes' => false,
'github-domains' => ['github.com'],
'bitbucket-expose-hostname' => true,
'disable-tls' => false,
'secure-http' => true,
'secure-svn-domains' => [],
'cafile' => null,
'capath' => null,
'github-expose-hostname' => true,
'gitlab-domains' => ['gitlab.com'],
'store-auths' => 'prompt',
'platform' => [],
'archive-format' => 'tar',
'archive-dir' => '.',
'htaccess-protect' => true,
'use-github-api' => true,
'lock' => true,
'platform-check' => 'php-only',
'bitbucket-oauth' => [],
'github-oauth' => [],
'gitlab-oauth' => [],
'gitlab-token' => [],
'http-basic' => [],
'bearer' => [],
'custom-headers' => [],
'bump-after-update' => false,
'allow-missing-requirements' => false,
'client-certificate' => [],
'forgejo-domains' => ['codeberg.org'],
'forgejo-token' => [],
];
/** @var array<string, mixed> */
public static $defaultRepositories = [
'packagist.org' => [
'type' => 'composer',
'url' => 'https://repo.packagist.org',
],
];
/** @var array<string, mixed> */
private $config;
/** @var ?non-empty-string */
private $baseDir;
/** @var array<int|string, mixed> */
private $repositories;
/** @var ConfigSourceInterface */
private $configSource;
/** @var ConfigSourceInterface */
private $authConfigSource;
/** @var ConfigSourceInterface|null */
private $localAuthConfigSource = null;
/** @var bool */
private $useEnvironment;
/** @var array<string, true> */
private $warnedHosts = [];
/** @var array<string, true> */
private $sslVerifyWarnedHosts = [];
/** @var array<string, string> */
private $sourceOfConfigValue = [];
/**
* @param bool $useEnvironment Use COMPOSER_ environment variables to replace config settings
* @param ?string $baseDir Optional base directory of the config
*/
public function __construct(bool $useEnvironment = true, ?string $baseDir = null)
{
// load defaults
$this->config = static::$defaultConfig;
$this->repositories = static::$defaultRepositories;
$this->useEnvironment = $useEnvironment;
$this->baseDir = is_string($baseDir) && '' !== $baseDir ? $baseDir : null;
foreach ($this->config as $configKey => $configValue) {
$this->setSourceOfConfigValue($configValue, $configKey, self::SOURCE_DEFAULT);
}
foreach ($this->repositories as $configKey => $configValue) {
$this->setSourceOfConfigValue($configValue, 'repositories.' . $configKey, self::SOURCE_DEFAULT);
}
}
/**
* Changing this can break path resolution for relative config paths so do not call this without knowing what you are doing
*
* The $baseDir should be an absolute path and without trailing slash
*
* @param non-empty-string|null $baseDir
*/
public function setBaseDir(?string $baseDir): void
{
$this->baseDir = $baseDir;
}
public function setConfigSource(ConfigSourceInterface $source): void
{
$this->configSource = $source;
}
public function getConfigSource(): ConfigSourceInterface
{
return $this->configSource;
}
public function setAuthConfigSource(ConfigSourceInterface $source): void
{
$this->authConfigSource = $source;
}
public function getAuthConfigSource(): ConfigSourceInterface
{
return $this->authConfigSource;
}
public function setLocalAuthConfigSource(ConfigSourceInterface $source): void
{
$this->localAuthConfigSource = $source;
}
public function getLocalAuthConfigSource(): ?ConfigSourceInterface
{
return $this->localAuthConfigSource;
}
/**
* Merges new config values with the existing ones (overriding)
*
* @param array{config?: array<string, mixed>, repositories?: array<mixed>} $config
*/
public function merge(array $config, string $source = self::SOURCE_UNKNOWN): void
{
// override defaults with given config
if (!empty($config['config']) && is_array($config['config'])) {
foreach ($config['config'] as $key => $val) {
if (in_array($key, ['bitbucket-oauth', 'github-oauth', 'gitlab-oauth', 'gitlab-token', 'http-basic', 'bearer', 'client-certificate', 'forgejo-token'], true) && isset($this->config[$key])) {
$this->config[$key] = array_merge($this->config[$key], $val);
$this->setSourceOfConfigValue($val, $key, $source);
} elseif (in_array($key, ['allow-plugins'], true) && isset($this->config[$key]) && is_array($this->config[$key]) && is_array($val)) {
// merging $val first to get the local config on top of the global one, then appending the global config,
// then merging local one again to make sure the values from local win over global ones for keys present in both
$this->config[$key] = array_merge($val, $this->config[$key], $val);
$this->setSourceOfConfigValue($val, $key, $source);
} elseif (in_array($key, ['gitlab-domains', 'github-domains'], true) && isset($this->config[$key])) {
$this->config[$key] = array_unique(array_merge($this->config[$key], $val));
$this->setSourceOfConfigValue($val, $key, $source);
} elseif ('preferred-install' === $key && isset($this->config[$key])) {
if (is_array($val) || is_array($this->config[$key])) {
if (is_string($val)) {
$val = ['*' => $val];
}
if (is_string($this->config[$key])) {
$this->config[$key] = ['*' => $this->config[$key]];
$this->sourceOfConfigValue[$key . '*'] = $source;
}
$this->config[$key] = array_merge($this->config[$key], $val);
$this->setSourceOfConfigValue($val, $key, $source);
// the full match pattern needs to be last
if (isset($this->config[$key]['*'])) {
$wildcard = $this->config[$key]['*'];
unset($this->config[$key]['*']);
$this->config[$key]['*'] = $wildcard;
}
} else {
$this->config[$key] = $val;
$this->setSourceOfConfigValue($val, $key, $source);
}
} elseif ('audit' === $key) {
$currentIgnores = $this->config['audit']['ignore'];
$this->config[$key] = array_merge($this->config['audit'], $val);
$this->setSourceOfConfigValue($val, $key, $source);
$this->config['audit']['ignore'] = array_merge($currentIgnores, $val['ignore'] ?? []);
} else {
$this->config[$key] = $val;
$this->setSourceOfConfigValue($val, $key, $source);
}
}
}
if (!empty($config['repositories']) && is_array($config['repositories'])) {
$this->repositories = array_reverse($this->repositories, true);
$newRepos = array_reverse($config['repositories'], true);
foreach ($newRepos as $name => $repository) {
// disable a repository by name
// this is a code path, that will be used less as the next check will be preferred
if (false === $repository) {
$this->disableRepoByName((string) $name);
continue;
}
// disable a repository with an anonymous {"name": false} repo
if (is_array($repository) && 1 === count($repository) && false === current($repository)) {
$this->disableRepoByName((string) key($repository));
continue;
}
// auto-deactivate the default packagist.org repo if it gets redefined
if (isset($repository['type'], $repository['url']) && $repository['type'] === 'composer' && Preg::isMatch('{^https?://(?:[a-z0-9-.]+\.)?packagist.org(/|$)}', $repository['url'])) {
$this->disableRepoByName('packagist.org');
}
// store repo
if (is_int($name)) {
if (!isset($this->repositories[$name])) {
$this->repositories[$name] = $repository;
} else {
$this->repositories[] = $repository;
}
$this->setSourceOfConfigValue($repository, 'repositories.' . array_search($repository, $this->repositories, true), $source);
} else {
if ($name === 'packagist') { // BC support for default "packagist" named repo
$this->repositories[$name . '.org'] = $repository;
$this->setSourceOfConfigValue($repository, 'repositories.' . $name . '.org', $source);
} else {
$this->repositories[$name] = $repository;
$this->setSourceOfConfigValue($repository, 'repositories.' . $name, $source);
}
}
}
$this->repositories = array_reverse($this->repositories, true);
}
}
/**
* @return array<int|string, mixed>
*/
public function getRepositories(): array
{
return $this->repositories;
}
/**
* Returns a setting
*
* @param int $flags Options (see class constants)
* @throws \RuntimeException
*
* @return mixed
*/
public function get(string $key, int $flags = 0)
{
switch ($key) {
// strings/paths with env var and {$refs} support
case 'vendor-dir':
case 'bin-dir':
case 'process-timeout':
case 'data-dir':
case 'cache-dir':
case 'cache-files-dir':
case 'cache-repo-dir':
case 'cache-vcs-dir':
case 'cafile':
case 'capath':
// convert foo-bar to COMPOSER_FOO_BAR and check if it exists since it overrides the local config
$env = 'COMPOSER_' . strtoupper(strtr($key, '-', '_'));
$val = $this->getComposerEnv($env);
if ($val !== false) {
$this->setSourceOfConfigValue($val, $key, $env);
}
if ($key === 'process-timeout') {
return max(0, false !== $val ? (int) $val : $this->config[$key]);
}
$val = rtrim((string) $this->process(false !== $val ? $val : $this->config[$key], $flags), '/\\');
$val = Platform::expandPath($val);
if (substr($key, -4) !== '-dir') {
return $val;
}
return (($flags & self::RELATIVE_PATHS) === self::RELATIVE_PATHS) ? $val : $this->realpath($val);
// booleans with env var support
case 'cache-read-only':
case 'htaccess-protect':
// convert foo-bar to COMPOSER_FOO_BAR and check if it exists since it overrides the local config
$env = 'COMPOSER_' . strtoupper(strtr($key, '-', '_'));
$val = $this->getComposerEnv($env);
if (false === $val) {
$val = $this->config[$key];
} else {
$this->setSourceOfConfigValue($val, $key, $env);
}
return $val !== 'false' && (bool) $val;
// booleans without env var support
case 'disable-tls':
case 'secure-http':
case 'use-github-api':
case 'lock':
// special case for secure-http
if ($key === 'secure-http' && $this->get('disable-tls') === true) {
return false;
}
return $this->config[$key] !== 'false' && (bool) $this->config[$key];
// ints without env var support
case 'cache-ttl':
return max(0, (int) $this->config[$key]);
// numbers with kb/mb/gb support, without env var support
case 'cache-files-maxsize':
if (!Preg::isMatch('/^\s*([0-9.]+)\s*(?:([kmg])(?:i?b)?)?\s*$/i', (string) $this->config[$key], $matches)) {
throw new \RuntimeException(
"Could not parse the value of '$key': {$this->config[$key]}"
);
}
$size = (float) $matches[1];
if (isset($matches[2])) {
switch (strtolower($matches[2])) {
case 'g':
$size *= 1024;
// intentional fallthrough
// no break
case 'm':
$size *= 1024;
// intentional fallthrough
// no break
case 'k':
$size *= 1024;
break;
}
}
return max(0, (int) $size);
// special cases below
case 'cache-files-ttl':
if (isset($this->config[$key])) {
return max(0, (int) $this->config[$key]);
}
return $this->get('cache-ttl');
case 'home':
return rtrim($this->process(Platform::expandPath($this->config[$key]), $flags), '/\\');
case 'bin-compat':
$value = $this->getComposerEnv('COMPOSER_BIN_COMPAT') ?: $this->config[$key];
if (!in_array($value, ['auto', 'full', 'proxy', 'symlink'])) {
throw new \RuntimeException(
"Invalid value for 'bin-compat': {$value}. Expected auto, full or proxy"
);
}
if ($value === 'symlink') {
trigger_error('config.bin-compat "symlink" is deprecated since Composer 2.2, use auto, full (for Windows compatibility) or proxy instead.', E_USER_DEPRECATED);
}
return $value;
case 'discard-changes':
$env = $this->getComposerEnv('COMPOSER_DISCARD_CHANGES');
if ($env !== false) {
if (!in_array($env, ['stash', 'true', 'false', '1', '0'], true)) {
throw new \RuntimeException(
"Invalid value for COMPOSER_DISCARD_CHANGES: {$env}. Expected 1, 0, true, false or stash"
);
}
if ('stash' === $env) {
return 'stash';
}
// convert string value to bool
return $env !== 'false' && (bool) $env;
}
if (!in_array($this->config[$key], [true, false, 'stash'], true)) {
throw new \RuntimeException(
"Invalid value for 'discard-changes': {$this->config[$key]}. Expected true, false or stash"
);
}
return $this->config[$key];
case 'github-protocols':
$protos = $this->config['github-protocols'];
if ($this->config['secure-http'] && false !== ($index = array_search('git', $protos))) {
unset($protos[$index]);
}
if (reset($protos) === 'http') {
throw new \RuntimeException('The http protocol for github is not available anymore, update your config\'s github-protocols to use "https", "git" or "ssh"');
}
return $protos;
case 'autoloader-suffix':
if ($this->config[$key] === '') { // we need to guarantee null or non-empty-string
return null;
}
return $this->process($this->config[$key], $flags);
case 'audit':
$result = $this->config[$key];
$abandonedEnv = $this->getComposerEnv('COMPOSER_AUDIT_ABANDONED');
if (false !== $abandonedEnv) {
if (!in_array($abandonedEnv, $validChoices = Auditor::ABANDONEDS, true)) {
throw new \RuntimeException(
"Invalid value for COMPOSER_AUDIT_ABANDONED: {$abandonedEnv}. Expected one of ".implode(', ', Auditor::ABANDONEDS)."."
);
}
$result['abandoned'] = $abandonedEnv;
}
$blockAbandonedEnv = $this->getComposerEnv('COMPOSER_SECURITY_BLOCKING_ABANDONED');
if (false !== $blockAbandonedEnv) {
if (!in_array($blockAbandonedEnv, ['0', '1'], true)) {
throw new \RuntimeException(
"Invalid value for COMPOSER_SECURITY_BLOCKING_ABANDONED: {$blockAbandonedEnv}. Expected 0 or 1."
);
}
$result['block-abandoned'] = (bool) (int) $blockAbandonedEnv;
}
return $result;
default:
if (!isset($this->config[$key])) {
return null;
}
return $this->process($this->config[$key], $flags);
}
}
/**
* @return array<string, mixed[]>
*/
public function all(int $flags = 0): array
{
$all = [
'repositories' => $this->getRepositories(),
];
foreach (array_keys($this->config) as $key) {
$all['config'][$key] = $this->get($key, $flags);
}
return $all;
}
public function getSourceOfValue(string $key): string
{
$this->get($key);
return $this->sourceOfConfigValue[$key] ?? self::SOURCE_UNKNOWN;
}
/**
* @param mixed $configValue
*/
private function setSourceOfConfigValue($configValue, string $path, string $source): void
{
$this->sourceOfConfigValue[$path] = $source;
if (is_array($configValue)) {
foreach ($configValue as $key => $value) {
$this->setSourceOfConfigValue($value, $path . '.' . $key, $source);
}
}
}
/**
* @return array<string, mixed[]>
*/
public function raw(): array
{
return [
'repositories' => $this->getRepositories(),
'config' => $this->config,
];
}
/**
* Checks whether a setting exists
*/
public function has(string $key): bool
{
return array_key_exists($key, $this->config);
}
/**
* Replaces {$refs} inside a config string
*
* @param string|mixed $value a config string that can contain {$refs-to-other-config}
* @param int $flags Options (see class constants)
*
* @return string|mixed
*/
private function process($value, int $flags)
{
if (!is_string($value)) {
return $value;
}
return Preg::replaceCallback('#\{\$(.+)\}#', function ($match) use ($flags) {
return $this->get($match[1], $flags);
}, $value);
}
/**
* Turns relative paths in absolute paths without realpath()
*
* Since the dirs might not exist yet we can not call realpath or it will fail.
*/
private function realpath(string $path): string
{
if (Preg::isMatch('{^(?:/|[a-z]:|[a-z0-9.]+://|\\\\\\\\)}i', $path)) {
return $path;
}
return $this->baseDir !== null ? $this->baseDir . '/' . $path : $path;
}
/**
* Reads the value of a Composer environment variable
*
* This should be used to read COMPOSER_ environment variables
* that overload config values.
*
* @param non-empty-string $var
*
* @return string|false
*/
private function getComposerEnv(string $var)
{
if ($this->useEnvironment) {
return Platform::getEnv($var);
}
return false;
}
private function disableRepoByName(string $name): void
{
if (isset($this->repositories[$name])) {
unset($this->repositories[$name]);
} elseif ($name === 'packagist') { // BC support for default "packagist" named repo
unset($this->repositories['packagist.org']);
}
}
/**
* Validates that the passed URL is allowed to be used by current config, or throws an exception.
*
* @param mixed[] $repoOptions
*/
public function prohibitUrlByConfig(string $url, ?IOInterface $io = null, array $repoOptions = []): void
{
// Return right away if the URL is malformed or custom (see issue #5173), but only for non-HTTP(S) URLs
if (false === filter_var($url, FILTER_VALIDATE_URL) && !Preg::isMatch('{^https?://}', $url)) {
return;
}
// Extract scheme and throw exception on known insecure protocols
$scheme = parse_url($url, PHP_URL_SCHEME);
$hostname = parse_url($url, PHP_URL_HOST);
if (in_array($scheme, ['http', 'git', 'ftp', 'svn'])) {
if ($this->get('secure-http')) {
if ($scheme === 'svn') {
if (in_array($hostname, $this->get('secure-svn-domains'), true)) {
return;
}
throw new TransportException("Your configuration does not allow connections to $url. See https://getcomposer.org/doc/06-config.md#secure-svn-domains for details.");
}
throw new TransportException("Your configuration does not allow connections to $url. See https://getcomposer.org/doc/06-config.md#secure-http for details.");
}
if ($io !== null) {
if (is_string($hostname)) {
if (!isset($this->warnedHosts[$hostname])) {
$io->writeError("<warning>Warning: Accessing $hostname over $scheme which is an insecure protocol.</warning>");
}
$this->warnedHosts[$hostname] = true;
}
}
}
if ($io !== null && is_string($hostname) && !isset($this->sslVerifyWarnedHosts[$hostname])) {
$warning = null;
if (isset($repoOptions['ssl']['verify_peer']) && !(bool) $repoOptions['ssl']['verify_peer']) {
$warning = 'verify_peer';
}
if (isset($repoOptions['ssl']['verify_peer_name']) && !(bool) $repoOptions['ssl']['verify_peer_name']) {
$warning = $warning === null ? 'verify_peer_name' : $warning . ' and verify_peer_name';
}
if ($warning !== null) {
$io->writeError("<warning>Warning: Accessing $hostname with $warning disabled.</warning>");
$this->sslVerifyWarnedHosts[$hostname] = true;
}
}
}
/**
* Used by long-running custom scripts in composer.json
*
* "scripts": {
* "watch": [
* "Composer\\Config::disableProcessTimeout",
* "vendor/bin/long-running-script --watch"
* ]
* }
*/
public static function disableProcessTimeout(): void
{
// Override global timeout set earlier by environment or config
ProcessExecutor::setTimeout(0);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/PartialComposer.php | src/Composer/PartialComposer.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer;
use Composer\Package\RootPackageInterface;
use Composer\Util\Loop;
use Composer\Repository\RepositoryManager;
use Composer\Installer\InstallationManager;
use Composer\EventDispatcher\EventDispatcher;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class PartialComposer
{
/**
* @var bool
*/
private $global = false;
/**
* @var RootPackageInterface
*/
private $package;
/**
* @var Loop
*/
private $loop;
/**
* @var RepositoryManager
*/
private $repositoryManager;
/**
* @var InstallationManager
*/
private $installationManager;
/**
* @var Config
*/
private $config;
/**
* @var EventDispatcher
*/
private $eventDispatcher;
public function setPackage(RootPackageInterface $package): void
{
$this->package = $package;
}
public function getPackage(): RootPackageInterface
{
return $this->package;
}
public function setConfig(Config $config): void
{
$this->config = $config;
}
public function getConfig(): Config
{
return $this->config;
}
public function setLoop(Loop $loop): void
{
$this->loop = $loop;
}
public function getLoop(): Loop
{
return $this->loop;
}
public function setRepositoryManager(RepositoryManager $manager): void
{
$this->repositoryManager = $manager;
}
public function getRepositoryManager(): RepositoryManager
{
return $this->repositoryManager;
}
public function setInstallationManager(InstallationManager $manager): void
{
$this->installationManager = $manager;
}
public function getInstallationManager(): InstallationManager
{
return $this->installationManager;
}
public function setEventDispatcher(EventDispatcher $eventDispatcher): void
{
$this->eventDispatcher = $eventDispatcher;
}
public function getEventDispatcher(): EventDispatcher
{
return $this->eventDispatcher;
}
public function isGlobal(): bool
{
return $this->global;
}
public function setGlobal(): void
{
$this->global = true;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Cache.php | src/Composer/Cache.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer;
use Composer\IO\IOInterface;
use Composer\Pcre\Preg;
use Composer\Util\Filesystem;
use Composer\Util\Platform;
use Composer\Util\Silencer;
use Symfony\Component\Finder\Finder;
/**
* Reads/writes to a filesystem cache
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class Cache
{
/** @var bool|null */
private static $cacheCollected = null;
/** @var IOInterface */
private $io;
/** @var string */
private $root;
/** @var ?bool */
private $enabled = null;
/** @var string */
private $allowlist;
/** @var Filesystem */
private $filesystem;
/** @var bool */
private $readOnly;
/**
* @param string $cacheDir location of the cache
* @param string $allowlist List of characters that are allowed in path names (used in a regex character class)
* @param Filesystem $filesystem optional filesystem instance
* @param bool $readOnly whether the cache is in readOnly mode
*/
public function __construct(IOInterface $io, string $cacheDir, string $allowlist = 'a-z0-9._', ?Filesystem $filesystem = null, bool $readOnly = false)
{
$this->io = $io;
$this->root = rtrim($cacheDir, '/\\') . '/';
$this->allowlist = $allowlist;
$this->filesystem = $filesystem ?: new Filesystem();
$this->readOnly = $readOnly;
if (!self::isUsable($cacheDir)) {
$this->enabled = false;
}
}
/**
* @return void
*/
public function setReadOnly(bool $readOnly)
{
$this->readOnly = $readOnly;
}
/**
* @return bool
*/
public function isReadOnly()
{
return $this->readOnly;
}
/**
* @return bool
*/
public static function isUsable(string $path)
{
return !Preg::isMatch('{(^|[\\\\/])(\$null|nul|NUL|/dev/null)([\\\\/]|$)}', $path);
}
/**
* @return bool
*/
public function isEnabled()
{
if ($this->enabled === null) {
$this->enabled = true;
if (
!$this->readOnly
&& (
(!is_dir($this->root) && !Silencer::call('mkdir', $this->root, 0777, true))
|| !is_writable($this->root)
)
) {
$this->io->writeError('<warning>Cannot create cache directory ' . $this->root . ', or directory is not writable. Proceeding without cache. See also cache-read-only config if your filesystem is read-only.</warning>');
$this->enabled = false;
}
}
return $this->enabled;
}
/**
* @return string
*/
public function getRoot()
{
return $this->root;
}
/**
* @return string|false
*/
public function read(string $file)
{
if ($this->isEnabled()) {
$file = Preg::replace('{[^'.$this->allowlist.']}i', '-', $file);
if (file_exists($this->root . $file)) {
$this->io->writeError('Reading '.$this->root . $file.' from cache', true, IOInterface::DEBUG);
return file_get_contents($this->root . $file);
}
}
return false;
}
/**
* @return bool
*/
public function write(string $file, string $contents)
{
$wasEnabled = $this->enabled === true;
if ($this->isEnabled() && !$this->readOnly) {
$file = Preg::replace('{[^'.$this->allowlist.']}i', '-', $file);
$this->io->writeError('Writing '.$this->root . $file.' into cache', true, IOInterface::DEBUG);
$tempFileName = $this->root . $file . bin2hex(random_bytes(5)) . '.tmp';
try {
return file_put_contents($tempFileName, $contents) !== false && rename($tempFileName, $this->root . $file);
} catch (\ErrorException $e) {
// If the write failed despite isEnabled checks passing earlier, rerun the isEnabled checks to
// see if they are still current and recreate the cache dir if needed. Refs https://github.com/composer/composer/issues/11076
if ($wasEnabled) {
clearstatcache();
$this->enabled = null;
return $this->write($file, $contents);
}
$this->io->writeError('<warning>Failed to write into cache: '.$e->getMessage().'</warning>', true, IOInterface::DEBUG);
if (Preg::isMatch('{^file_put_contents\(\): Only ([0-9]+) of ([0-9]+) bytes written}', $e->getMessage(), $m)) {
// Remove partial file.
unlink($tempFileName);
$message = sprintf(
'<warning>Writing %1$s into cache failed after %2$u of %3$u bytes written, only %4$s bytes of free space available</warning>',
$tempFileName,
$m[1],
$m[2],
function_exists('disk_free_space') ? @disk_free_space(dirname($tempFileName)) : 'unknown'
);
$this->io->writeError($message);
return false;
}
throw $e;
}
}
return false;
}
/**
* Copy a file into the cache
*
* @return bool
*/
public function copyFrom(string $file, string $source)
{
if ($this->isEnabled() && !$this->readOnly) {
$file = Preg::replace('{[^'.$this->allowlist.']}i', '-', $file);
$this->filesystem->ensureDirectoryExists(dirname($this->root . $file));
if (!file_exists($source)) {
$this->io->writeError('<error>'.$source.' does not exist, can not write into cache</error>');
} elseif ($this->io->isDebug()) {
$this->io->writeError('Writing '.$this->root . $file.' into cache from '.$source);
}
return $this->filesystem->copy($source, $this->root . $file);
}
return false;
}
/**
* Copy a file out of the cache
*
* @return bool
*/
public function copyTo(string $file, string $target)
{
if ($this->isEnabled()) {
$file = Preg::replace('{[^'.$this->allowlist.']}i', '-', $file);
if (file_exists($this->root . $file)) {
try {
touch($this->root . $file, (int) filemtime($this->root . $file), time());
} catch (\ErrorException $e) {
// fallback in case the above failed due to incorrect ownership
// see https://github.com/composer/composer/issues/4070
Silencer::call('touch', $this->root . $file);
}
$this->io->writeError('Reading '.$this->root . $file.' from cache', true, IOInterface::DEBUG);
return $this->filesystem->copy($this->root . $file, $target);
}
}
return false;
}
/**
* @return bool
*/
public function gcIsNecessary()
{
if (self::$cacheCollected) {
return false;
}
self::$cacheCollected = true;
if (Platform::getEnv('COMPOSER_TEST_SUITE')) {
return false;
}
if (Platform::isInputCompletionProcess()) {
return false;
}
return !random_int(0, 50);
}
/**
* @return bool
*/
public function remove(string $file)
{
if ($this->isEnabled() && !$this->readOnly) {
$file = Preg::replace('{[^'.$this->allowlist.']}i', '-', $file);
if (file_exists($this->root . $file)) {
return $this->filesystem->unlink($this->root . $file);
}
}
return false;
}
/**
* @return bool
*/
public function clear()
{
if ($this->isEnabled() && !$this->readOnly) {
$this->filesystem->emptyDirectory($this->root);
return true;
}
return false;
}
/**
* @return int|false
* @phpstan-return int<0, max>|false
*/
public function getAge(string $file)
{
if ($this->isEnabled()) {
$file = Preg::replace('{[^'.$this->allowlist.']}i', '-', $file);
if (file_exists($this->root . $file) && ($mtime = filemtime($this->root . $file)) !== false) {
return abs(time() - $mtime);
}
}
return false;
}
/**
* @return bool
*/
public function gc(int $ttl, int $maxSize)
{
if ($this->isEnabled() && !$this->readOnly) {
$expire = new \DateTime();
$expire->modify('-'.$ttl.' seconds');
$finder = $this->getFinder()->date('until '.$expire->format('Y-m-d H:i:s'));
foreach ($finder as $file) {
$this->filesystem->unlink($file->getPathname());
}
$totalSize = $this->filesystem->size($this->root);
if ($totalSize > $maxSize) {
$iterator = $this->getFinder()->sortByAccessedTime()->getIterator();
while ($totalSize > $maxSize && $iterator->valid()) {
$filepath = $iterator->current()->getPathname();
$totalSize -= $this->filesystem->size($filepath);
$this->filesystem->unlink($filepath);
$iterator->next();
}
}
self::$cacheCollected = true;
return true;
}
return false;
}
public function gcVcsCache(int $ttl): bool
{
if ($this->isEnabled()) {
$expire = new \DateTime();
$expire->modify('-'.$ttl.' seconds');
$finder = Finder::create()->in($this->root)->directories()->depth(0)->date('until '.$expire->format('Y-m-d H:i:s'));
foreach ($finder as $file) {
$this->filesystem->removeDirectory($file->getPathname());
}
self::$cacheCollected = true;
return true;
}
return false;
}
/**
* @return string|false
*/
public function sha1(string $file)
{
if ($this->isEnabled()) {
$file = Preg::replace('{[^'.$this->allowlist.']}i', '-', $file);
if (file_exists($this->root . $file)) {
return hash_file('sha1', $this->root . $file);
}
}
return false;
}
/**
* @return string|false
*/
public function sha256(string $file)
{
if ($this->isEnabled()) {
$file = Preg::replace('{[^'.$this->allowlist.']}i', '-', $file);
if (file_exists($this->root . $file)) {
return hash_file('sha256', $this->root . $file);
}
}
return false;
}
/**
* @return Finder
*/
protected function getFinder()
{
return Finder::create()->in($this->root)->files();
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Factory.php | src/Composer/Factory.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer;
use Composer\Config\JsonConfigSource;
use Composer\Json\JsonFile;
use Composer\IO\IOInterface;
use Composer\Package\Archiver;
use Composer\Package\Version\VersionGuesser;
use Composer\Package\RootPackageInterface;
use Composer\Repository\FilesystemRepository;
use Composer\Repository\RepositoryManager;
use Composer\Repository\RepositoryFactory;
use Composer\Util\Filesystem;
use Composer\Util\Platform;
use Composer\Util\ProcessExecutor;
use Composer\Util\HttpDownloader;
use Composer\Util\Loop;
use Composer\Util\Silencer;
use Composer\Plugin\PluginEvents;
use Composer\EventDispatcher\Event;
use Phar;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
use Symfony\Component\Console\Output\ConsoleOutput;
use Composer\EventDispatcher\EventDispatcher;
use Composer\Autoload\AutoloadGenerator;
use Composer\Package\Version\VersionParser;
use Composer\Downloader\TransportException;
use Composer\Json\JsonValidationException;
use Composer\Repository\InstalledRepositoryInterface;
use UnexpectedValueException;
use ZipArchive;
/**
* Creates a configured instance of composer.
*
* @author Ryan Weaver <ryan@knplabs.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author Igor Wiedler <igor@wiedler.ch>
* @author Nils Adermann <naderman@naderman.de>
*/
class Factory
{
/**
* @throws \RuntimeException
*/
protected static function getHomeDir(): string
{
$home = Platform::getEnv('COMPOSER_HOME');
if ($home) {
return $home;
}
if (Platform::isWindows()) {
if (!Platform::getEnv('APPDATA')) {
throw new \RuntimeException('The APPDATA or COMPOSER_HOME environment variable must be set for composer to run correctly');
}
return rtrim(strtr(Platform::getEnv('APPDATA'), '\\', '/'), '/') . '/Composer';
}
$userDir = self::getUserDir();
$dirs = [];
if (self::useXdg()) {
// XDG Base Directory Specifications
$xdgConfig = Platform::getEnv('XDG_CONFIG_HOME');
if (!$xdgConfig) {
$xdgConfig = $userDir . '/.config';
}
$dirs[] = $xdgConfig . '/composer';
}
$dirs[] = $userDir . '/.composer';
// select first dir which exists of: $XDG_CONFIG_HOME/composer or ~/.composer
foreach ($dirs as $dir) {
if (Silencer::call('is_dir', $dir)) {
return $dir;
}
}
// if none exists, we default to first defined one (XDG one if system uses it, or ~/.composer otherwise)
return $dirs[0];
}
protected static function getCacheDir(string $home): string
{
$cacheDir = Platform::getEnv('COMPOSER_CACHE_DIR');
if ($cacheDir) {
return $cacheDir;
}
$homeEnv = Platform::getEnv('COMPOSER_HOME');
if ($homeEnv) {
return $homeEnv . '/cache';
}
if (Platform::isWindows()) {
if ($cacheDir = Platform::getEnv('LOCALAPPDATA')) {
$cacheDir .= '/Composer';
} else {
$cacheDir = $home . '/cache';
}
return rtrim(strtr($cacheDir, '\\', '/'), '/');
}
$userDir = self::getUserDir();
if (PHP_OS === 'Darwin') {
// Migrate existing cache dir in old location if present
if (is_dir($home . '/cache') && !is_dir($userDir . '/Library/Caches/composer')) {
Silencer::call('rename', $home . '/cache', $userDir . '/Library/Caches/composer');
}
return $userDir . '/Library/Caches/composer';
}
if ($home === $userDir . '/.composer' && is_dir($home . '/cache')) {
return $home . '/cache';
}
if (self::useXdg()) {
$xdgCache = Platform::getEnv('XDG_CACHE_HOME') ?: $userDir . '/.cache';
return $xdgCache . '/composer';
}
return $home . '/cache';
}
protected static function getDataDir(string $home): string
{
$homeEnv = Platform::getEnv('COMPOSER_HOME');
if ($homeEnv) {
return $homeEnv;
}
if (Platform::isWindows()) {
return strtr($home, '\\', '/');
}
$userDir = self::getUserDir();
if ($home !== $userDir . '/.composer' && self::useXdg()) {
$xdgData = Platform::getEnv('XDG_DATA_HOME') ?: $userDir . '/.local/share';
return $xdgData . '/composer';
}
return $home;
}
public static function createConfig(?IOInterface $io = null, ?string $cwd = null): Config
{
$cwd = $cwd ?? Platform::getCwd(true);
$config = new Config(true, $cwd);
// determine and add main dirs to the config
$home = self::getHomeDir();
$config->merge([
'config' => [
'home' => $home,
'cache-dir' => self::getCacheDir($home),
'data-dir' => self::getDataDir($home),
],
], Config::SOURCE_DEFAULT);
// load global config
$file = new JsonFile($config->get('home').'/config.json');
if ($file->exists()) {
if ($io instanceof IOInterface) {
$io->writeError('Loading config file ' . $file->getPath(), true, IOInterface::DEBUG);
}
self::validateJsonSchema($io, $file);
$config->merge($file->read(), $file->getPath());
}
$config->setConfigSource(new JsonConfigSource($file));
$htaccessProtect = $config->get('htaccess-protect');
if ($htaccessProtect) {
// Protect directory against web access. Since HOME could be
// the www-data's user home and be web-accessible it is a
// potential security risk
$dirs = [$config->get('home'), $config->get('cache-dir'), $config->get('data-dir')];
foreach ($dirs as $dir) {
if (!file_exists($dir . '/.htaccess')) {
if (!is_dir($dir)) {
Silencer::call('mkdir', $dir, 0777, true);
}
Silencer::call('file_put_contents', $dir . '/.htaccess', 'Deny from all');
}
}
}
// load global auth file
$file = new JsonFile($config->get('home').'/auth.json');
if ($file->exists()) {
if ($io instanceof IOInterface) {
$io->writeError('Loading config file ' . $file->getPath(), true, IOInterface::DEBUG);
}
self::validateJsonSchema($io, $file, JsonFile::AUTH_SCHEMA);
$config->merge(['config' => $file->read()], $file->getPath());
}
$config->setAuthConfigSource(new JsonConfigSource($file, true));
self::loadComposerAuthEnv($config, $io);
return $config;
}
public static function getComposerFile(): string
{
$env = Platform::getEnv('COMPOSER');
if (is_string($env)) {
$env = trim($env);
if ('' !== $env) {
if (is_dir($env)) {
throw new \RuntimeException('The COMPOSER environment variable is set to '.$env.' which is a directory, this variable should point to a composer.json or be left unset.');
}
return $env;
}
}
return './composer.json';
}
public static function getLockFile(string $composerFile): string
{
return "json" === pathinfo($composerFile, PATHINFO_EXTENSION)
? substr($composerFile, 0, -4).'lock'
: $composerFile . '.lock';
}
/**
* @return array{highlight: OutputFormatterStyle, warning: OutputFormatterStyle}
*/
public static function createAdditionalStyles(): array
{
return [
'highlight' => new OutputFormatterStyle('red'),
'warning' => new OutputFormatterStyle('black', 'yellow'),
];
}
public static function createOutput(): ConsoleOutput
{
$styles = self::createAdditionalStyles();
$formatter = new OutputFormatter(false, $styles);
return new ConsoleOutput(ConsoleOutput::VERBOSITY_NORMAL, null, $formatter);
}
/**
* Creates a Composer instance
*
* @param IOInterface $io IO instance
* @param array<string, mixed>|string|null $localConfig either a configuration array or a filename to read from, if null it will
* read from the default filename
* @param bool|'local'|'global' $disablePlugins Whether plugins should not be loaded, can be set to local or global to only disable local/global plugins
* @param bool $disableScripts Whether scripts should not be run
* @param bool $fullLoad Whether to initialize everything or only main project stuff (used when loading the global composer)
* @throws \InvalidArgumentException
* @throws UnexpectedValueException
* @return Composer|PartialComposer Composer if $fullLoad is true, otherwise PartialComposer
* @phpstan-return ($fullLoad is true ? Composer : PartialComposer)
*/
public function createComposer(IOInterface $io, $localConfig = null, $disablePlugins = false, ?string $cwd = null, bool $fullLoad = true, bool $disableScripts = false)
{
// if a custom composer.json path is given, we change the default cwd to be that file's directory
if (is_string($localConfig) && is_file($localConfig) && null === $cwd) {
$cwd = dirname($localConfig);
}
$cwd = $cwd ?? Platform::getCwd(true);
// load Composer configuration
if (null === $localConfig) {
$localConfig = static::getComposerFile();
}
$localConfigSource = Config::SOURCE_UNKNOWN;
if (is_string($localConfig)) {
$composerFile = $localConfig;
$file = new JsonFile($localConfig, null, $io);
if (!$file->exists()) {
if ($localConfig === './composer.json' || $localConfig === 'composer.json') {
$message = 'Composer could not find a composer.json file in '.$cwd;
} else {
$message = 'Composer could not find the config file: '.$localConfig;
}
$instructions = $fullLoad ? 'To initialize a project, please create a composer.json file. See https://getcomposer.org/basic-usage' : '';
throw new \InvalidArgumentException($message.PHP_EOL.$instructions);
}
if (!Platform::isInputCompletionProcess()) {
try {
$file->validateSchema(JsonFile::LAX_SCHEMA);
} catch (JsonValidationException $e) {
$errors = ' - ' . implode(PHP_EOL . ' - ', $e->getErrors());
$message = $e->getMessage() . ':' . PHP_EOL . $errors;
throw new JsonValidationException($message);
}
}
$localConfig = $file->read();
$localConfigSource = $file->getPath();
}
// Load config and override with local config/auth config
$config = static::createConfig($io, $cwd);
$isGlobal = $localConfigSource !== Config::SOURCE_UNKNOWN && realpath($config->get('home')) === realpath(dirname($localConfigSource));
$config->merge($localConfig, $localConfigSource);
if (isset($composerFile)) {
$io->writeError('Loading config file ' . $composerFile .' ('.realpath($composerFile).')', true, IOInterface::DEBUG);
$config->setConfigSource(new JsonConfigSource(new JsonFile(realpath($composerFile), null, $io)));
$localAuthFile = new JsonFile(dirname(realpath($composerFile)) . '/auth.json', null, $io);
if ($localAuthFile->exists()) {
$io->writeError('Loading config file ' . $localAuthFile->getPath(), true, IOInterface::DEBUG);
self::validateJsonSchema($io, $localAuthFile, JsonFile::AUTH_SCHEMA);
$config->merge(['config' => $localAuthFile->read()], $localAuthFile->getPath());
$config->setLocalAuthConfigSource(new JsonConfigSource($localAuthFile, true));
}
}
// make sure we load the auth env again over the local auth.json + composer.json config
self::loadComposerAuthEnv($config, $io);
$vendorDir = $config->get('vendor-dir');
// initialize composer
$composer = $fullLoad ? new Composer() : new PartialComposer();
$composer->setConfig($config);
if ($isGlobal) {
$composer->setGlobal();
}
if ($fullLoad) {
// load auth configs into the IO instance
$io->loadConfiguration($config);
// load existing Composer\InstalledVersions instance if available and scripts/plugins are allowed, as they might need it
// we only load if the InstalledVersions class wasn't defined yet so that this is only loaded once
if (false === $disablePlugins && false === $disableScripts && !class_exists('Composer\InstalledVersions', false) && file_exists($installedVersionsPath = $config->get('vendor-dir').'/composer/installed.php')) {
// force loading the class at this point so it is loaded from the composer phar and not from the vendor dir
// as we cannot guarantee integrity of that file
if (class_exists('Composer\InstalledVersions')) {
FilesystemRepository::safelyLoadInstalledVersions($installedVersionsPath);
}
}
}
$httpDownloader = self::createHttpDownloader($io, $config);
$process = new ProcessExecutor($io);
$loop = new Loop($httpDownloader, $process);
$composer->setLoop($loop);
// initialize event dispatcher
$dispatcher = new EventDispatcher($composer, $io, $process);
$dispatcher->setRunScripts(!$disableScripts);
$composer->setEventDispatcher($dispatcher);
// initialize repository manager
$rm = RepositoryFactory::manager($io, $config, $httpDownloader, $dispatcher, $process);
$composer->setRepositoryManager($rm);
// force-set the version of the global package if not defined as
// guessing it adds no value and only takes time
if (!$fullLoad && !isset($localConfig['version'])) {
$localConfig['version'] = '1.0.0';
}
// load package
$parser = new VersionParser;
$guesser = new VersionGuesser($config, $process, $parser, $io);
$loader = $this->loadRootPackage($rm, $config, $parser, $guesser, $io);
$package = $loader->load($localConfig, 'Composer\Package\RootPackage', $cwd);
$composer->setPackage($package);
// load local repository
$this->addLocalRepository($io, $rm, $vendorDir, $package, $process);
// initialize installation manager
$im = $this->createInstallationManager($loop, $io, $dispatcher);
$composer->setInstallationManager($im);
if ($composer instanceof Composer) {
// initialize download manager
$dm = $this->createDownloadManager($io, $config, $httpDownloader, $process, $dispatcher);
$composer->setDownloadManager($dm);
// initialize autoload generator
$generator = new AutoloadGenerator($dispatcher, $io);
$composer->setAutoloadGenerator($generator);
// initialize archive manager
$am = $this->createArchiveManager($config, $dm, $loop);
$composer->setArchiveManager($am);
}
// add installers to the manager (must happen after download manager is created since they read it out of $composer)
$this->createDefaultInstallers($im, $composer, $io, $process);
// init locker if possible
if ($composer instanceof Composer && isset($composerFile)) {
$lockFile = self::getLockFile($composerFile);
if (!$config->get('lock') && file_exists($lockFile)) {
$io->writeError('<warning>'.$lockFile.' is present but ignored as the "lock" config option is disabled.</warning>');
}
$locker = new Package\Locker($io, new JsonFile($config->get('lock') ? $lockFile : Platform::getDevNull(), null, $io), $im, file_get_contents($composerFile), $process);
$composer->setLocker($locker);
} elseif ($composer instanceof Composer) {
$locker = new Package\Locker($io, new JsonFile(Platform::getDevNull(), null, $io), $im, JsonFile::encode($localConfig), $process);
$composer->setLocker($locker);
}
if ($composer instanceof Composer) {
$globalComposer = null;
if (!$composer->isGlobal()) {
$globalComposer = $this->createGlobalComposer($io, $config, $disablePlugins, $disableScripts);
}
$pm = $this->createPluginManager($io, $composer, $globalComposer, $disablePlugins);
$composer->setPluginManager($pm);
if ($composer->isGlobal()) {
$pm->setRunningInGlobalDir(true);
}
$pm->loadInstalledPlugins();
}
if ($fullLoad) {
$initEvent = new Event(PluginEvents::INIT);
$composer->getEventDispatcher()->dispatch($initEvent->getName(), $initEvent);
// once everything is initialized we can
// purge packages from local repos if they have been deleted on the filesystem
$this->purgePackages($rm->getLocalRepository(), $im);
}
return $composer;
}
/**
* @param bool $disablePlugins Whether plugins should not be loaded
* @param bool $disableScripts Whether scripts should not be executed
*/
public static function createGlobal(IOInterface $io, bool $disablePlugins = false, bool $disableScripts = false): ?Composer
{
$factory = new static();
return $factory->createGlobalComposer($io, static::createConfig($io), $disablePlugins, $disableScripts, true);
}
protected function addLocalRepository(IOInterface $io, RepositoryManager $rm, string $vendorDir, RootPackageInterface $rootPackage, ?ProcessExecutor $process = null): void
{
$fs = null;
if ($process) {
$fs = new Filesystem($process);
}
$rm->setLocalRepository(new Repository\InstalledFilesystemRepository(new JsonFile($vendorDir.'/composer/installed.json', null, $io), true, $rootPackage, $fs));
}
/**
* @param bool|'local'|'global' $disablePlugins Whether plugins should not be loaded, can be set to local or global to only disable local/global plugins
* @return PartialComposer|Composer|null By default PartialComposer, but Composer if $fullLoad is set to true
* @phpstan-return ($fullLoad is true ? Composer|null : PartialComposer|null)
*/
protected function createGlobalComposer(IOInterface $io, Config $config, $disablePlugins, bool $disableScripts, bool $fullLoad = false): ?PartialComposer
{
// make sure if disable plugins was 'local' it is now turned off
$disablePlugins = $disablePlugins === 'global' || $disablePlugins === true;
$composer = null;
try {
$composer = $this->createComposer($io, $config->get('home') . '/composer.json', $disablePlugins, $config->get('home'), $fullLoad, $disableScripts);
} catch (\Exception $e) {
$io->writeError('Failed to initialize global composer: '.$e->getMessage(), true, IOInterface::DEBUG);
}
return $composer;
}
public function createDownloadManager(IOInterface $io, Config $config, HttpDownloader $httpDownloader, ProcessExecutor $process, ?EventDispatcher $eventDispatcher = null): Downloader\DownloadManager
{
$cache = null;
if ($config->get('cache-files-ttl') > 0) {
$cache = new Cache($io, $config->get('cache-files-dir'), 'a-z0-9_./');
$cache->setReadOnly($config->get('cache-read-only'));
}
$fs = new Filesystem($process);
$dm = new Downloader\DownloadManager($io, false, $fs);
switch ($preferred = $config->get('preferred-install')) {
case 'dist':
$dm->setPreferDist(true);
break;
case 'source':
$dm->setPreferSource(true);
break;
case 'auto':
default:
// noop
break;
}
if (is_array($preferred)) {
$dm->setPreferences($preferred);
}
$dm->setDownloader('git', new Downloader\GitDownloader($io, $config, $process, $fs));
$dm->setDownloader('svn', new Downloader\SvnDownloader($io, $config, $process, $fs));
$dm->setDownloader('fossil', new Downloader\FossilDownloader($io, $config, $process, $fs));
$dm->setDownloader('hg', new Downloader\HgDownloader($io, $config, $process, $fs));
$dm->setDownloader('perforce', new Downloader\PerforceDownloader($io, $config, $process, $fs));
$dm->setDownloader('zip', new Downloader\ZipDownloader($io, $config, $httpDownloader, $eventDispatcher, $cache, $fs, $process));
$dm->setDownloader('rar', new Downloader\RarDownloader($io, $config, $httpDownloader, $eventDispatcher, $cache, $fs, $process));
$dm->setDownloader('tar', new Downloader\TarDownloader($io, $config, $httpDownloader, $eventDispatcher, $cache, $fs, $process));
$dm->setDownloader('gzip', new Downloader\GzipDownloader($io, $config, $httpDownloader, $eventDispatcher, $cache, $fs, $process));
$dm->setDownloader('xz', new Downloader\XzDownloader($io, $config, $httpDownloader, $eventDispatcher, $cache, $fs, $process));
$dm->setDownloader('phar', new Downloader\PharDownloader($io, $config, $httpDownloader, $eventDispatcher, $cache, $fs, $process));
$dm->setDownloader('file', new Downloader\FileDownloader($io, $config, $httpDownloader, $eventDispatcher, $cache, $fs, $process));
$dm->setDownloader('path', new Downloader\PathDownloader($io, $config, $httpDownloader, $eventDispatcher, $cache, $fs, $process));
return $dm;
}
/**
* @param Config $config The configuration
* @param Downloader\DownloadManager $dm Manager use to download sources
* @return Archiver\ArchiveManager
*/
public function createArchiveManager(Config $config, Downloader\DownloadManager $dm, Loop $loop)
{
$am = new Archiver\ArchiveManager($dm, $loop);
if (class_exists(ZipArchive::class)) {
$am->addArchiver(new Archiver\ZipArchiver);
}
if (class_exists(Phar::class)) {
$am->addArchiver(new Archiver\PharArchiver);
}
return $am;
}
/**
* @param bool|'local'|'global' $disablePlugins Whether plugins should not be loaded, can be set to local or global to only disable local/global plugins
*/
protected function createPluginManager(IOInterface $io, Composer $composer, ?PartialComposer $globalComposer = null, $disablePlugins = false): Plugin\PluginManager
{
return new Plugin\PluginManager($io, $composer, $globalComposer, $disablePlugins);
}
public function createInstallationManager(Loop $loop, IOInterface $io, ?EventDispatcher $eventDispatcher = null): Installer\InstallationManager
{
return new Installer\InstallationManager($loop, $io, $eventDispatcher);
}
protected function createDefaultInstallers(Installer\InstallationManager $im, PartialComposer $composer, IOInterface $io, ?ProcessExecutor $process = null): void
{
$fs = new Filesystem($process);
$binaryInstaller = new Installer\BinaryInstaller($io, rtrim($composer->getConfig()->get('bin-dir'), '/'), $composer->getConfig()->get('bin-compat'), $fs, rtrim($composer->getConfig()->get('vendor-dir'), '/'));
$im->addInstaller(new Installer\LibraryInstaller($io, $composer, null, $fs, $binaryInstaller));
$im->addInstaller(new Installer\PluginInstaller($io, $composer, $fs, $binaryInstaller));
$im->addInstaller(new Installer\MetapackageInstaller($io));
}
/**
* @param InstalledRepositoryInterface $repo repository to purge packages from
* @param Installer\InstallationManager $im manager to check whether packages are still installed
*/
protected function purgePackages(InstalledRepositoryInterface $repo, Installer\InstallationManager $im): void
{
foreach ($repo->getPackages() as $package) {
if (!$im->isPackageInstalled($repo, $package)) {
$repo->removePackage($package);
}
}
}
protected function loadRootPackage(RepositoryManager $rm, Config $config, VersionParser $parser, VersionGuesser $guesser, IOInterface $io): Package\Loader\RootPackageLoader
{
return new Package\Loader\RootPackageLoader($rm, $config, $parser, $guesser, $io);
}
/**
* @param IOInterface $io IO instance
* @param mixed $config either a configuration array or a filename to read from, if null it will read from
* the default filename
* @param bool|'local'|'global' $disablePlugins Whether plugins should not be loaded, can be set to local or global to only disable local/global plugins
* @param bool $disableScripts Whether scripts should not be run
*/
public static function create(IOInterface $io, $config = null, $disablePlugins = false, bool $disableScripts = false): Composer
{
$factory = new static();
// for BC reasons, if a config is passed in either as array or a path that is not the default composer.json path
// we disable local plugins as they really should not be loaded from CWD
// If you want to avoid this behavior, you should be calling createComposer directly with a $cwd arg set correctly
// to the path where the composer.json being loaded resides
if ($config !== null && $config !== self::getComposerFile() && $disablePlugins === false) {
$disablePlugins = 'local';
}
return $factory->createComposer($io, $config, $disablePlugins, null, true, $disableScripts);
}
/**
* If you are calling this in a plugin, you probably should instead use $composer->getLoop()->getHttpDownloader()
*
* @param IOInterface $io IO instance
* @param Config $config Config instance
* @param mixed[] $options Array of options passed directly to HttpDownloader constructor
*/
public static function createHttpDownloader(IOInterface $io, Config $config, array $options = []): HttpDownloader
{
static $warned = false;
$disableTls = false;
// allow running the config command if disable-tls is in the arg list, even if openssl is missing, to allow disabling it via the config command
if (isset($_SERVER['argv']) && in_array('disable-tls', $_SERVER['argv']) && (in_array('conf', $_SERVER['argv']) || in_array('config', $_SERVER['argv']))) {
$warned = true;
$disableTls = !extension_loaded('openssl');
} elseif ($config->get('disable-tls') === true) {
if (!$warned) {
$io->writeError('<warning>You are running Composer with SSL/TLS protection disabled.</warning>');
}
$warned = true;
$disableTls = true;
} elseif (!extension_loaded('openssl')) {
throw new Exception\NoSslException('The openssl extension is required for SSL/TLS protection but is not available. '
. 'If you can not enable the openssl extension, you can disable this error, at your own risk, by setting the \'disable-tls\' option to true.');
}
$httpDownloaderOptions = [];
if ($disableTls === false) {
if ('' !== $config->get('cafile')) {
$httpDownloaderOptions['ssl']['cafile'] = $config->get('cafile');
}
if ('' !== $config->get('capath')) {
$httpDownloaderOptions['ssl']['capath'] = $config->get('capath');
}
$httpDownloaderOptions = array_replace_recursive($httpDownloaderOptions, $options);
}
try {
$httpDownloader = new HttpDownloader($io, $config, $httpDownloaderOptions, $disableTls);
} catch (TransportException $e) {
if (false !== strpos($e->getMessage(), 'cafile')) {
$io->write('<error>Unable to locate a valid CA certificate file. You must set a valid \'cafile\' option.</error>');
$io->write('<error>A valid CA certificate file is required for SSL/TLS protection.</error>');
$io->write('<error>You can disable this error, at your own risk, by setting the \'disable-tls\' option to true.</error>');
}
throw $e;
}
return $httpDownloader;
}
private static function loadComposerAuthEnv(Config $config, ?IOInterface $io): void
{
$composerAuthEnv = Platform::getEnv('COMPOSER_AUTH');
if (false === $composerAuthEnv || '' === $composerAuthEnv) {
return;
}
$authData = json_decode($composerAuthEnv);
if (null === $authData) {
throw new UnexpectedValueException('COMPOSER_AUTH environment variable is malformed, should be a valid JSON object');
}
if ($io instanceof IOInterface) {
$io->writeError('Loading auth config from COMPOSER_AUTH', true, IOInterface::DEBUG);
}
self::validateJsonSchema($io, $authData, JsonFile::AUTH_SCHEMA, 'COMPOSER_AUTH');
$authData = json_decode($composerAuthEnv, true);
if (null !== $authData) {
$config->merge(['config' => $authData], 'COMPOSER_AUTH');
}
}
private static function useXdg(): bool
{
foreach (array_keys($_SERVER) as $key) {
if (strpos((string) $key, 'XDG_') === 0) {
return true;
}
}
if (Silencer::call('is_dir', '/etc/xdg')) {
return true;
}
return false;
}
/**
* @throws \RuntimeException
*/
private static function getUserDir(): string
{
$home = Platform::getEnv('HOME');
if (!$home) {
throw new \RuntimeException('The HOME or COMPOSER_HOME environment variable must be set for composer to run correctly');
}
return rtrim(strtr($home, '\\', '/'), '/');
}
/**
* @param mixed $fileOrData
* @param JsonFile::*_SCHEMA $schema
*/
private static function validateJsonSchema(?IOInterface $io, $fileOrData, int $schema = JsonFile::LAX_SCHEMA, ?string $source = null): void
{
if (Platform::isInputCompletionProcess()) {
return;
}
try {
if ($fileOrData instanceof JsonFile) {
$fileOrData->validateSchema($schema);
} else {
if (null === $source) {
throw new \InvalidArgumentException('$source is required to be provided if $fileOrData is arbitrary data');
}
JsonFile::validateJsonSchema($source, $fileOrData, $schema);
}
} catch (JsonValidationException $e) {
$msg = $e->getMessage().', this may result in errors and should be resolved:'.PHP_EOL.' - '.implode(PHP_EOL.' - ', $e->getErrors());
if ($io instanceof IOInterface) {
$io->writeError('<warning>'.$msg.'</>');
} else {
throw new UnexpectedValueException($msg);
}
}
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Installer.php | src/Composer/Installer.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer;
use Composer\Advisory\AuditConfig;
use Composer\Autoload\AutoloadGenerator;
use Composer\Console\GithubActionError;
use Composer\DependencyResolver\DefaultPolicy;
use Composer\DependencyResolver\LocalRepoTransaction;
use Composer\DependencyResolver\LockTransaction;
use Composer\DependencyResolver\Operation\UpdateOperation;
use Composer\DependencyResolver\Operation\InstallOperation;
use Composer\DependencyResolver\Operation\UninstallOperation;
use Composer\DependencyResolver\PoolOptimizer;
use Composer\DependencyResolver\Pool;
use Composer\DependencyResolver\Request;
use Composer\DependencyResolver\SecurityAdvisoryPoolFilter;
use Composer\DependencyResolver\Solver;
use Composer\DependencyResolver\SolverProblemsException;
use Composer\DependencyResolver\PolicyInterface;
use Composer\Downloader\DownloadManager;
use Composer\Downloader\TransportException;
use Composer\EventDispatcher\EventDispatcher;
use Composer\Filter\PlatformRequirementFilter\IgnoreListPlatformRequirementFilter;
use Composer\Filter\PlatformRequirementFilter\PlatformRequirementFilterFactory;
use Composer\Filter\PlatformRequirementFilter\PlatformRequirementFilterInterface;
use Composer\Installer\InstallationManager;
use Composer\Installer\InstallerEvents;
use Composer\Installer\SuggestedPackagesReporter;
use Composer\IO\IOInterface;
use Composer\Package\AliasPackage;
use Composer\Package\RootAliasPackage;
use Composer\Package\BasePackage;
use Composer\Package\CompletePackage;
use Composer\Package\CompletePackageInterface;
use Composer\Package\Link;
use Composer\Package\Loader\ArrayLoader;
use Composer\Package\Dumper\ArrayDumper;
use Composer\Package\Version\VersionParser;
use Composer\Package\Package;
use Composer\Repository\ArrayRepository;
use Composer\Repository\RepositorySet;
use Composer\Repository\CompositeRepository;
use Composer\Semver\Constraint\Constraint;
use Composer\Package\Locker;
use Composer\Package\RootPackageInterface;
use Composer\Repository\InstalledArrayRepository;
use Composer\Repository\InstalledRepositoryInterface;
use Composer\Repository\InstalledRepository;
use Composer\Repository\RootPackageRepository;
use Composer\Repository\PlatformRepository;
use Composer\Repository\RepositoryInterface;
use Composer\Repository\RepositoryManager;
use Composer\Repository\LockArrayRepository;
use Composer\Script\ScriptEvents;
use Composer\Semver\Constraint\ConstraintInterface;
use Composer\Advisory\Auditor;
use Composer\Util\Platform;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author Beau Simensen <beau@dflydev.com>
* @author Konstantin Kudryashov <ever.zet@gmail.com>
* @author Nils Adermann <naderman@naderman.de>
*/
class Installer
{
public const ERROR_NONE = 0; // no error/success state
public const ERROR_GENERIC_FAILURE = 1;
public const ERROR_NO_LOCK_FILE_FOR_PARTIAL_UPDATE = 3;
public const ERROR_LOCK_FILE_INVALID = 4;
// used/declared in SolverProblemsException, carried over here for completeness
public const ERROR_DEPENDENCY_RESOLUTION_FAILED = 2;
public const ERROR_AUDIT_FAILED = 5;
// technically exceptions are thrown with various status codes >400, but the process exit code is normalized to 100
public const ERROR_TRANSPORT_EXCEPTION = 100;
/**
* @var IOInterface
*/
protected $io;
/**
* @var Config
*/
protected $config;
/**
* @var RootPackageInterface&BasePackage
*/
protected $package;
// TODO can we get rid of the below and just use the package itself?
/**
* @var RootPackageInterface&BasePackage
*/
protected $fixedRootPackage;
/**
* @var DownloadManager
*/
protected $downloadManager;
/**
* @var RepositoryManager
*/
protected $repositoryManager;
/**
* @var Locker
*/
protected $locker;
/**
* @var InstallationManager
*/
protected $installationManager;
/**
* @var EventDispatcher
*/
protected $eventDispatcher;
/**
* @var AutoloadGenerator
*/
protected $autoloadGenerator;
/** @var bool */
protected $preferSource = false;
/** @var bool */
protected $preferDist = false;
/** @var bool */
protected $optimizeAutoloader = false;
/** @var bool */
protected $classMapAuthoritative = false;
/** @var bool */
protected $apcuAutoloader = false;
/** @var string|null */
protected $apcuAutoloaderPrefix = null;
/** @var bool */
protected $devMode = false;
/** @var bool */
protected $dryRun = false;
/** @var bool */
protected $downloadOnly = false;
/** @var bool */
protected $verbose = false;
/** @var bool */
protected $update = false;
/** @var bool */
protected $install = true;
/** @var bool */
protected $dumpAutoloader = true;
/** @var bool */
protected $runScripts = true;
/** @var bool */
protected $preferStable = false;
/** @var bool */
protected $preferLowest = false;
/** @var bool */
protected $minimalUpdate = false;
/** @var bool */
protected $writeLock;
/** @var bool */
protected $executeOperations = true;
/** @var bool */
protected $audit = true;
/** @var bool */
protected $errorOnAudit = false;
/** @var Auditor::FORMAT_* */
protected $auditFormat = Auditor::FORMAT_SUMMARY;
/** @var AuditConfig|null */
private $auditConfig = null;
/** @var list<string> */
private $ignoredTypes = ['php-ext', 'php-ext-zend'];
/** @var list<string>|null */
private $allowedTypes = null;
/** @var bool */
protected $updateMirrors = false;
/**
* Array of package names/globs flagged for update
*
* @var non-empty-list<string>|null
*/
protected $updateAllowList = null;
/** @var Request::UPDATE_* */
protected $updateAllowTransitiveDependencies = Request::UPDATE_ONLY_LISTED;
/**
* @var SuggestedPackagesReporter
*/
protected $suggestedPackagesReporter;
/**
* @var PlatformRequirementFilterInterface
*/
protected $platformRequirementFilter;
/**
* @var ?RepositoryInterface
*/
protected $additionalFixedRepository;
/** @var array<string, ConstraintInterface> */
protected $temporaryConstraints = [];
/**
* Constructor
*
* @param RootPackageInterface&BasePackage $package
*/
public function __construct(IOInterface $io, Config $config, RootPackageInterface $package, DownloadManager $downloadManager, RepositoryManager $repositoryManager, Locker $locker, InstallationManager $installationManager, EventDispatcher $eventDispatcher, AutoloadGenerator $autoloadGenerator)
{
$this->io = $io;
$this->config = $config;
$this->package = $package;
$this->downloadManager = $downloadManager;
$this->repositoryManager = $repositoryManager;
$this->locker = $locker;
$this->installationManager = $installationManager;
$this->eventDispatcher = $eventDispatcher;
$this->autoloadGenerator = $autoloadGenerator;
$this->suggestedPackagesReporter = new SuggestedPackagesReporter($this->io);
$this->platformRequirementFilter = PlatformRequirementFilterFactory::ignoreNothing();
$this->writeLock = $config->get('lock');
}
/**
* Run installation (or update)
*
* @throws \Exception
* @return int 0 on success or a positive error code on failure
* @phpstan-return self::ERROR_*
*/
public function run(): int
{
// Disable GC to save CPU cycles, as the dependency solver can create hundreds of thousands
// of PHP objects, the GC can spend quite some time walking the tree of references looking
// for stuff to collect while there is nothing to collect. This slows things down dramatically
// and turning it off results in much better performance. Do not try this at home however.
gc_collect_cycles();
gc_disable();
if ($this->updateAllowList !== null && $this->updateMirrors) {
throw new \RuntimeException("The installer options updateMirrors and updateAllowList are mutually exclusive.");
}
$isFreshInstall = $this->repositoryManager->getLocalRepository()->isFresh();
// Force update if there is no lock file present
if (!$this->update && !$this->locker->isLocked()) {
$this->io->writeError('<warning>No composer.lock file present. Updating dependencies to latest instead of installing from lock file. See https://getcomposer.org/install for more information.</warning>');
$this->update = true;
}
if ($this->dryRun) {
$this->verbose = true;
$this->runScripts = false;
$this->executeOperations = false;
$this->writeLock = false;
$this->dumpAutoloader = false;
$this->mockLocalRepositories($this->repositoryManager);
}
if ($this->downloadOnly) {
$this->dumpAutoloader = false;
}
if ($this->update && !$this->install) {
$this->dumpAutoloader = false;
}
if ($this->runScripts) {
Platform::putEnv('COMPOSER_DEV_MODE', $this->devMode ? '1' : '0');
// dispatch pre event
// should we treat this more strictly as running an update and then running an install, triggering events multiple times?
$eventName = $this->update ? ScriptEvents::PRE_UPDATE_CMD : ScriptEvents::PRE_INSTALL_CMD;
$this->eventDispatcher->dispatchScript($eventName, $this->devMode);
}
$this->downloadManager->setPreferSource($this->preferSource);
$this->downloadManager->setPreferDist($this->preferDist);
$localRepo = $this->repositoryManager->getLocalRepository();
try {
if ($this->update) {
$res = $this->doUpdate($localRepo, $this->install);
} else {
$res = $this->doInstall($localRepo);
}
if ($res !== 0) {
return $res;
}
} catch (\Exception $e) {
if ($this->executeOperations && $this->install && $this->config->get('notify-on-install')) {
$this->installationManager->notifyInstalls($this->io);
}
throw $e;
}
if ($this->executeOperations && $this->install && $this->config->get('notify-on-install')) {
$this->installationManager->notifyInstalls($this->io);
}
if ($this->update) {
$installedRepo = new InstalledRepository([
$this->locker->getLockedRepository($this->devMode),
$this->createPlatformRepo(false),
new RootPackageRepository(clone $this->package),
]);
if ($isFreshInstall) {
$this->suggestedPackagesReporter->addSuggestionsFromPackage($this->package);
}
$this->suggestedPackagesReporter->outputMinimalistic($installedRepo);
}
// Find abandoned packages and warn user
$lockedRepository = $this->locker->getLockedRepository(true);
foreach ($lockedRepository->getPackages() as $package) {
if (!$package instanceof CompletePackage || !$package->isAbandoned()) {
continue;
}
$replacement = is_string($package->getReplacementPackage())
? 'Use ' . $package->getReplacementPackage() . ' instead'
: 'No replacement was suggested';
$this->io->writeError(
sprintf(
"<warning>Package %s is abandoned, you should avoid using it. %s.</warning>",
$package->getPrettyName(),
$replacement
)
);
}
if ($this->dumpAutoloader) {
// write autoloader
if ($this->optimizeAutoloader) {
$this->io->writeError('<info>Generating optimized autoload files</info>');
} else {
$this->io->writeError('<info>Generating autoload files</info>');
}
$this->autoloadGenerator->setClassMapAuthoritative($this->classMapAuthoritative);
$this->autoloadGenerator->setApcu($this->apcuAutoloader, $this->apcuAutoloaderPrefix);
$this->autoloadGenerator->setRunScripts($this->runScripts);
$this->autoloadGenerator->setPlatformRequirementFilter($this->platformRequirementFilter);
$this
->autoloadGenerator
->dump(
$this->config,
$localRepo,
$this->package,
$this->installationManager,
'composer',
$this->optimizeAutoloader,
null,
$this->locker
);
}
if ($this->install && $this->executeOperations) {
// force binaries re-generation in case they are missing
foreach ($localRepo->getPackages() as $package) {
$this->installationManager->ensureBinariesPresence($package);
}
}
$fundEnv = Platform::getEnv('COMPOSER_FUND');
$showFunding = true;
if (is_numeric($fundEnv)) {
$showFunding = intval($fundEnv) !== 0;
}
if ($showFunding) {
$fundingCount = 0;
foreach ($localRepo->getPackages() as $package) {
if ($package instanceof CompletePackageInterface && !$package instanceof AliasPackage && $package->getFunding()) {
$fundingCount++;
}
}
if ($fundingCount > 0) {
$this->io->writeError([
sprintf(
"<info>%d package%s you are using %s looking for funding.</info>",
$fundingCount,
1 === $fundingCount ? '' : 's',
1 === $fundingCount ? 'is' : 'are'
),
'<info>Use the `composer fund` command to find out more!</info>',
]);
}
}
if ($this->runScripts) {
// dispatch post event
$eventName = $this->update ? ScriptEvents::POST_UPDATE_CMD : ScriptEvents::POST_INSTALL_CMD;
$this->eventDispatcher->dispatchScript($eventName, $this->devMode);
}
// re-enable GC except on HHVM which triggers a warning here
if (!defined('HHVM_VERSION')) {
gc_enable();
}
$auditConfig = $this->getAuditConfig();
if ($auditConfig->audit) {
if ($this->update && !$this->install) {
$packages = $lockedRepository->getCanonicalPackages();
$target = 'locked';
} else {
$packages = $localRepo->getCanonicalPackages();
$target = 'installed';
}
if (count($packages) > 0) {
try {
$auditor = new Auditor();
$repoSet = new RepositorySet();
foreach ($this->repositoryManager->getRepositories() as $repo) {
$repoSet->addRepository($repo);
}
return $auditor->audit($this->io, $repoSet, $packages, $auditConfig->auditFormat, true, $auditConfig->ignoreListForAudit, $auditConfig->auditAbandoned, $auditConfig->ignoreSeverityForAudit, $auditConfig->ignoreUnreachable, $auditConfig->ignoreAbandonedForAudit) > 0 && $this->errorOnAudit ? self::ERROR_AUDIT_FAILED : 0;
} catch (TransportException $e) {
$this->io->error('Failed to audit '.$target.' packages.');
if ($this->io->isVerbose()) {
$this->io->error('['.get_class($e).'] '.$e->getMessage());
}
}
} else {
$this->io->writeError('No '.$target.' packages - skipping audit.');
}
}
return 0;
}
/**
* @phpstan-return self::ERROR_*
*/
protected function doUpdate(InstalledRepositoryInterface $localRepo, bool $doInstall): int
{
$platformRepo = $this->createPlatformRepo(true);
$aliases = $this->getRootAliases(true);
$lockedRepository = null;
try {
if ($this->locker->isLocked()) {
$lockedRepository = $this->locker->getLockedRepository(true);
}
} catch (\Seld\JsonLint\ParsingException $e) {
if ($this->updateAllowList !== null || $this->updateMirrors) {
// in case we are doing a partial update or updating mirrors, the lock file is needed so we error
throw $e;
}
// otherwise, ignoring parse errors as the lock file will be regenerated from scratch when
// doing a full update
}
if (($this->updateAllowList !== null || $this->updateMirrors) && !$lockedRepository) {
$this->io->writeError('<error>Cannot update ' . ($this->updateMirrors ? 'lock file information' : 'only a partial set of packages') . ' without a lock file present. Run `composer update` to generate a lock file.</error>', true, IOInterface::QUIET);
return self::ERROR_NO_LOCK_FILE_FOR_PARTIAL_UPDATE;
}
$this->io->writeError('<info>Loading composer repositories with package information</info>');
// creating repository set
$policy = $this->createPolicy(true, $lockedRepository);
$repositorySet = $this->createRepositorySet(true, $platformRepo, $aliases);
$repositories = $this->repositoryManager->getRepositories();
foreach ($repositories as $repository) {
$repositorySet->addRepository($repository);
}
if ($lockedRepository) {
$repositorySet->addRepository($lockedRepository);
}
$request = $this->createRequest($this->fixedRootPackage, $platformRepo, $lockedRepository);
$this->requirePackagesForUpdate($request, $lockedRepository, true);
// pass the allow list into the request, so the pool builder can apply it
if ($this->updateAllowList !== null) {
$request->setUpdateAllowList($this->updateAllowList, $this->updateAllowTransitiveDependencies);
}
$pool = $repositorySet->createPool($request, $this->io, $this->eventDispatcher, $this->createPoolOptimizer($policy), $this->ignoredTypes, $this->allowedTypes, $this->createSecurityAuditPoolFilter());
$this->io->writeError('<info>Updating dependencies</info>');
// solve dependencies
$solver = new Solver($policy, $pool, $this->io);
try {
$lockTransaction = $solver->solve($request, $this->platformRequirementFilter);
$ruleSetSize = $solver->getRuleSetSize();
$solver = null;
} catch (SolverProblemsException $e) {
$err = 'Your requirements could not be resolved to an installable set of packages.';
$prettyProblem = $e->getPrettyString($repositorySet, $request, $pool, $this->io->isVerbose());
$this->io->writeError('<error>'. $err .'</error>', true, IOInterface::QUIET);
$this->io->writeError($prettyProblem);
if (!$this->devMode) {
$this->io->writeError('<warning>Running update with --no-dev does not mean require-dev is ignored, it just means the packages will not be installed. If dev requirements are blocking the update you have to resolve those problems.</warning>', true, IOInterface::QUIET);
}
$ghe = new GithubActionError($this->io);
$ghe->emit($err."\n".$prettyProblem);
return max(self::ERROR_GENERIC_FAILURE, $e->getCode());
}
$this->io->writeError("Analyzed ".count($pool)." packages to resolve dependencies", true, IOInterface::VERBOSE);
$this->io->writeError("Analyzed ".$ruleSetSize." rules to resolve dependencies", true, IOInterface::VERBOSE);
$pool = null;
if (!$lockTransaction->getOperations()) {
$this->io->writeError('Nothing to modify in lock file');
if ($this->minimalUpdate && $this->updateAllowList === null && $this->locker->isFresh()) {
$this->io->writeError('<warning>The --minimal-changes option should be used with package arguments or after modifying composer.json requirements, otherwise it will likely not yield any dependency changes.</warning>');
}
}
$exitCode = $this->extractDevPackages($lockTransaction, $platformRepo, $aliases, $policy, $lockedRepository);
if ($exitCode !== 0) {
return $exitCode;
}
Semver\CompilingMatcher::clear();
// write lock
$platformReqs = $this->extractPlatformRequirements($this->package->getRequires());
$platformDevReqs = $this->extractPlatformRequirements($this->package->getDevRequires());
$installsUpdates = $uninstalls = [];
if ($lockTransaction->getOperations()) {
$installNames = $updateNames = $uninstallNames = [];
foreach ($lockTransaction->getOperations() as $operation) {
if ($operation instanceof InstallOperation) {
$installsUpdates[] = $operation;
$installNames[] = $operation->getPackage()->getPrettyName().':'.$operation->getPackage()->getFullPrettyVersion();
} elseif ($operation instanceof UpdateOperation) {
// when mirrors/metadata from a package gets updated we do not want to list it as an
// update in the output as it is only an internal lock file metadata update
if ($this->updateMirrors
&& $operation->getInitialPackage()->getName() === $operation->getTargetPackage()->getName()
&& $operation->getInitialPackage()->getVersion() === $operation->getTargetPackage()->getVersion()
) {
continue;
}
$installsUpdates[] = $operation;
$updateNames[] = $operation->getTargetPackage()->getPrettyName().':'.$operation->getTargetPackage()->getFullPrettyVersion();
} elseif ($operation instanceof UninstallOperation) {
$uninstalls[] = $operation;
$uninstallNames[] = $operation->getPackage()->getPrettyName();
}
}
if ($this->config->get('lock')) {
$this->io->writeError(sprintf(
"<info>Lock file operations: %d install%s, %d update%s, %d removal%s</info>",
count($installNames),
1 === count($installNames) ? '' : 's',
count($updateNames),
1 === count($updateNames) ? '' : 's',
count($uninstalls),
1 === count($uninstalls) ? '' : 's'
));
if ($installNames) {
$this->io->writeError("Installs: ".implode(', ', $installNames), true, IOInterface::VERBOSE);
}
if ($updateNames) {
$this->io->writeError("Updates: ".implode(', ', $updateNames), true, IOInterface::VERBOSE);
}
if ($uninstalls) {
$this->io->writeError("Removals: ".implode(', ', $uninstallNames), true, IOInterface::VERBOSE);
}
}
}
$sortByName = static function ($a, $b): int {
if ($a instanceof UpdateOperation) {
$a = $a->getTargetPackage()->getName();
} else {
$a = $a->getPackage()->getName();
}
if ($b instanceof UpdateOperation) {
$b = $b->getTargetPackage()->getName();
} else {
$b = $b->getPackage()->getName();
}
return strcmp($a, $b);
};
usort($uninstalls, $sortByName);
usort($installsUpdates, $sortByName);
foreach (array_merge($uninstalls, $installsUpdates) as $operation) {
// collect suggestions
if ($operation instanceof InstallOperation) {
$this->suggestedPackagesReporter->addSuggestionsFromPackage($operation->getPackage());
}
// output op if lock file is enabled, but alias op only in debug verbosity
if ($this->config->get('lock') && (false === strpos($operation->getOperationType(), 'Alias') || $this->io->isDebug())) {
$sourceRepo = '';
if ($this->io->isVeryVerbose() && false === strpos($operation->getOperationType(), 'Alias')) {
$operationPkg = ($operation instanceof UpdateOperation ? $operation->getTargetPackage() : $operation->getPackage());
if ($operationPkg->getRepository() !== null) {
$sourceRepo = ' from ' . $operationPkg->getRepository()->getRepoName();
}
}
$this->io->writeError(' - ' . $operation->show(true) . $sourceRepo);
}
}
$updatedLock = $this->locker->setLockData(
$lockTransaction->getNewLockPackages(false, $this->updateMirrors),
$lockTransaction->getNewLockPackages(true, $this->updateMirrors),
$platformReqs,
$platformDevReqs,
$lockTransaction->getAliases($aliases),
$this->package->getMinimumStability(),
$this->package->getStabilityFlags(),
$this->preferStable || $this->package->getPreferStable(),
$this->preferLowest,
$this->config->get('platform') ?: [],
$this->writeLock && $this->executeOperations
);
if ($updatedLock && $this->writeLock && $this->executeOperations) {
$this->io->writeError('<info>Writing lock file</info>');
}
if ($doInstall) {
// TODO ensure lock is used from locker as-is, since it may not have been written to disk in case of executeOperations == false
return $this->doInstall($localRepo, true);
}
return 0;
}
/**
* Run the solver a second time on top of the existing update result with only the current result set in the pool
* and see what packages would get removed if we only had the non-dev packages in the solver request
*
* @param array<int, array<string, string>> $aliases
*
* @phpstan-param list<array{package: string, version: string, alias: string, alias_normalized: string}> $aliases
* @phpstan-return self::ERROR_*
*/
protected function extractDevPackages(LockTransaction $lockTransaction, PlatformRepository $platformRepo, array $aliases, PolicyInterface $policy, ?LockArrayRepository $lockedRepository = null): int
{
if (!$this->package->getDevRequires()) {
return 0;
}
$resultRepo = new ArrayRepository([]);
$loader = new ArrayLoader(null, true);
$dumper = new ArrayDumper();
foreach ($lockTransaction->getNewLockPackages(false) as $pkg) {
$resultRepo->addPackage($loader->load($dumper->dump($pkg)));
}
$repositorySet = $this->createRepositorySet(true, $platformRepo, $aliases);
$repositorySet->addRepository($resultRepo);
$request = $this->createRequest($this->fixedRootPackage, $platformRepo);
$this->requirePackagesForUpdate($request, $lockedRepository, false);
$pool = $repositorySet->createPoolWithAllPackages();
$solver = new Solver($policy, $pool, $this->io);
try {
$nonDevLockTransaction = $solver->solve($request, $this->platformRequirementFilter);
$solver = null;
} catch (SolverProblemsException $e) {
$err = 'Unable to find a compatible set of packages based on your non-dev requirements alone.';
$prettyProblem = $e->getPrettyString($repositorySet, $request, $pool, $this->io->isVerbose(), true);
$this->io->writeError('<error>'. $err .'</error>', true, IOInterface::QUIET);
$this->io->writeError('Your requirements can be resolved successfully when require-dev packages are present.');
$this->io->writeError('You may need to move packages from require-dev or some of their dependencies to require.');
$this->io->writeError($prettyProblem);
$ghe = new GithubActionError($this->io);
$ghe->emit($err."\n".$prettyProblem);
return $e->getCode();
}
$lockTransaction->setNonDevPackages($nonDevLockTransaction);
return 0;
}
/**
* @param bool $alreadySolved Whether the function is called as part of an update command or independently
* @return int exit code
* @phpstan-return self::ERROR_*
*/
protected function doInstall(InstalledRepositoryInterface $localRepo, bool $alreadySolved = false): int
{
if ($this->config->get('lock')) {
$this->io->writeError('<info>Installing dependencies from lock file'.($this->devMode ? ' (including require-dev)' : '').'</info>');
}
$lockedRepository = $this->locker->getLockedRepository($this->devMode);
// verify that the lock file works with the current platform repository
// we can skip this part if we're doing this as the second step after an update
if (!$alreadySolved) {
$this->io->writeError('<info>Verifying lock file contents can be installed on current platform.</info>');
$platformRepo = $this->createPlatformRepo(false);
// creating repository set
$policy = $this->createPolicy(false);
// use aliases from lock file only, so empty root aliases here
$repositorySet = $this->createRepositorySet(false, $platformRepo, [], $lockedRepository);
$repositorySet->addRepository($lockedRepository);
// creating requirements request
$request = $this->createRequest($this->fixedRootPackage, $platformRepo, $lockedRepository);
if (!$this->locker->isFresh()) {
$this->io->writeError('<warning>Warning: The lock file is not up to date with the latest changes in composer.json. You may be getting outdated dependencies. It is recommended that you run `composer update` or `composer update <package name>`.</warning>', true, IOInterface::QUIET);
}
$missingRequirementInfo = $this->locker->getMissingRequirementInfo($this->package, $this->devMode);
if ($missingRequirementInfo !== []) {
$this->io->writeError($missingRequirementInfo);
if (!$this->config->get('allow-missing-requirements')) {
return self::ERROR_LOCK_FILE_INVALID;
}
}
foreach ($lockedRepository->getPackages() as $package) {
$request->fixLockedPackage($package);
}
$rootRequires = $this->package->getRequires();
if ($this->devMode) {
$rootRequires = array_merge($rootRequires, $this->package->getDevRequires());
}
foreach ($rootRequires as $link) {
if (PlatformRepository::isPlatformPackage($link->getTarget())) {
$request->requireName($link->getTarget(), $link->getConstraint());
}
}
foreach ($this->locker->getPlatformRequirements($this->devMode) as $link) {
if (!isset($rootRequires[$link->getTarget()])) {
$request->requireName($link->getTarget(), $link->getConstraint());
}
}
unset($rootRequires, $link);
$pool = $repositorySet->createPool($request, $this->io, $this->eventDispatcher, null, $this->ignoredTypes, $this->allowedTypes, null);
// solve dependencies
$solver = new Solver($policy, $pool, $this->io);
try {
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | true |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/Decisions.php | src/Composer/DependencyResolver/Decisions.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver;
/**
* Stores decisions on installing, removing or keeping packages
*
* @author Nils Adermann <naderman@naderman.de>
* @implements \Iterator<array{0: int, 1: Rule}>
*/
class Decisions implements \Iterator, \Countable
{
public const DECISION_LITERAL = 0;
public const DECISION_REASON = 1;
/** @var Pool */
protected $pool;
/** @var array<int, int> */
protected $decisionMap;
/**
* @var array<int, array{0: int, 1: Rule}>
*/
protected $decisionQueue = [];
public function __construct(Pool $pool)
{
$this->pool = $pool;
$this->decisionMap = [];
}
public function decide(int $literal, int $level, Rule $why): void
{
$this->addDecision($literal, $level);
$this->decisionQueue[] = [
self::DECISION_LITERAL => $literal,
self::DECISION_REASON => $why,
];
}
public function satisfy(int $literal): bool
{
$packageId = abs($literal);
return (
$literal > 0 && isset($this->decisionMap[$packageId]) && $this->decisionMap[$packageId] > 0 ||
$literal < 0 && isset($this->decisionMap[$packageId]) && $this->decisionMap[$packageId] < 0
);
}
public function conflict(int $literal): bool
{
$packageId = abs($literal);
return (
(isset($this->decisionMap[$packageId]) && $this->decisionMap[$packageId] > 0 && $literal < 0) ||
(isset($this->decisionMap[$packageId]) && $this->decisionMap[$packageId] < 0 && $literal > 0)
);
}
public function decided(int $literalOrPackageId): bool
{
return ($this->decisionMap[abs($literalOrPackageId)] ?? 0) !== 0;
}
public function undecided(int $literalOrPackageId): bool
{
return ($this->decisionMap[abs($literalOrPackageId)] ?? 0) === 0;
}
public function decidedInstall(int $literalOrPackageId): bool
{
$packageId = abs($literalOrPackageId);
return isset($this->decisionMap[$packageId]) && $this->decisionMap[$packageId] > 0;
}
public function decisionLevel(int $literalOrPackageId): int
{
$packageId = abs($literalOrPackageId);
if (isset($this->decisionMap[$packageId])) {
return abs($this->decisionMap[$packageId]);
}
return 0;
}
public function decisionRule(int $literalOrPackageId): Rule
{
$packageId = abs($literalOrPackageId);
foreach ($this->decisionQueue as $decision) {
if ($packageId === abs($decision[self::DECISION_LITERAL])) {
return $decision[self::DECISION_REASON];
}
}
throw new \LogicException('Did not find a decision rule using '.$literalOrPackageId);
}
/**
* @return array{0: int, 1: Rule} a literal and decision reason
*/
public function atOffset(int $queueOffset): array
{
return $this->decisionQueue[$queueOffset];
}
public function validOffset(int $queueOffset): bool
{
return $queueOffset >= 0 && $queueOffset < \count($this->decisionQueue);
}
public function lastReason(): Rule
{
return $this->decisionQueue[\count($this->decisionQueue) - 1][self::DECISION_REASON];
}
public function lastLiteral(): int
{
return $this->decisionQueue[\count($this->decisionQueue) - 1][self::DECISION_LITERAL];
}
public function reset(): void
{
while ($decision = array_pop($this->decisionQueue)) {
$this->decisionMap[abs($decision[self::DECISION_LITERAL])] = 0;
}
}
/**
* @param int<-1, max> $offset
*/
public function resetToOffset(int $offset): void
{
while (\count($this->decisionQueue) > $offset + 1) {
$decision = array_pop($this->decisionQueue);
$this->decisionMap[abs($decision[self::DECISION_LITERAL])] = 0;
}
}
public function revertLast(): void
{
$this->decisionMap[abs($this->lastLiteral())] = 0;
array_pop($this->decisionQueue);
}
public function count(): int
{
return \count($this->decisionQueue);
}
public function rewind(): void
{
end($this->decisionQueue);
}
/**
* @return array{0: int, 1: Rule}|false
*/
#[\ReturnTypeWillChange]
public function current()
{
return current($this->decisionQueue);
}
public function key(): ?int
{
return key($this->decisionQueue);
}
public function next(): void
{
prev($this->decisionQueue);
}
public function valid(): bool
{
return false !== current($this->decisionQueue);
}
public function isEmpty(): bool
{
return \count($this->decisionQueue) === 0;
}
protected function addDecision(int $literal, int $level): void
{
$packageId = abs($literal);
$previousDecision = $this->decisionMap[$packageId] ?? 0;
if ($previousDecision !== 0) {
$literalString = $this->pool->literalToPrettyString($literal, []);
$package = $this->pool->literalToPackage($literal);
throw new SolverBugException(
"Trying to decide $literalString on level $level, even though $package was previously decided as ".$previousDecision."."
);
}
if ($literal > 0) {
$this->decisionMap[$packageId] = $level;
} else {
$this->decisionMap[$packageId] = -$level;
}
}
public function toString(?Pool $pool = null): string
{
$decisionMap = $this->decisionMap;
ksort($decisionMap);
$str = '[';
foreach ($decisionMap as $packageId => $level) {
$str .= ($pool !== null ? $pool->literalToPackage($packageId) : $packageId).':'.$level.',';
}
$str .= ']';
return $str;
}
public function __toString(): string
{
return $this->toString();
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/Transaction.php | src/Composer/DependencyResolver/Transaction.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver;
use Composer\Package\AliasPackage;
use Composer\Package\CompletePackageInterface;
use Composer\Package\Link;
use Composer\Package\PackageInterface;
use Composer\Repository\PlatformRepository;
use Composer\DependencyResolver\Operation\OperationInterface;
/**
* @author Nils Adermann <naderman@naderman.de>
* @internal
*/
class Transaction
{
/**
* @var OperationInterface[]
*/
protected $operations;
/**
* Packages present at the beginning of the transaction
* @var PackageInterface[]
*/
protected $presentPackages;
/**
* Package set resulting from this transaction
* @var array<string, PackageInterface>
*/
protected $resultPackageMap;
/**
* @var array<string, PackageInterface[]>
*/
protected $resultPackagesByName = [];
/**
* @param PackageInterface[] $presentPackages
* @param PackageInterface[] $resultPackages
*/
public function __construct(array $presentPackages, array $resultPackages)
{
$this->presentPackages = $presentPackages;
$this->setResultPackageMaps($resultPackages);
$this->operations = $this->calculateOperations();
}
/**
* @return OperationInterface[]
*/
public function getOperations(): array
{
return $this->operations;
}
/**
* @param PackageInterface[] $resultPackages
*/
private function setResultPackageMaps(array $resultPackages): void
{
$packageSort = static function (PackageInterface $a, PackageInterface $b): int {
// sort alias packages by the same name behind their non alias version
if ($a->getName() === $b->getName()) {
if ($a instanceof AliasPackage !== $b instanceof AliasPackage) {
return $a instanceof AliasPackage ? -1 : 1;
}
// if names are the same, compare version, e.g. to sort aliases reliably, actual order does not matter
return strcmp($b->getVersion(), $a->getVersion());
}
return strcmp($b->getName(), $a->getName());
};
$this->resultPackageMap = [];
foreach ($resultPackages as $package) {
$this->resultPackageMap[spl_object_hash($package)] = $package;
foreach ($package->getNames() as $name) {
$this->resultPackagesByName[$name][] = $package;
}
}
uasort($this->resultPackageMap, $packageSort);
foreach ($this->resultPackagesByName as $name => $packages) {
uasort($this->resultPackagesByName[$name], $packageSort);
}
}
/**
* @return OperationInterface[]
*/
protected function calculateOperations(): array
{
$operations = [];
$presentPackageMap = [];
$removeMap = [];
$presentAliasMap = [];
$removeAliasMap = [];
foreach ($this->presentPackages as $package) {
if ($package instanceof AliasPackage) {
$presentAliasMap[$package->getName().'::'.$package->getVersion()] = $package;
$removeAliasMap[$package->getName().'::'.$package->getVersion()] = $package;
} else {
$presentPackageMap[$package->getName()] = $package;
$removeMap[$package->getName()] = $package;
}
}
$stack = $this->getRootPackages();
$visited = [];
$processed = [];
while (\count($stack) > 0) {
$package = array_pop($stack);
if (isset($processed[spl_object_hash($package)])) {
continue;
}
if (!isset($visited[spl_object_hash($package)])) {
$visited[spl_object_hash($package)] = true;
$stack[] = $package;
if ($package instanceof AliasPackage) {
$stack[] = $package->getAliasOf();
} else {
foreach ($package->getRequires() as $link) {
$possibleRequires = $this->getProvidersInResult($link);
foreach ($possibleRequires as $require) {
$stack[] = $require;
}
}
}
} elseif (!isset($processed[spl_object_hash($package)])) {
$processed[spl_object_hash($package)] = true;
if ($package instanceof AliasPackage) {
$aliasKey = $package->getName().'::'.$package->getVersion();
if (isset($presentAliasMap[$aliasKey])) {
unset($removeAliasMap[$aliasKey]);
} else {
$operations[] = new Operation\MarkAliasInstalledOperation($package);
}
} else {
if (isset($presentPackageMap[$package->getName()])) {
$source = $presentPackageMap[$package->getName()];
// do we need to update?
// TODO different for lock?
if ($package->getVersion() !== $presentPackageMap[$package->getName()]->getVersion() ||
$package->getDistReference() !== $presentPackageMap[$package->getName()]->getDistReference() ||
$package->getSourceReference() !== $presentPackageMap[$package->getName()]->getSourceReference() ||
(
$package instanceof CompletePackageInterface
&& $presentPackageMap[$package->getName()] instanceof CompletePackageInterface
&& (
$package->isAbandoned() !== $presentPackageMap[$package->getName()]->isAbandoned()
|| $package->getReplacementPackage() !== $presentPackageMap[$package->getName()]->getReplacementPackage()
)
)
) {
$operations[] = new Operation\UpdateOperation($source, $package);
}
unset($removeMap[$package->getName()]);
} else {
$operations[] = new Operation\InstallOperation($package);
unset($removeMap[$package->getName()]);
}
}
}
}
foreach ($removeMap as $name => $package) {
array_unshift($operations, new Operation\UninstallOperation($package));
}
foreach ($removeAliasMap as $nameVersion => $package) {
$operations[] = new Operation\MarkAliasUninstalledOperation($package);
}
$operations = $this->movePluginsToFront($operations);
// TODO fix this:
// we have to do this again here even though the above stack code did it because moving plugins moves them before uninstalls
$operations = $this->moveUninstallsToFront($operations);
// TODO skip updates which don't update? is this needed? we shouldn't schedule this update in the first place?
/*
if ('update' === $opType) {
$targetPackage = $operation->getTargetPackage();
if ($targetPackage->isDev()) {
$initialPackage = $operation->getInitialPackage();
if ($targetPackage->getVersion() === $initialPackage->getVersion()
&& (!$targetPackage->getSourceReference() || $targetPackage->getSourceReference() === $initialPackage->getSourceReference())
&& (!$targetPackage->getDistReference() || $targetPackage->getDistReference() === $initialPackage->getDistReference())
) {
$this->io->writeError(' - Skipping update of ' . $targetPackage->getPrettyName() . ' to the same reference-locked version', true, IOInterface::DEBUG);
$this->io->writeError('', true, IOInterface::DEBUG);
continue;
}
}
}*/
return $this->operations = $operations;
}
/**
* Determine which packages in the result are not required by any other packages in it.
*
* These serve as a starting point to enumerate packages in a topological order despite potential cycles.
* If there are packages with a cycle on the top level the package with the lowest name gets picked
*
* @return array<string, PackageInterface>
*/
protected function getRootPackages(): array
{
$roots = $this->resultPackageMap;
foreach ($this->resultPackageMap as $packageHash => $package) {
if (!isset($roots[$packageHash])) {
continue;
}
foreach ($package->getRequires() as $link) {
$possibleRequires = $this->getProvidersInResult($link);
foreach ($possibleRequires as $require) {
if ($require !== $package) {
unset($roots[spl_object_hash($require)]);
}
}
}
}
return $roots;
}
/**
* @return PackageInterface[]
*/
protected function getProvidersInResult(Link $link): array
{
if (!isset($this->resultPackagesByName[$link->getTarget()])) {
return [];
}
return $this->resultPackagesByName[$link->getTarget()];
}
/**
* Workaround: if your packages depend on plugins, we must be sure
* that those are installed / updated first; else it would lead to packages
* being installed multiple times in different folders, when running Composer
* twice.
*
* While this does not fix the root-causes of https://github.com/composer/composer/issues/1147,
* it at least fixes the symptoms and makes usage of composer possible (again)
* in such scenarios.
*
* @param OperationInterface[] $operations
* @return OperationInterface[] reordered operation list
*/
private function movePluginsToFront(array $operations): array
{
$dlModifyingPluginsNoDeps = [];
$dlModifyingPluginsWithDeps = [];
$dlModifyingPluginRequires = [];
$pluginsNoDeps = [];
$pluginsWithDeps = [];
$pluginRequires = [];
foreach (array_reverse($operations, true) as $idx => $op) {
if ($op instanceof Operation\InstallOperation) {
$package = $op->getPackage();
} elseif ($op instanceof Operation\UpdateOperation) {
$package = $op->getTargetPackage();
} else {
continue;
}
$extra = $package->getExtra();
$isDownloadsModifyingPlugin = $package->getType() === 'composer-plugin' && isset($extra['plugin-modifies-downloads']) && $extra['plugin-modifies-downloads'] === true;
// is this a downloads modifying plugin or a dependency of one?
if ($isDownloadsModifyingPlugin || \count(array_intersect($package->getNames(), $dlModifyingPluginRequires)) > 0) {
// get the package's requires, but filter out any platform requirements
$requires = array_filter(array_keys($package->getRequires()), static function ($req): bool {
return !PlatformRepository::isPlatformPackage($req);
});
// is this a plugin with no meaningful dependencies?
if ($isDownloadsModifyingPlugin && 0 === \count($requires)) {
// plugins with no dependencies go to the very front
array_unshift($dlModifyingPluginsNoDeps, $op);
} else {
// capture the requirements for this package so those packages will be moved up as well
$dlModifyingPluginRequires = array_merge($dlModifyingPluginRequires, $requires);
// move the operation to the front
array_unshift($dlModifyingPluginsWithDeps, $op);
}
unset($operations[$idx]);
continue;
}
// is this package a plugin?
$isPlugin = $package->getType() === 'composer-plugin' || $package->getType() === 'composer-installer';
// is this a plugin or a dependency of a plugin?
if ($isPlugin || \count(array_intersect($package->getNames(), $pluginRequires)) > 0) {
// get the package's requires, but filter out any platform requirements
$requires = array_filter(array_keys($package->getRequires()), static function ($req): bool {
return !PlatformRepository::isPlatformPackage($req);
});
// is this a plugin with no meaningful dependencies?
if ($isPlugin && 0 === \count($requires)) {
// plugins with no dependencies go to the very front
array_unshift($pluginsNoDeps, $op);
} else {
// capture the requirements for this package so those packages will be moved up as well
$pluginRequires = array_merge($pluginRequires, $requires);
// move the operation to the front
array_unshift($pluginsWithDeps, $op);
}
unset($operations[$idx]);
}
}
return array_merge($dlModifyingPluginsNoDeps, $dlModifyingPluginsWithDeps, $pluginsNoDeps, $pluginsWithDeps, $operations);
}
/**
* Removals of packages should be executed before installations in
* case two packages resolve to the same path (due to custom installers)
*
* @param OperationInterface[] $operations
* @return OperationInterface[] reordered operation list
*/
private function moveUninstallsToFront(array $operations): array
{
$uninstOps = [];
foreach ($operations as $idx => $op) {
if ($op instanceof Operation\UninstallOperation || $op instanceof Operation\MarkAliasUninstalledOperation) {
$uninstOps[] = $op;
unset($operations[$idx]);
}
}
return array_merge($uninstOps, $operations);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/GenericRule.php | src/Composer/DependencyResolver/GenericRule.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver;
/**
* @author Nils Adermann <naderman@naderman.de>
*/
class GenericRule extends Rule
{
/** @var list<int> */
protected $literals;
/**
* @param list<int> $literals
*/
public function __construct(array $literals, $reason, $reasonData)
{
parent::__construct($reason, $reasonData);
// sort all packages ascending by id
sort($literals);
$this->literals = $literals;
}
/**
* @return list<int>
*/
public function getLiterals(): array
{
return $this->literals;
}
/**
* @inheritDoc
*/
public function getHash()
{
$data = unpack('ihash', (string) hash(\PHP_VERSION_ID > 80100 ? 'xxh3' : 'sha1', implode(',', $this->literals), true));
if (false === $data) {
throw new \RuntimeException('Failed unpacking: '.implode(', ', $this->literals));
}
return $data['hash'];
}
/**
* Checks if this rule is equal to another one
*
* Ignores whether either of the rules is disabled.
*
* @param Rule $rule The rule to check against
* @return bool Whether the rules are equal
*/
public function equals(Rule $rule): bool
{
return $this->literals === $rule->getLiterals();
}
public function isAssertion(): bool
{
return 1 === \count($this->literals);
}
/**
* Formats a rule as a string of the format (Literal1|Literal2|...)
*/
public function __toString(): string
{
$result = $this->isDisabled() ? 'disabled(' : '(';
foreach ($this->literals as $i => $literal) {
if ($i !== 0) {
$result .= '|';
}
$result .= $literal;
}
$result .= ')';
return $result;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/PoolOptimizer.php | src/Composer/DependencyResolver/PoolOptimizer.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver;
use Composer\Package\AliasPackage;
use Composer\Package\BasePackage;
use Composer\Package\Version\VersionParser;
use Composer\Semver\CompilingMatcher;
use Composer\Semver\Constraint\ConstraintInterface;
use Composer\Semver\Constraint\Constraint;
use Composer\Semver\Constraint\MultiConstraint;
use Composer\Semver\Intervals;
/**
* Optimizes a given pool
*
* @author Yanick Witschi <yanick.witschi@terminal42.ch>
*/
class PoolOptimizer
{
/**
* @var PolicyInterface
*/
private $policy;
/**
* @var array<int, true>
*/
private $irremovablePackages = [];
/**
* @var array<string, array<string, ConstraintInterface>>
*/
private $requireConstraintsPerPackage = [];
/**
* @var array<string, array<string, ConstraintInterface>>
*/
private $conflictConstraintsPerPackage = [];
/**
* @var array<int, true>
*/
private $packagesToRemove = [];
/**
* @var array<int, BasePackage[]>
*/
private $aliasesPerPackage = [];
/**
* @var array<string, array<string, string>>
*/
private $removedVersionsByPackage = [];
public function __construct(PolicyInterface $policy)
{
$this->policy = $policy;
}
public function optimize(Request $request, Pool $pool): Pool
{
$this->prepare($request, $pool);
$this->optimizeByIdenticalDependencies($request, $pool);
$this->optimizeImpossiblePackagesAway($request, $pool);
$optimizedPool = $this->applyRemovalsToPool($pool);
// No need to run this recursively at the moment
// because the current optimizations cannot provide
// even more gains when ran again. Might change
// in the future with additional optimizations.
$this->irremovablePackages = [];
$this->requireConstraintsPerPackage = [];
$this->conflictConstraintsPerPackage = [];
$this->packagesToRemove = [];
$this->aliasesPerPackage = [];
$this->removedVersionsByPackage = [];
return $optimizedPool;
}
private function prepare(Request $request, Pool $pool): void
{
$irremovablePackageConstraintGroups = [];
// Mark fixed or locked packages as irremovable
foreach ($request->getFixedOrLockedPackages() as $package) {
$irremovablePackageConstraintGroups[$package->getName()][] = new Constraint('==', $package->getVersion());
}
// Extract requested package requirements
foreach ($request->getRequires() as $require => $constraint) {
$this->extractRequireConstraintsPerPackage($require, $constraint);
}
// First pass over all packages to extract information and mark package constraints irremovable
foreach ($pool->getPackages() as $package) {
// Extract package requirements
foreach ($package->getRequires() as $link) {
$this->extractRequireConstraintsPerPackage($link->getTarget(), $link->getConstraint());
}
// Extract package conflicts
foreach ($package->getConflicts() as $link) {
$this->extractConflictConstraintsPerPackage($link->getTarget(), $link->getConstraint());
}
// Keep track of alias packages for every package so if either the alias or aliased is kept
// we keep the others as they are a unit of packages really
if ($package instanceof AliasPackage) {
$this->aliasesPerPackage[$package->getAliasOf()->id][] = $package;
}
}
$irremovablePackageConstraints = [];
foreach ($irremovablePackageConstraintGroups as $packageName => $constraints) {
$irremovablePackageConstraints[$packageName] = 1 === \count($constraints) ? $constraints[0] : new MultiConstraint($constraints, false);
}
unset($irremovablePackageConstraintGroups);
// Mark the packages as irremovable based on the constraints
foreach ($pool->getPackages() as $package) {
if (!isset($irremovablePackageConstraints[$package->getName()])) {
continue;
}
if (CompilingMatcher::match($irremovablePackageConstraints[$package->getName()], Constraint::OP_EQ, $package->getVersion())) {
$this->markPackageIrremovable($package);
}
}
}
private function markPackageIrremovable(BasePackage $package): void
{
$this->irremovablePackages[$package->id] = true;
if ($package instanceof AliasPackage) {
// recursing here so aliasesPerPackage for the aliasOf can be checked
// and all its aliases marked as irremovable as well
$this->markPackageIrremovable($package->getAliasOf());
}
if (isset($this->aliasesPerPackage[$package->id])) {
foreach ($this->aliasesPerPackage[$package->id] as $aliasPackage) {
$this->irremovablePackages[$aliasPackage->id] = true;
}
}
}
/**
* @return Pool Optimized pool
*/
private function applyRemovalsToPool(Pool $pool): Pool
{
$packages = [];
$removedVersions = [];
foreach ($pool->getPackages() as $package) {
if (!isset($this->packagesToRemove[$package->id])) {
$packages[] = $package;
} else {
$removedVersions[$package->getName()][$package->getVersion()] = $package->getPrettyVersion();
}
}
$optimizedPool = new Pool($packages, $pool->getUnacceptableFixedOrLockedPackages(), $removedVersions, $this->removedVersionsByPackage, $pool->getAllSecurityRemovedPackageVersions(), $pool->getAllAbandonedRemovedPackageVersions());
return $optimizedPool;
}
private function optimizeByIdenticalDependencies(Request $request, Pool $pool): void
{
$identicalDefinitionsPerPackage = [];
$packageIdenticalDefinitionLookup = [];
foreach ($pool->getPackages() as $package) {
// If that package was already marked irremovable, we can skip
// the entire process for it
if (isset($this->irremovablePackages[$package->id])) {
continue;
}
$this->markPackageForRemoval($package->id);
$dependencyHash = $this->calculateDependencyHash($package);
foreach ($package->getNames(false) as $packageName) {
if (!isset($this->requireConstraintsPerPackage[$packageName])) {
continue;
}
foreach ($this->requireConstraintsPerPackage[$packageName] as $requireConstraint) {
$groupHashParts = [];
if (CompilingMatcher::match($requireConstraint, Constraint::OP_EQ, $package->getVersion())) {
$groupHashParts[] = 'require:' . (string) $requireConstraint;
}
if (\count($package->getReplaces()) > 0) {
foreach ($package->getReplaces() as $link) {
if (CompilingMatcher::match($link->getConstraint(), Constraint::OP_EQ, $package->getVersion())) {
// Use the same hash part as the regular require hash because that's what the replacement does
$groupHashParts[] = 'require:' . (string) $link->getConstraint();
}
}
}
if (isset($this->conflictConstraintsPerPackage[$packageName])) {
foreach ($this->conflictConstraintsPerPackage[$packageName] as $conflictConstraint) {
if (CompilingMatcher::match($conflictConstraint, Constraint::OP_EQ, $package->getVersion())) {
$groupHashParts[] = 'conflict:' . (string) $conflictConstraint;
}
}
}
if (0 === \count($groupHashParts)) {
continue;
}
$groupHash = implode('', $groupHashParts);
$identicalDefinitionsPerPackage[$packageName][$groupHash][$dependencyHash][] = $package;
$packageIdenticalDefinitionLookup[$package->id][$packageName] = ['groupHash' => $groupHash, 'dependencyHash' => $dependencyHash];
}
}
}
foreach ($identicalDefinitionsPerPackage as $constraintGroups) {
foreach ($constraintGroups as $constraintGroup) {
foreach ($constraintGroup as $packages) {
// Only one package in this constraint group has the same requirements, we're not allowed to remove that package
if (1 === \count($packages)) {
$this->keepPackage($packages[0], $identicalDefinitionsPerPackage, $packageIdenticalDefinitionLookup);
continue;
}
// Otherwise we find out which one is the preferred package in this constraint group which is
// then not allowed to be removed either
$literals = [];
foreach ($packages as $package) {
$literals[] = $package->id;
}
foreach ($this->policy->selectPreferredPackages($pool, $literals) as $preferredLiteral) {
$this->keepPackage($pool->literalToPackage($preferredLiteral), $identicalDefinitionsPerPackage, $packageIdenticalDefinitionLookup);
}
}
}
}
}
private function calculateDependencyHash(BasePackage $package): string
{
$hash = '';
$hashRelevantLinks = [
'requires' => $package->getRequires(),
'conflicts' => $package->getConflicts(),
'replaces' => $package->getReplaces(),
'provides' => $package->getProvides(),
];
foreach ($hashRelevantLinks as $key => $links) {
if (0 === \count($links)) {
continue;
}
// start new hash section
$hash .= $key . ':';
$subhash = [];
foreach ($links as $link) {
// To get the best dependency hash matches we should use Intervals::compactConstraint() here.
// However, the majority of projects are going to specify their constraints already pretty
// much in the best variant possible. In other words, we'd be wasting time here and it would actually hurt
// performance more than the additional few packages that could be filtered out would benefit the process.
$subhash[$link->getTarget()] = (string) $link->getConstraint();
}
// Sort for best result
ksort($subhash);
foreach ($subhash as $target => $constraint) {
$hash .= $target . '@' . $constraint;
}
}
return $hash;
}
private function markPackageForRemoval(int $id): void
{
// We are not allowed to remove packages if they have been marked as irremovable
if (isset($this->irremovablePackages[$id])) {
throw new \LogicException('Attempted removing a package which was previously marked irremovable');
}
$this->packagesToRemove[$id] = true;
}
/**
* @param array<string, array<string, array<string, list<BasePackage>>>> $identicalDefinitionsPerPackage
* @param array<int, array<string, array{groupHash: string, dependencyHash: string}>> $packageIdenticalDefinitionLookup
*/
private function keepPackage(BasePackage $package, array $identicalDefinitionsPerPackage, array $packageIdenticalDefinitionLookup): void
{
// Already marked to keep
if (!isset($this->packagesToRemove[$package->id])) {
return;
}
unset($this->packagesToRemove[$package->id]);
if ($package instanceof AliasPackage) {
// recursing here so aliasesPerPackage for the aliasOf can be checked
// and all its aliases marked to be kept as well
$this->keepPackage($package->getAliasOf(), $identicalDefinitionsPerPackage, $packageIdenticalDefinitionLookup);
}
// record all the versions of the package group so we can list them later in Problem output
foreach ($package->getNames(false) as $name) {
if (isset($packageIdenticalDefinitionLookup[$package->id][$name])) {
$packageGroupPointers = $packageIdenticalDefinitionLookup[$package->id][$name];
$packageGroup = $identicalDefinitionsPerPackage[$name][$packageGroupPointers['groupHash']][$packageGroupPointers['dependencyHash']];
foreach ($packageGroup as $pkg) {
if ($pkg instanceof AliasPackage && $pkg->getPrettyVersion() === VersionParser::DEFAULT_BRANCH_ALIAS) {
$pkg = $pkg->getAliasOf();
}
$this->removedVersionsByPackage[spl_object_hash($package)][$pkg->getVersion()] = $pkg->getPrettyVersion();
}
}
}
if (isset($this->aliasesPerPackage[$package->id])) {
foreach ($this->aliasesPerPackage[$package->id] as $aliasPackage) {
unset($this->packagesToRemove[$aliasPackage->id]);
// record all the versions of the package group so we can list them later in Problem output
foreach ($aliasPackage->getNames(false) as $name) {
if (isset($packageIdenticalDefinitionLookup[$aliasPackage->id][$name])) {
$packageGroupPointers = $packageIdenticalDefinitionLookup[$aliasPackage->id][$name];
$packageGroup = $identicalDefinitionsPerPackage[$name][$packageGroupPointers['groupHash']][$packageGroupPointers['dependencyHash']];
foreach ($packageGroup as $pkg) {
if ($pkg instanceof AliasPackage && $pkg->getPrettyVersion() === VersionParser::DEFAULT_BRANCH_ALIAS) {
$pkg = $pkg->getAliasOf();
}
$this->removedVersionsByPackage[spl_object_hash($aliasPackage)][$pkg->getVersion()] = $pkg->getPrettyVersion();
}
}
}
}
}
}
/**
* Use the list of locked packages to constrain the loaded packages
* This will reduce packages with significant numbers of historical versions to a smaller number
* and reduce the resulting rule set that is generated
*/
private function optimizeImpossiblePackagesAway(Request $request, Pool $pool): void
{
if (\count($request->getLockedPackages()) === 0) {
return;
}
$packageIndex = [];
foreach ($pool->getPackages() as $package) {
$id = $package->id;
// Do not remove irremovable packages
if (isset($this->irremovablePackages[$id])) {
continue;
}
// Do not remove a package aliased by another package, nor aliases
if (isset($this->aliasesPerPackage[$id]) || $package instanceof AliasPackage) {
continue;
}
// Do not remove locked packages
if ($request->isFixedPackage($package) || $request->isLockedPackage($package)) {
continue;
}
$packageIndex[$package->getName()][$package->id] = $package;
}
foreach ($request->getLockedPackages() as $package) {
// If this locked package is no longer required by root or anything in the pool, it may get uninstalled so do not apply its requirements
// In a case where a requirement WERE to appear in the pool by a package that would not be used, it would've been unlocked and so not filtered still
$isUnusedPackage = true;
foreach ($package->getNames(false) as $packageName) {
if (isset($this->requireConstraintsPerPackage[$packageName])) {
$isUnusedPackage = false;
break;
}
}
if ($isUnusedPackage) {
continue;
}
foreach ($package->getRequires() as $link) {
$require = $link->getTarget();
if (!isset($packageIndex[$require])) {
continue;
}
$linkConstraint = $link->getConstraint();
foreach ($packageIndex[$require] as $id => $requiredPkg) {
if (false === CompilingMatcher::match($linkConstraint, Constraint::OP_EQ, $requiredPkg->getVersion())) {
$this->markPackageForRemoval($id);
unset($packageIndex[$require][$id]);
}
}
}
}
}
/**
* Disjunctive require constraints need to be considered in their own group. E.g. "^2.14 || ^3.3" needs to generate
* two require constraint groups in order for us to keep the best matching package for "^2.14" AND "^3.3" as otherwise, we'd
* only keep either one which can cause trouble (e.g. when using --prefer-lowest).
*
* @return void
*/
private function extractRequireConstraintsPerPackage(string $package, ConstraintInterface $constraint)
{
foreach ($this->expandDisjunctiveMultiConstraints($constraint) as $expanded) {
$this->requireConstraintsPerPackage[$package][(string) $expanded] = $expanded;
}
}
/**
* Disjunctive conflict constraints need to be considered in their own group. E.g. "^2.14 || ^3.3" needs to generate
* two conflict constraint groups in order for us to keep the best matching package for "^2.14" AND "^3.3" as otherwise, we'd
* only keep either one which can cause trouble (e.g. when using --prefer-lowest).
*
* @return void
*/
private function extractConflictConstraintsPerPackage(string $package, ConstraintInterface $constraint)
{
foreach ($this->expandDisjunctiveMultiConstraints($constraint) as $expanded) {
$this->conflictConstraintsPerPackage[$package][(string) $expanded] = $expanded;
}
}
/**
* @return ConstraintInterface[]
*/
private function expandDisjunctiveMultiConstraints(ConstraintInterface $constraint)
{
$constraint = Intervals::compactConstraint($constraint);
if ($constraint instanceof MultiConstraint && $constraint->isDisjunctive()) {
// No need to call ourselves recursively here because Intervals::compactConstraint() ensures that there
// are no nested disjunctive MultiConstraint instances possible
return $constraint->getConstraints();
}
// Regular constraints and conjunctive MultiConstraints
return [$constraint];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/PoolBuilder.php | src/Composer/DependencyResolver/PoolBuilder.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver;
use Composer\EventDispatcher\EventDispatcher;
use Composer\IO\IOInterface;
use Composer\Package\AliasPackage;
use Composer\Package\BasePackage;
use Composer\Package\CompleteAliasPackage;
use Composer\Package\CompletePackage;
use Composer\Package\PackageInterface;
use Composer\Package\Version\StabilityFilter;
use Composer\Pcre\Preg;
use Composer\Plugin\PluginEvents;
use Composer\Plugin\PrePoolCreateEvent;
use Composer\Repository\PlatformRepository;
use Composer\Repository\RepositoryInterface;
use Composer\Repository\RootPackageRepository;
use Composer\Semver\CompilingMatcher;
use Composer\Semver\Constraint\Constraint;
use Composer\Semver\Constraint\ConstraintInterface;
use Composer\Semver\Constraint\MatchAllConstraint;
use Composer\Semver\Constraint\MultiConstraint;
use Composer\Semver\Intervals;
/**
* @author Nils Adermann <naderman@naderman.de>
*/
class PoolBuilder
{
private const LOAD_BATCH_SIZE = 50;
/**
* @var int[]
* @phpstan-var array<key-of<BasePackage::STABILITIES>, BasePackage::STABILITY_*>
*/
private $acceptableStabilities;
/**
* @var int[]
* @phpstan-var array<string, BasePackage::STABILITY_*>
*/
private $stabilityFlags;
/**
* @var array[]
* @phpstan-var array<string, array<string, array{alias: string, alias_normalized: string}>>
*/
private $rootAliases;
/**
* @var string[]
* @phpstan-var array<string, string>
*/
private $rootReferences;
/**
* @var array<string, ConstraintInterface>
*/
private $temporaryConstraints;
/**
* @var ?EventDispatcher
*/
private $eventDispatcher;
/**
* @var PoolOptimizer|null
*/
private $poolOptimizer;
/**
* @var IOInterface
*/
private $io;
/**
* @var array[]
* @phpstan-var array<string, AliasPackage[]>
*/
private $aliasMap = [];
/**
* @var ConstraintInterface[]
* @phpstan-var array<string, ConstraintInterface>
*/
private $packagesToLoad = [];
/**
* @var ConstraintInterface[]
* @phpstan-var array<string, ConstraintInterface>
*/
private $loadedPackages = [];
/**
* @var array[]
* @phpstan-var array<int, array<string, array<string, PackageInterface>>>
*/
private $loadedPerRepo = [];
/**
* @var array<int, BasePackage>
*/
private $packages = [];
/**
* @var BasePackage[]
*/
private $unacceptableFixedOrLockedPackages = [];
/** @var array<string> */
private $updateAllowList = [];
/** @var array<string, array<PackageInterface>> */
private $skippedLoad = [];
/** @var list<string> */
private $ignoredTypes = [];
/** @var list<string>|null */
private $allowedTypes = null;
/**
* If provided, only these package names are loaded
*
* This is a special-use functionality of the Request class to optimize the pool creation process
* when only a minimal subset of packages is needed and we do not need their dependencies.
*
* @var array<string, int>|null
*/
private $restrictedPackagesList = null;
/**
* Keeps a list of dependencies which are locked but were auto-unlocked as they are path repositories
*
* This half-unlocked state means the package itself will update but the UPDATE_LISTED_WITH_TRANSITIVE_DEPS*
* flags will not apply until the package really gets unlocked in some other way than being a path repo
*
* @var array<string, true>
*/
private $pathRepoUnlocked = [];
/**
* Keeps a list of dependencies which are root requirements, and as such
* have already their maximum required range loaded and can not be
* extended by markPackageNameForLoading
*
* Packages get cleared from this list if they get unlocked as in that case
* we need to actually load them
*
* @var array<string, true>
*/
private $maxExtendedReqs = [];
/**
* @var array
* @phpstan-var array<string, bool>
*/
private $updateAllowWarned = [];
/** @var int */
private $indexCounter = 0;
/** @var ?SecurityAdvisoryPoolFilter */
private $securityAdvisoryPoolFilter;
/**
* @param int[] $acceptableStabilities array of stability => BasePackage::STABILITY_* value
* @phpstan-param array<key-of<BasePackage::STABILITIES>, BasePackage::STABILITY_*> $acceptableStabilities
* @param int[] $stabilityFlags an array of package name => BasePackage::STABILITY_* value
* @phpstan-param array<string, BasePackage::STABILITY_*> $stabilityFlags
* @param array[] $rootAliases
* @phpstan-param array<string, array<string, array{alias: string, alias_normalized: string}>> $rootAliases
* @param string[] $rootReferences an array of package name => source reference
* @phpstan-param array<string, string> $rootReferences
* @param array<string, ConstraintInterface> $temporaryConstraints Runtime temporary constraints that will be used to filter packages
*/
public function __construct(array $acceptableStabilities, array $stabilityFlags, array $rootAliases, array $rootReferences, IOInterface $io, ?EventDispatcher $eventDispatcher = null, ?PoolOptimizer $poolOptimizer = null, array $temporaryConstraints = [], ?SecurityAdvisoryPoolFilter $securityAdvisoryPoolFilter = null)
{
$this->acceptableStabilities = $acceptableStabilities;
$this->stabilityFlags = $stabilityFlags;
$this->rootAliases = $rootAliases;
$this->rootReferences = $rootReferences;
$this->eventDispatcher = $eventDispatcher;
$this->poolOptimizer = $poolOptimizer;
$this->io = $io;
$this->temporaryConstraints = $temporaryConstraints;
$this->securityAdvisoryPoolFilter = $securityAdvisoryPoolFilter;
}
/**
* Packages of those types are ignored
*
* @param list<string> $types
*/
public function setIgnoredTypes(array $types): void
{
$this->ignoredTypes = $types;
}
/**
* Only packages of those types are allowed if set to non-null
*
* @param list<string>|null $types
*/
public function setAllowedTypes(?array $types): void
{
$this->allowedTypes = $types;
}
/**
* @param RepositoryInterface[] $repositories
*/
public function buildPool(array $repositories, Request $request): Pool
{
$this->restrictedPackagesList = $request->getRestrictedPackages() !== null ? array_flip($request->getRestrictedPackages()) : null;
if (\count($request->getUpdateAllowList()) > 0) {
$this->updateAllowList = $request->getUpdateAllowList();
$this->warnAboutNonMatchingUpdateAllowList($request);
if (null === $request->getLockedRepository()) {
throw new \LogicException('No lock repo present and yet a partial update was requested.');
}
foreach ($request->getLockedRepository()->getPackages() as $lockedPackage) {
if (!$this->isUpdateAllowed($lockedPackage)) {
// remember which packages we skipped loading remote content for in this partial update
$this->skippedLoad[$lockedPackage->getName()][] = $lockedPackage;
foreach ($lockedPackage->getReplaces() as $link) {
$this->skippedLoad[$link->getTarget()][] = $lockedPackage;
}
// Path repo packages are never loaded from lock, to force them to always remain in sync
// unless symlinking is disabled in which case we probably should rather treat them like
// regular packages. We mark them specially so they can be reloaded fully including update propagation
// if they do get unlocked, but by default they are unlocked without update propagation.
if ($lockedPackage->getDistType() === 'path') {
$transportOptions = $lockedPackage->getTransportOptions();
if (!isset($transportOptions['symlink']) || $transportOptions['symlink'] !== false) {
$this->pathRepoUnlocked[$lockedPackage->getName()] = true;
continue;
}
}
$request->lockPackage($lockedPackage);
}
}
}
foreach ($request->getFixedOrLockedPackages() as $package) {
// using MatchAllConstraint here because fixed packages do not need to retrigger
// loading any packages
$this->loadedPackages[$package->getName()] = new MatchAllConstraint();
// replace means conflict, so if a fixed package replaces a name, no need to load that one, packages would conflict anyways
foreach ($package->getReplaces() as $link) {
$this->loadedPackages[$link->getTarget()] = new MatchAllConstraint();
}
// TODO in how far can we do the above for conflicts? It's more tricky cause conflicts can be limited to
// specific versions while replace is a conflict with all versions of the name
if (
$package->getRepository() instanceof RootPackageRepository
|| $package->getRepository() instanceof PlatformRepository
|| StabilityFilter::isPackageAcceptable($this->acceptableStabilities, $this->stabilityFlags, $package->getNames(), $package->getStability())
) {
$this->loadPackage($request, $repositories, $package, false);
} else {
$this->unacceptableFixedOrLockedPackages[] = $package;
}
}
foreach ($request->getRequires() as $packageName => $constraint) {
// fixed and locked packages have already been added, so if a root require needs one of them, no need to do anything
if (isset($this->loadedPackages[$packageName])) {
continue;
}
$this->packagesToLoad[$packageName] = $constraint;
$this->maxExtendedReqs[$packageName] = true;
}
// clean up packagesToLoad for anything we manually marked loaded above
foreach ($this->packagesToLoad as $name => $constraint) {
if (isset($this->loadedPackages[$name])) {
unset($this->packagesToLoad[$name]);
}
}
while (\count($this->packagesToLoad) > 0) {
$this->loadPackagesMarkedForLoading($request, $repositories);
}
if (\count($this->temporaryConstraints) > 0) {
foreach ($this->packages as $i => $package) {
// we check all alias related packages at once, so no need to check individual aliases
if ($package instanceof AliasPackage) {
continue;
}
foreach ($package->getNames() as $packageName) {
if (!isset($this->temporaryConstraints[$packageName])) {
continue;
}
$constraint = $this->temporaryConstraints[$packageName];
$packageAndAliases = [$i => $package];
if (isset($this->aliasMap[spl_object_hash($package)])) {
$packageAndAliases += $this->aliasMap[spl_object_hash($package)];
}
$found = false;
foreach ($packageAndAliases as $packageOrAlias) {
if (CompilingMatcher::match($constraint, Constraint::OP_EQ, $packageOrAlias->getVersion())) {
$found = true;
}
}
if (!$found) {
foreach ($packageAndAliases as $index => $packageOrAlias) {
unset($this->packages[$index]);
}
}
}
}
}
if ($this->eventDispatcher !== null) {
$prePoolCreateEvent = new PrePoolCreateEvent(
PluginEvents::PRE_POOL_CREATE,
$repositories,
$request,
$this->acceptableStabilities,
$this->stabilityFlags,
$this->rootAliases,
$this->rootReferences,
$this->packages,
$this->unacceptableFixedOrLockedPackages
);
$this->eventDispatcher->dispatch($prePoolCreateEvent->getName(), $prePoolCreateEvent);
$this->packages = $prePoolCreateEvent->getPackages();
$this->unacceptableFixedOrLockedPackages = $prePoolCreateEvent->getUnacceptableFixedPackages();
}
$pool = new Pool($this->packages, $this->unacceptableFixedOrLockedPackages);
$this->aliasMap = [];
$this->packagesToLoad = [];
$this->loadedPackages = [];
$this->loadedPerRepo = [];
$this->packages = [];
$this->unacceptableFixedOrLockedPackages = [];
$this->maxExtendedReqs = [];
$this->skippedLoad = [];
$this->indexCounter = 0;
$this->io->debug('Built pool.');
// filter vulnerable packages before optimizing the pool otherwise we may end up with inconsistent state where the optimizer took away versions
// that were not vulnerable and now suddenly the vulnerable ones are removed and we are missing some versions to make it solvable
$pool = $this->runSecurityAdvisoryFilter($pool, $repositories, $request);
$pool = $this->runOptimizer($request, $pool);
Intervals::clear();
return $pool;
}
private function markPackageNameForLoading(Request $request, string $name, ConstraintInterface $constraint): void
{
// Skip platform requires at this stage
if (PlatformRepository::isPlatformPackage($name)) {
return;
}
// Root require (which was not unlocked) already loaded the maximum range so no
// need to check anything here
if (isset($this->maxExtendedReqs[$name])) {
return;
}
// Root requires can not be overruled by dependencies so there is no point in
// extending the loaded constraint for those.
// This is triggered when loading a root require which was locked but got unlocked, then
// we make sure that we load at most the intervals covered by the root constraint.
$rootRequires = $request->getRequires();
if (isset($rootRequires[$name]) && !Intervals::isSubsetOf($constraint, $rootRequires[$name])) {
$constraint = $rootRequires[$name];
}
// Not yet loaded or already marked for a reload, set the constraint to be loaded
if (!isset($this->loadedPackages[$name])) {
// Maybe it was already marked before but not loaded yet. In that case
// we have to extend the constraint (we don't check if they are identical because
// MultiConstraint::create() will optimize anyway)
if (isset($this->packagesToLoad[$name])) {
// Already marked for loading and this does not expand the constraint to be loaded, nothing to do
if (Intervals::isSubsetOf($constraint, $this->packagesToLoad[$name])) {
return;
}
// extend the constraint to be loaded
$constraint = Intervals::compactConstraint(MultiConstraint::create([$this->packagesToLoad[$name], $constraint], false));
}
$this->packagesToLoad[$name] = $constraint;
return;
}
// No need to load this package with this constraint because it is
// a subset of the constraint with which we have already loaded packages
if (Intervals::isSubsetOf($constraint, $this->loadedPackages[$name])) {
return;
}
// We have already loaded that package but not in the constraint that's
// required. We extend the constraint and mark that package as not being loaded
// yet so we get the required package versions
$this->packagesToLoad[$name] = Intervals::compactConstraint(MultiConstraint::create([$this->loadedPackages[$name], $constraint], false));
unset($this->loadedPackages[$name]);
}
/**
* @param RepositoryInterface[] $repositories
*/
private function loadPackagesMarkedForLoading(Request $request, array $repositories): void
{
foreach ($this->packagesToLoad as $name => $constraint) {
if ($this->restrictedPackagesList !== null && !isset($this->restrictedPackagesList[$name])) {
unset($this->packagesToLoad[$name]);
continue;
}
$this->loadedPackages[$name] = $constraint;
}
// Load packages in chunks of 50 to prevent memory usage build-up due to caches of all sorts
$packageBatches = array_chunk($this->packagesToLoad, self::LOAD_BATCH_SIZE, true);
$this->packagesToLoad = [];
foreach ($repositories as $repoIndex => $repository) {
// these repos have their packages fixed or locked if they need to be loaded so we
// never need to load anything else from them
if ($repository instanceof PlatformRepository || $repository === $request->getLockedRepository()) {
continue;
}
if (0 === \count($packageBatches)) {
break;
}
foreach ($packageBatches as $batchIndex => $packageBatch) {
$result = $repository->loadPackages($packageBatch, $this->acceptableStabilities, $this->stabilityFlags, $this->loadedPerRepo[$repoIndex] ?? []);
foreach ($result['namesFound'] as $name) {
// avoid loading the same package again from other repositories once it has been found
unset($packageBatches[$batchIndex][$name]);
}
foreach ($result['packages'] as $package) {
$this->loadedPerRepo[$repoIndex][$package->getName()][$package->getVersion()] = $package;
if (in_array($package->getType(), $this->ignoredTypes, true) || ($this->allowedTypes !== null && !in_array($package->getType(), $this->allowedTypes, true))) {
continue;
}
$this->loadPackage($request, $repositories, $package, !isset($this->pathRepoUnlocked[$package->getName()]));
}
}
$packageBatches = array_chunk(array_merge(...$packageBatches), self::LOAD_BATCH_SIZE, true);
}
}
/**
* @param RepositoryInterface[] $repositories
*/
private function loadPackage(Request $request, array $repositories, BasePackage $package, bool $propagateUpdate): void
{
$index = $this->indexCounter++;
$this->packages[$index] = $package;
if ($package instanceof AliasPackage) {
$this->aliasMap[spl_object_hash($package->getAliasOf())][$index] = $package;
}
$name = $package->getName();
// we're simply setting the root references on all versions for a name here and rely on the solver to pick the
// right version. It'd be more work to figure out which versions and which aliases of those versions this may
// apply to
if (isset($this->rootReferences[$name])) {
// do not modify the references on already locked or fixed packages
if (!$request->isLockedPackage($package) && !$request->isFixedPackage($package)) {
$package->setSourceDistReferences($this->rootReferences[$name]);
}
}
// if propagateUpdate is false we are loading a fixed or locked package, root aliases do not apply as they are
// manually loaded as separate packages in this case
//
// packages in pathRepoUnlocked however need to also load root aliases, they have propagateUpdate set to
// false because their deps should not be unlocked, but that is irrelevant for root aliases
if (($propagateUpdate || isset($this->pathRepoUnlocked[$package->getName()])) && isset($this->rootAliases[$name][$package->getVersion()])) {
$alias = $this->rootAliases[$name][$package->getVersion()];
if ($package instanceof AliasPackage) {
$basePackage = $package->getAliasOf();
} else {
$basePackage = $package;
}
if ($basePackage instanceof CompletePackage) {
$aliasPackage = new CompleteAliasPackage($basePackage, $alias['alias_normalized'], $alias['alias']);
} else {
$aliasPackage = new AliasPackage($basePackage, $alias['alias_normalized'], $alias['alias']);
}
$aliasPackage->setRootPackageAlias(true);
$newIndex = $this->indexCounter++;
$this->packages[$newIndex] = $aliasPackage;
$this->aliasMap[spl_object_hash($aliasPackage->getAliasOf())][$newIndex] = $aliasPackage;
}
foreach ($package->getRequires() as $link) {
$require = $link->getTarget();
$linkConstraint = $link->getConstraint();
// if the required package is loaded as a locked package only and hasn't had its deps analyzed
if (isset($this->skippedLoad[$require])) {
// if we're doing a full update or this is a partial update with transitive deps and we're currently
// looking at a package which needs to be updated we need to unlock the package we now know is a
// dependency of another package which we are trying to update, and then attempt to load it again
if ($propagateUpdate && $request->getUpdateAllowTransitiveDependencies()) {
$skippedRootRequires = $this->getSkippedRootRequires($request, $require);
if ($request->getUpdateAllowTransitiveRootDependencies() || 0 === \count($skippedRootRequires)) {
$this->unlockPackage($request, $repositories, $require);
$this->markPackageNameForLoading($request, $require, $linkConstraint);
} else {
foreach ($skippedRootRequires as $rootRequire) {
if (!isset($this->updateAllowWarned[$rootRequire])) {
$this->updateAllowWarned[$rootRequire] = true;
$this->io->writeError('<warning>Dependency '.$rootRequire.' is also a root requirement. Package has not been listed as an update argument, so keeping locked at old version. Use --with-all-dependencies (-W) to include root dependencies.</warning>');
}
}
}
} elseif (isset($this->pathRepoUnlocked[$require]) && !isset($this->loadedPackages[$require])) {
// if doing a partial update and a package depends on a path-repo-unlocked package which is not referenced by the root, we need to ensure it gets loaded as it was not loaded by the request's root requirements
// and would not be loaded above if update propagation is not allowed (which happens if the requirer is itself a path-repo-unlocked package) or if transitive deps are not allowed to be unlocked
$this->markPackageNameForLoading($request, $require, $linkConstraint);
}
} else {
$this->markPackageNameForLoading($request, $require, $linkConstraint);
}
}
// if we're doing a partial update with deps we also need to unlock packages which are being replaced in case
// they are currently locked and thus prevent this updateable package from being installable/updateable
if ($propagateUpdate && $request->getUpdateAllowTransitiveDependencies()) {
foreach ($package->getReplaces() as $link) {
$replace = $link->getTarget();
if (isset($this->loadedPackages[$replace], $this->skippedLoad[$replace])) {
$skippedRootRequires = $this->getSkippedRootRequires($request, $replace);
if ($request->getUpdateAllowTransitiveRootDependencies() || 0 === \count($skippedRootRequires)) {
$this->unlockPackage($request, $repositories, $replace);
// the replaced package only needs to be loaded if something else requires it
$this->markPackageNameForLoadingIfRequired($request, $replace);
} else {
foreach ($skippedRootRequires as $rootRequire) {
if (!isset($this->updateAllowWarned[$rootRequire])) {
$this->updateAllowWarned[$rootRequire] = true;
$this->io->writeError('<warning>Dependency '.$rootRequire.' is also a root requirement. Package has not been listed as an update argument, so keeping locked at old version. Use --with-all-dependencies (-W) to include root dependencies.</warning>');
}
}
}
}
}
}
}
/**
* Checks if a particular name is required directly in the request
*
* @param string $name packageName
*/
private function isRootRequire(Request $request, string $name): bool
{
$rootRequires = $request->getRequires();
return isset($rootRequires[$name]);
}
/**
* @return string[]
*/
private function getSkippedRootRequires(Request $request, string $name): array
{
if (!isset($this->skippedLoad[$name])) {
return [];
}
$rootRequires = $request->getRequires();
$matches = [];
if (isset($rootRequires[$name])) {
return array_map(static function (PackageInterface $package) use ($name): string {
if ($name !== $package->getName()) {
return $package->getName() .' (via replace of '.$name.')';
}
return $package->getName();
}, $this->skippedLoad[$name]);
}
foreach ($this->skippedLoad[$name] as $packageOrReplacer) {
if (isset($rootRequires[$packageOrReplacer->getName()])) {
$matches[] = $packageOrReplacer->getName();
}
foreach ($packageOrReplacer->getReplaces() as $link) {
if (isset($rootRequires[$link->getTarget()])) {
if ($name !== $packageOrReplacer->getName()) {
$matches[] = $packageOrReplacer->getName() .' (via replace of '.$name.')';
} else {
$matches[] = $packageOrReplacer->getName();
}
break;
}
}
}
return $matches;
}
/**
* Checks whether the update allow list allows this package in the lock file to be updated
*/
private function isUpdateAllowed(BasePackage $package): bool
{
foreach ($this->updateAllowList as $pattern) {
$patternRegexp = BasePackage::packageNameToRegexp($pattern);
if (Preg::isMatch($patternRegexp, $package->getName())) {
return true;
}
}
return false;
}
private function warnAboutNonMatchingUpdateAllowList(Request $request): void
{
if (null === $request->getLockedRepository()) {
throw new \LogicException('No lock repo present and yet a partial update was requested.');
}
foreach ($this->updateAllowList as $pattern) {
$matchedPlatformPackage = false;
$patternRegexp = BasePackage::packageNameToRegexp($pattern);
// update pattern matches a locked package? => all good
foreach ($request->getLockedRepository()->getPackages() as $package) {
if (Preg::isMatch($patternRegexp, $package->getName())) {
continue 2;
}
}
// update pattern matches a root require? => all good, probably a new package
foreach ($request->getRequires() as $packageName => $constraint) {
if (Preg::isMatch($patternRegexp, $packageName)) {
if (PlatformRepository::isPlatformPackage($packageName)) {
$matchedPlatformPackage = true;
continue;
}
continue 2;
}
}
if ($matchedPlatformPackage) {
$this->io->writeError('<warning>Pattern "' . $pattern . '" listed for update matches platform packages, but these cannot be updated by Composer.</warning>');
} elseif (strpos($pattern, '*') !== false) {
$this->io->writeError('<warning>Pattern "' . $pattern . '" listed for update does not match any locked packages.</warning>');
} else {
$this->io->writeError('<warning>Package "' . $pattern . '" listed for update is not locked.</warning>');
}
}
}
/**
* Reverts the decision to use a locked package if a partial update with transitive dependencies
* found that this package actually needs to be updated
*
* @param RepositoryInterface[] $repositories
*/
private function unlockPackage(Request $request, array $repositories, string $name): void
{
foreach ($this->skippedLoad[$name] as $packageOrReplacer) {
// if we unfixed a replaced package name, we also need to unfix the replacer itself
// as long as it was not unfixed yet
if ($packageOrReplacer->getName() !== $name && isset($this->skippedLoad[$packageOrReplacer->getName()])) {
$replacerName = $packageOrReplacer->getName();
if ($request->getUpdateAllowTransitiveRootDependencies() || (!$this->isRootRequire($request, $name) && !$this->isRootRequire($request, $replacerName))) {
$this->unlockPackage($request, $repositories, $replacerName);
if ($this->isRootRequire($request, $replacerName)) {
$this->markPackageNameForLoading($request, $replacerName, new MatchAllConstraint);
} else {
foreach ($this->packages as $loadedPackage) {
$requires = $loadedPackage->getRequires();
if (isset($requires[$replacerName])) {
$this->markPackageNameForLoading($request, $replacerName, $requires[$replacerName]->getConstraint());
}
}
}
}
}
}
if (isset($this->pathRepoUnlocked[$name])) {
foreach ($this->packages as $index => $package) {
if ($package->getName() === $name) {
$this->removeLoadedPackage($request, $repositories, $package, $index);
}
}
}
unset($this->skippedLoad[$name], $this->loadedPackages[$name], $this->maxExtendedReqs[$name], $this->pathRepoUnlocked[$name]);
// remove locked package by this name which was already initialized
foreach ($request->getLockedPackages() as $lockedPackage) {
if (!($lockedPackage instanceof AliasPackage) && $lockedPackage->getName() === $name) {
if (false !== $index = array_search($lockedPackage, $this->packages, true)) {
$request->unlockPackage($lockedPackage);
$this->removeLoadedPackage($request, $repositories, $lockedPackage, $index);
// make sure that any requirements for this package by other locked or fixed packages are now
// also loaded, as they were previously ignored because the locked (now unlocked) package already
// satisfied their requirements
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | true |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/Pool.php | src/Composer/DependencyResolver/Pool.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver;
use Composer\Advisory\PartialSecurityAdvisory;
use Composer\Advisory\SecurityAdvisory;
use Composer\Package\BasePackage;
use Composer\Package\Version\VersionParser;
use Composer\Semver\CompilingMatcher;
use Composer\Semver\Constraint\ConstraintInterface;
use Composer\Semver\Constraint\Constraint;
/**
* A package pool contains all packages for dependency resolution
*
* @author Nils Adermann <naderman@naderman.de>
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class Pool implements \Countable
{
/** @var BasePackage[] */
protected $packages = [];
/** @var array<string, BasePackage[]> */
protected $packageByName = [];
/** @var VersionParser */
protected $versionParser;
/** @var array<string, array<string, BasePackage[]>> */
protected $providerCache = [];
/** @var BasePackage[] */
protected $unacceptableFixedOrLockedPackages;
/** @var array<string, array<string, string>> Map of package name => normalized version => pretty version */
protected $removedVersions = [];
/** @var array<string, array<string, string>> Map of package object hash => removed normalized versions => removed pretty version */
protected $removedVersionsByPackage = [];
/** @var array<string, array<string, array<SecurityAdvisory|PartialSecurityAdvisory>>> Map of package name => normalized version => security advisories */
private $securityRemovedVersions = [];
/** @var array<string, array<string, string>> Map of package name => normalized version => pretty version */
private $abandonedRemovedVersions = [];
/**
* @param BasePackage[] $packages
* @param BasePackage[] $unacceptableFixedOrLockedPackages
* @param array<string, array<string, string>> $removedVersions
* @param array<string, array<string, string>> $removedVersionsByPackage
* @param array<string, array<string, array<SecurityAdvisory|PartialSecurityAdvisory>>> $securityRemovedVersions
* @param array<string, array<string, string>> $abandonedRemovedVersions
*/
public function __construct(array $packages = [], array $unacceptableFixedOrLockedPackages = [], array $removedVersions = [], array $removedVersionsByPackage = [], array $securityRemovedVersions = [], array $abandonedRemovedVersions = [])
{
$this->versionParser = new VersionParser;
$this->setPackages($packages);
$this->unacceptableFixedOrLockedPackages = $unacceptableFixedOrLockedPackages;
$this->removedVersions = $removedVersions;
$this->removedVersionsByPackage = $removedVersionsByPackage;
$this->securityRemovedVersions = $securityRemovedVersions;
$this->abandonedRemovedVersions = $abandonedRemovedVersions;
}
/**
* @return array<string, string>
*/
public function getRemovedVersions(string $name, ConstraintInterface $constraint): array
{
if (!isset($this->removedVersions[$name])) {
return [];
}
$result = [];
foreach ($this->removedVersions[$name] as $version => $prettyVersion) {
if ($constraint->matches(new Constraint('==', $version))) {
$result[$version] = $prettyVersion;
}
}
return $result;
}
/**
* @return array<string, array<string, string>>
*/
public function getAllRemovedVersions(): array
{
return $this->removedVersions;
}
/**
* @return array<string, string>
*/
public function getRemovedVersionsByPackage(string $objectHash): array
{
if (!isset($this->removedVersionsByPackage[$objectHash])) {
return [];
}
return $this->removedVersionsByPackage[$objectHash];
}
/**
* @return array<string, array<string, string>>
*/
public function getAllRemovedVersionsByPackage(): array
{
return $this->removedVersionsByPackage;
}
public function isSecurityRemovedPackageVersion(string $packageName, ?ConstraintInterface $constraint): bool
{
foreach ($this->securityRemovedVersions[$packageName] ?? [] as $version => $packageWithSecurityAdvisories) {
if ($constraint !== null && $constraint->matches(new Constraint('==', $version))) {
return true;
}
}
return false;
}
/**
* @return string[]
*/
public function getSecurityAdvisoryIdentifiersForPackageVersion(string $packageName, ?ConstraintInterface $constraint): array
{
foreach ($this->securityRemovedVersions[$packageName] ?? [] as $version => $packageWithSecurityAdvisories) {
if ($constraint !== null && $constraint->matches(new Constraint('==', $version))) {
return array_map(static function ($advisory) {
return $advisory->advisoryId;
}, $packageWithSecurityAdvisories);
}
}
return [];
}
public function isAbandonedRemovedPackageVersion(string $packageName, ?ConstraintInterface $constraint): bool
{
foreach ($this->abandonedRemovedVersions[$packageName] ?? [] as $version => $prettyVersion) {
if ($constraint !== null && $constraint->matches(new Constraint('==', $version))) {
return true;
}
}
return false;
}
/**
* @return array<string, array<string, array<SecurityAdvisory|PartialSecurityAdvisory>>>
*/
public function getAllSecurityRemovedPackageVersions(): array
{
return $this->securityRemovedVersions;
}
/**
* @return array<string, array<string, string>>
*/
public function getAllAbandonedRemovedPackageVersions(): array
{
return $this->abandonedRemovedVersions;
}
/**
* @param BasePackage[] $packages
*/
private function setPackages(array $packages): void
{
$id = 1;
foreach ($packages as $package) {
$this->packages[] = $package;
$package->id = $id++;
foreach ($package->getNames() as $provided) {
$this->packageByName[$provided][] = $package;
}
}
}
/**
* @return BasePackage[]
*/
public function getPackages(): array
{
return $this->packages;
}
/**
* Retrieves the package object for a given package id.
*/
public function packageById(int $id): BasePackage
{
return $this->packages[$id - 1];
}
/**
* Returns how many packages have been loaded into the pool
*/
public function count(): int
{
return \count($this->packages);
}
/**
* Searches all packages providing the given package name and match the constraint
*
* @param string $name The package name to be searched for
* @param ?ConstraintInterface $constraint A constraint that all returned
* packages must match or null to return all
* @return BasePackage[] A set of packages
*/
public function whatProvides(string $name, ?ConstraintInterface $constraint = null): array
{
$key = (string) $constraint;
if (isset($this->providerCache[$name][$key])) {
return $this->providerCache[$name][$key];
}
return $this->providerCache[$name][$key] = $this->computeWhatProvides($name, $constraint);
}
/**
* @param string $name The package name to be searched for
* @param ?ConstraintInterface $constraint A constraint that all returned
* packages must match or null to return all
* @return BasePackage[]
*/
private function computeWhatProvides(string $name, ?ConstraintInterface $constraint = null): array
{
if (!isset($this->packageByName[$name])) {
return [];
}
$matches = [];
foreach ($this->packageByName[$name] as $candidate) {
if ($this->match($candidate, $name, $constraint)) {
$matches[] = $candidate;
}
}
return $matches;
}
public function literalToPackage(int $literal): BasePackage
{
$packageId = abs($literal);
return $this->packageById($packageId);
}
/**
* @param array<int, BasePackage> $installedMap
*/
public function literalToPrettyString(int $literal, array $installedMap): string
{
$package = $this->literalToPackage($literal);
if (isset($installedMap[$package->id])) {
$prefix = ($literal > 0 ? 'keep' : 'remove');
} else {
$prefix = ($literal > 0 ? 'install' : 'don\'t install');
}
return $prefix.' '.$package->getPrettyString();
}
/**
* Checks if the package matches the given constraint directly or through
* provided or replaced packages
*
* @param string $name Name of the package to be matched
*/
public function match(BasePackage $candidate, string $name, ?ConstraintInterface $constraint = null): bool
{
$candidateName = $candidate->getName();
$candidateVersion = $candidate->getVersion();
if ($candidateName === $name) {
return $constraint === null || CompilingMatcher::match($constraint, Constraint::OP_EQ, $candidateVersion);
}
$provides = $candidate->getProvides();
$replaces = $candidate->getReplaces();
// aliases create multiple replaces/provides for one target so they can not use the shortcut below
if (isset($replaces[0]) || isset($provides[0])) {
foreach ($provides as $link) {
if ($link->getTarget() === $name && ($constraint === null || $constraint->matches($link->getConstraint()))) {
return true;
}
}
foreach ($replaces as $link) {
if ($link->getTarget() === $name && ($constraint === null || $constraint->matches($link->getConstraint()))) {
return true;
}
}
return false;
}
if (isset($provides[$name]) && ($constraint === null || $constraint->matches($provides[$name]->getConstraint()))) {
return true;
}
if (isset($replaces[$name]) && ($constraint === null || $constraint->matches($replaces[$name]->getConstraint()))) {
return true;
}
return false;
}
public function isUnacceptableFixedOrLockedPackage(BasePackage $package): bool
{
return \in_array($package, $this->unacceptableFixedOrLockedPackages, true);
}
/**
* @return BasePackage[]
*/
public function getUnacceptableFixedOrLockedPackages(): array
{
return $this->unacceptableFixedOrLockedPackages;
}
public function __toString(): string
{
$str = "Pool:\n";
foreach ($this->packages as $package) {
$str .= '- '.str_pad((string) $package->id, 6, ' ', STR_PAD_LEFT).': '.$package->getName()."\n";
}
return $str;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/Rule2Literals.php | src/Composer/DependencyResolver/Rule2Literals.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver;
/**
* @author Nils Adermann <naderman@naderman.de>
* @phpstan-import-type ReasonData from Rule
*/
class Rule2Literals extends Rule
{
/** @var int */
protected $literal1;
/** @var int */
protected $literal2;
/**
* @param Rule::RULE_* $reason A RULE_* constant
* @param mixed $reasonData
*
* @phpstan-param ReasonData $reasonData
*/
public function __construct(int $literal1, int $literal2, $reason, $reasonData)
{
parent::__construct($reason, $reasonData);
if ($literal1 < $literal2) {
$this->literal1 = $literal1;
$this->literal2 = $literal2;
} else {
$this->literal1 = $literal2;
$this->literal2 = $literal1;
}
}
/**
* @return non-empty-list<int>
*/
public function getLiterals(): array
{
return [$this->literal1, $this->literal2];
}
/**
* @inheritDoc
*/
public function getHash()
{
return $this->literal1.','.$this->literal2;
}
/**
* Checks if this rule is equal to another one
*
* Ignores whether either of the rules is disabled.
*
* @param Rule $rule The rule to check against
* @return bool Whether the rules are equal
*/
public function equals(Rule $rule): bool
{
// specialized fast-case
if ($rule instanceof self) {
if ($this->literal1 !== $rule->literal1) {
return false;
}
if ($this->literal2 !== $rule->literal2) {
return false;
}
return true;
}
$literals = $rule->getLiterals();
if (2 !== \count($literals)) {
return false;
}
if ($this->literal1 !== $literals[0]) {
return false;
}
if ($this->literal2 !== $literals[1]) {
return false;
}
return true;
}
/** @return false */
public function isAssertion(): bool
{
return false;
}
/**
* Formats a rule as a string of the format (Literal1|Literal2|...)
*/
public function __toString(): string
{
$result = $this->isDisabled() ? 'disabled(' : '(';
$result .= $this->literal1 . '|' . $this->literal2 . ')';
return $result;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/LockTransaction.php | src/Composer/DependencyResolver/LockTransaction.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver;
use Composer\Package\AliasPackage;
use Composer\Package\BasePackage;
use Composer\Package\Package;
use Composer\Pcre\Preg;
/**
* @author Nils Adermann <naderman@naderman.de>
* @internal
*/
class LockTransaction extends Transaction
{
/**
* packages in current lock file, platform repo or otherwise present
*
* Indexed by spl_object_hash
*
* @var array<string, BasePackage>
*/
protected $presentMap;
/**
* Packages which cannot be mapped, platform repo, root package, other fixed repos
*
* Indexed by package id
*
* @var array<int, BasePackage>
*/
protected $unlockableMap;
/**
* @var array{dev: BasePackage[], non-dev: BasePackage[], all: BasePackage[]}
*/
protected $resultPackages;
/**
* @param array<string, BasePackage> $presentMap
* @param array<int, BasePackage> $unlockableMap
*/
public function __construct(Pool $pool, array $presentMap, array $unlockableMap, Decisions $decisions)
{
$this->presentMap = $presentMap;
$this->unlockableMap = $unlockableMap;
$this->setResultPackages($pool, $decisions);
parent::__construct($this->presentMap, $this->resultPackages['all']);
}
// TODO make this a bit prettier instead of the two text indexes?
public function setResultPackages(Pool $pool, Decisions $decisions): void
{
$this->resultPackages = ['all' => [], 'non-dev' => [], 'dev' => []];
foreach ($decisions as $i => $decision) {
$literal = $decision[Decisions::DECISION_LITERAL];
if ($literal > 0) {
$package = $pool->literalToPackage($literal);
$this->resultPackages['all'][] = $package;
if (!isset($this->unlockableMap[$package->id])) {
$this->resultPackages['non-dev'][] = $package;
}
}
}
}
public function setNonDevPackages(LockTransaction $extractionResult): void
{
$packages = $extractionResult->getNewLockPackages(false);
$this->resultPackages['dev'] = $this->resultPackages['non-dev'];
$this->resultPackages['non-dev'] = [];
foreach ($packages as $package) {
foreach ($this->resultPackages['dev'] as $i => $resultPackage) {
// TODO this comparison is probably insufficient, aliases, what about modified versions? I guess they aren't possible?
if ($package->getName() === $resultPackage->getName()) {
$this->resultPackages['non-dev'][] = $resultPackage;
unset($this->resultPackages['dev'][$i]);
}
}
}
}
// TODO additionalFixedRepository needs to be looked at here as well?
/**
* @return BasePackage[]
*/
public function getNewLockPackages(bool $devMode, bool $updateMirrors = false): array
{
$packages = [];
foreach ($this->resultPackages[$devMode ? 'dev' : 'non-dev'] as $package) {
if ($package instanceof AliasPackage) {
continue;
}
// if we're just updating mirrors we need to reset everything to the same as currently "present" packages' references to keep the lock file as-is
if ($updateMirrors === true && !array_key_exists(spl_object_hash($package), $this->presentMap)) {
$package = $this->updateMirrorAndUrls($package);
}
$packages[] = $package;
}
return $packages;
}
/**
* Try to return the original package from presentMap with updated URLs/mirrors
*
* If the type of source/dist changed, then we do not update those and keep them as they were
*/
private function updateMirrorAndUrls(BasePackage $package): BasePackage
{
foreach ($this->presentMap as $presentPackage) {
if ($package->getName() !== $presentPackage->getName()) {
continue;
}
if ($package->getVersion() !== $presentPackage->getVersion()) {
continue;
}
if ($presentPackage->getSourceReference() === null) {
continue;
}
if ($presentPackage->getSourceType() !== $package->getSourceType()) {
continue;
}
if ($presentPackage instanceof Package) {
$presentPackage->setSourceUrl($package->getSourceUrl());
$presentPackage->setSourceMirrors($package->getSourceMirrors());
}
// if the dist type changed, we only update the source url/mirrors
if ($presentPackage->getDistType() !== $package->getDistType()) {
return $presentPackage;
}
// update dist url if it is in a known format
if (
$package->getDistUrl() !== null
&& $presentPackage->getDistReference() !== null
&& Preg::isMatch('{^https?://(?:(?:www\.)?bitbucket\.org|(api\.)?github\.com|(?:www\.)?gitlab\.com)/}i', $package->getDistUrl())
) {
$presentPackage->setDistUrl(Preg::replace('{(?<=/|sha=)[a-f0-9]{40}(?=/|$)}i', $presentPackage->getDistReference(), $package->getDistUrl()));
}
$presentPackage->setDistMirrors($package->getDistMirrors());
return $presentPackage;
}
return $package;
}
/**
* Checks which of the given aliases from composer.json are actually in use for the lock file
* @param list<array{package: string, version: string, alias: string, alias_normalized: string}> $aliases
* @return list<array{package: string, version: string, alias: string, alias_normalized: string}>
*/
public function getAliases(array $aliases): array
{
$usedAliases = [];
foreach ($this->resultPackages['all'] as $package) {
if ($package instanceof AliasPackage) {
foreach ($aliases as $index => $alias) {
if ($alias['package'] === $package->getName()) {
$usedAliases[] = $alias;
unset($aliases[$index]);
}
}
}
}
usort($usedAliases, static function ($a, $b): int {
return strcmp($a['package'], $b['package']);
});
return $usedAliases;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/MultiConflictRule.php | src/Composer/DependencyResolver/MultiConflictRule.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver;
/**
* @author Nils Adermann <naderman@naderman.de>
*
* MultiConflictRule([A, B, C]) acts as Rule([-A, -B]), Rule([-A, -C]), Rule([-B, -C])
*/
class MultiConflictRule extends Rule
{
/** @var non-empty-list<int> */
protected $literals;
/**
* @param non-empty-list<int> $literals
*/
public function __construct(array $literals, $reason, $reasonData)
{
parent::__construct($reason, $reasonData);
if (\count($literals) < 3) {
throw new \RuntimeException("multi conflict rule requires at least 3 literals");
}
// sort all packages ascending by id
sort($literals);
$this->literals = $literals;
}
/**
* @return non-empty-list<int>
*/
public function getLiterals(): array
{
return $this->literals;
}
/**
* @inheritDoc
*/
public function getHash()
{
$data = unpack('ihash', (string) hash(\PHP_VERSION_ID > 80100 ? 'xxh3' : 'sha1', 'c:'.implode(',', $this->literals), true));
if (false === $data) {
throw new \RuntimeException('Failed unpacking: '.implode(', ', $this->literals));
}
return $data['hash'];
}
/**
* Checks if this rule is equal to another one
*
* Ignores whether either of the rules is disabled.
*
* @param Rule $rule The rule to check against
* @return bool Whether the rules are equal
*/
public function equals(Rule $rule): bool
{
if ($rule instanceof MultiConflictRule) {
return $this->literals === $rule->getLiterals();
}
return false;
}
public function isAssertion(): bool
{
return false;
}
/**
* @return never
* @throws \RuntimeException
*/
public function disable(): void
{
throw new \RuntimeException("Disabling multi conflict rules is not possible. Please contact composer at https://github.com/composer/composer to let us debug what lead to this situation.");
}
/**
* Formats a rule as a string of the format (Literal1|Literal2|...)
*/
public function __toString(): string
{
// TODO multi conflict?
$result = $this->isDisabled() ? 'disabled(multi(' : '(multi(';
foreach ($this->literals as $i => $literal) {
if ($i !== 0) {
$result .= '|';
}
$result .= $literal;
}
$result .= '))';
return $result;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/Request.php | src/Composer/DependencyResolver/Request.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver;
use Composer\Package\BasePackage;
use Composer\Package\PackageInterface;
use Composer\Repository\LockArrayRepository;
use Composer\Semver\Constraint\ConstraintInterface;
use Composer\Semver\Constraint\MatchAllConstraint;
/**
* @author Nils Adermann <naderman@naderman.de>
*/
class Request
{
/**
* Identifies a partial update for listed packages only, all dependencies will remain at locked versions
*/
public const UPDATE_ONLY_LISTED = 0;
/**
* Identifies a partial update for listed packages and recursively all their dependencies, however dependencies
* also directly required by the root composer.json and their dependencies will remain at the locked version.
*/
public const UPDATE_LISTED_WITH_TRANSITIVE_DEPS_NO_ROOT_REQUIRE = 1;
/**
* Identifies a partial update for listed packages and recursively all their dependencies, even dependencies
* also directly required by the root composer.json will be updated.
*/
public const UPDATE_LISTED_WITH_TRANSITIVE_DEPS = 2;
/** @var ?LockArrayRepository */
protected $lockedRepository;
/** @var array<string, ConstraintInterface> */
protected $requires = [];
/** @var array<string, BasePackage> */
protected $fixedPackages = [];
/** @var array<string, BasePackage> */
protected $lockedPackages = [];
/** @var array<string, BasePackage> */
protected $fixedLockedPackages = [];
/** @var array<string> */
protected $updateAllowList = [];
/** @var false|self::UPDATE_* */
protected $updateAllowTransitiveDependencies = false;
/** @var non-empty-list<string>|null */
private $restrictedPackages = null;
public function __construct(?LockArrayRepository $lockedRepository = null)
{
$this->lockedRepository = $lockedRepository;
}
public function requireName(string $packageName, ?ConstraintInterface $constraint = null): void
{
$packageName = strtolower($packageName);
if ($constraint === null) {
$constraint = new MatchAllConstraint();
}
if (isset($this->requires[$packageName])) {
throw new \LogicException('Overwriting requires seems like a bug ('.$packageName.' '.$this->requires[$packageName]->getPrettyString().' => '.$constraint->getPrettyString().', check why it is happening, might be a root alias');
}
$this->requires[$packageName] = $constraint;
}
/**
* Mark a package as currently present and having to remain installed
*
* This is used for platform packages which cannot be modified by Composer. A rule enforcing their installation is
* generated for dependency resolution. Partial updates with dependencies cannot in any way modify these packages.
*/
public function fixPackage(BasePackage $package): void
{
$this->fixedPackages[spl_object_hash($package)] = $package;
}
/**
* Mark a package as locked to a specific version but removable
*
* This is used for lock file packages which need to be treated similar to fixed packages by the pool builder in
* that by default they should really only have the currently present version loaded and no remote alternatives.
*
* However unlike fixed packages there will not be a special rule enforcing their installation for the solver, so
* if nothing requires these packages they will be removed. Additionally in a partial update these packages can be
* unlocked, meaning other versions can be installed if explicitly requested as part of the update.
*/
public function lockPackage(BasePackage $package): void
{
$this->lockedPackages[spl_object_hash($package)] = $package;
}
/**
* Marks a locked package fixed. So it's treated irremovable like a platform package.
*
* This is necessary for the composer install step which verifies the lock file integrity and should not allow
* removal of any packages. At the same time lock packages there cannot simply be marked fixed, as error reporting
* would then report them as platform packages, so this still marks them as locked packages at the same time.
*/
public function fixLockedPackage(BasePackage $package): void
{
$this->fixedPackages[spl_object_hash($package)] = $package;
$this->fixedLockedPackages[spl_object_hash($package)] = $package;
}
public function unlockPackage(BasePackage $package): void
{
unset($this->lockedPackages[spl_object_hash($package)]);
}
/**
* @param array<string> $updateAllowList
* @param false|self::UPDATE_* $updateAllowTransitiveDependencies
*/
public function setUpdateAllowList(array $updateAllowList, $updateAllowTransitiveDependencies): void
{
$this->updateAllowList = $updateAllowList;
$this->updateAllowTransitiveDependencies = $updateAllowTransitiveDependencies;
}
/**
* @return array<string>
*/
public function getUpdateAllowList(): array
{
return $this->updateAllowList;
}
public function getUpdateAllowTransitiveDependencies(): bool
{
return $this->updateAllowTransitiveDependencies !== self::UPDATE_ONLY_LISTED;
}
public function getUpdateAllowTransitiveRootDependencies(): bool
{
return $this->updateAllowTransitiveDependencies === self::UPDATE_LISTED_WITH_TRANSITIVE_DEPS;
}
/**
* @return array<string, ConstraintInterface>
*/
public function getRequires(): array
{
return $this->requires;
}
/**
* @return array<string, BasePackage>
*/
public function getFixedPackages(): array
{
return $this->fixedPackages;
}
public function isFixedPackage(BasePackage $package): bool
{
return isset($this->fixedPackages[spl_object_hash($package)]);
}
/**
* @return array<string, BasePackage>
*/
public function getLockedPackages(): array
{
return $this->lockedPackages;
}
public function isLockedPackage(PackageInterface $package): bool
{
return isset($this->lockedPackages[spl_object_hash($package)]) || isset($this->fixedLockedPackages[spl_object_hash($package)]);
}
/**
* @return array<string, BasePackage>
*/
public function getFixedOrLockedPackages(): array
{
return array_merge($this->fixedPackages, $this->lockedPackages);
}
/**
* @return ($packageIds is true ? array<int, BasePackage> : array<string, BasePackage>)
*
* @TODO look into removing the packageIds option, the only place true is used
* is for the installed map in the solver problems.
* Some locked packages may not be in the pool,
* so they have a package->id of -1
*/
public function getPresentMap(bool $packageIds = false): array
{
$presentMap = [];
if ($this->lockedRepository !== null) {
foreach ($this->lockedRepository->getPackages() as $package) {
$presentMap[$packageIds ? $package->getId() : spl_object_hash($package)] = $package;
}
}
foreach ($this->fixedPackages as $package) {
$presentMap[$packageIds ? $package->getId() : spl_object_hash($package)] = $package;
}
return $presentMap;
}
/**
* @return array<int, BasePackage>
*/
public function getFixedPackagesMap(): array
{
$fixedPackagesMap = [];
foreach ($this->fixedPackages as $package) {
$fixedPackagesMap[$package->getId()] = $package;
}
return $fixedPackagesMap;
}
public function getLockedRepository(): ?LockArrayRepository
{
return $this->lockedRepository;
}
/**
* Restricts the pool builder from loading other packages than those listed here
*
* @param non-empty-list<string> $names
*/
public function restrictPackages(array $names): void
{
$this->restrictedPackages = $names;
}
/**
* @return list<string>
*/
public function getRestrictedPackages(): ?array
{
return $this->restrictedPackages;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/Solver.php | src/Composer/DependencyResolver/Solver.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver;
use Composer\Filter\PlatformRequirementFilter\IgnoreListPlatformRequirementFilter;
use Composer\Filter\PlatformRequirementFilter\PlatformRequirementFilterFactory;
use Composer\Filter\PlatformRequirementFilter\PlatformRequirementFilterInterface;
use Composer\IO\IOInterface;
use Composer\Package\BasePackage;
/**
* @author Nils Adermann <naderman@naderman.de>
*/
class Solver
{
private const BRANCH_LITERALS = 0;
private const BRANCH_LEVEL = 1;
/** @var PolicyInterface */
protected $policy;
/** @var Pool */
protected $pool;
/** @var RuleSet */
protected $rules;
/** @var RuleWatchGraph */
protected $watchGraph;
/** @var Decisions */
protected $decisions;
/** @var BasePackage[] */
protected $fixedMap;
/** @var int */
protected $propagateIndex;
/** @var array<int, array{array<int, int>, int}> */
protected $branches = [];
/** @var Problem[] */
protected $problems = [];
/** @var array<Rule[]> */
protected $learnedPool = [];
/** @var array<string, int> */
protected $learnedWhy = [];
/** @var bool */
public $testFlagLearnedPositiveLiteral = false;
/** @var IOInterface */
protected $io;
public function __construct(PolicyInterface $policy, Pool $pool, IOInterface $io)
{
$this->io = $io;
$this->policy = $policy;
$this->pool = $pool;
}
public function getRuleSetSize(): int
{
return \count($this->rules);
}
public function getPool(): Pool
{
return $this->pool;
}
// aka solver_makeruledecisions
private function makeAssertionRuleDecisions(): void
{
$decisionStart = \count($this->decisions) - 1;
$rulesCount = \count($this->rules);
for ($ruleIndex = 0; $ruleIndex < $rulesCount; $ruleIndex++) {
$rule = $this->rules->ruleById[$ruleIndex];
if (!$rule->isAssertion() || $rule->isDisabled()) {
continue;
}
$literals = $rule->getLiterals();
$literal = $literals[0];
if (!$this->decisions->decided($literal)) {
$this->decisions->decide($literal, 1, $rule);
continue;
}
if ($this->decisions->satisfy($literal)) {
continue;
}
// found a conflict
if (RuleSet::TYPE_LEARNED === $rule->getType()) {
$rule->disable();
continue;
}
$conflict = $this->decisions->decisionRule($literal);
if (RuleSet::TYPE_PACKAGE === $conflict->getType()) {
$problem = new Problem();
$problem->addRule($rule);
$problem->addRule($conflict);
$rule->disable();
$this->problems[] = $problem;
continue;
}
// conflict with another root require/fixed package
$problem = new Problem();
$problem->addRule($rule);
$problem->addRule($conflict);
// push all of our rules (can only be root require/fixed package rules)
// asserting this literal on the problem stack
foreach ($this->rules->getIteratorFor(RuleSet::TYPE_REQUEST) as $assertRule) {
if ($assertRule->isDisabled() || !$assertRule->isAssertion()) {
continue;
}
$assertRuleLiterals = $assertRule->getLiterals();
$assertRuleLiteral = $assertRuleLiterals[0];
if (abs($literal) !== abs($assertRuleLiteral)) {
continue;
}
$problem->addRule($assertRule);
$assertRule->disable();
}
$this->problems[] = $problem;
$this->decisions->resetToOffset($decisionStart);
$ruleIndex = -1;
}
}
protected function setupFixedMap(Request $request): void
{
$this->fixedMap = [];
foreach ($request->getFixedPackages() as $package) {
$this->fixedMap[$package->id] = $package;
}
}
protected function checkForRootRequireProblems(Request $request, PlatformRequirementFilterInterface $platformRequirementFilter): void
{
foreach ($request->getRequires() as $packageName => $constraint) {
if ($platformRequirementFilter->isIgnored($packageName)) {
continue;
} elseif ($platformRequirementFilter instanceof IgnoreListPlatformRequirementFilter) {
$constraint = $platformRequirementFilter->filterConstraint($packageName, $constraint);
}
if (0 === \count($this->pool->whatProvides($packageName, $constraint))) {
$problem = new Problem();
$problem->addRule(new GenericRule([], Rule::RULE_ROOT_REQUIRE, ['packageName' => $packageName, 'constraint' => $constraint]));
$this->problems[] = $problem;
}
}
}
public function solve(Request $request, ?PlatformRequirementFilterInterface $platformRequirementFilter = null): LockTransaction
{
$platformRequirementFilter = $platformRequirementFilter ?? PlatformRequirementFilterFactory::ignoreNothing();
$this->setupFixedMap($request);
$this->io->writeError('Generating rules', true, IOInterface::DEBUG);
$ruleSetGenerator = new RuleSetGenerator($this->policy, $this->pool);
$this->rules = $ruleSetGenerator->getRulesFor($request, $platformRequirementFilter);
unset($ruleSetGenerator);
$this->checkForRootRequireProblems($request, $platformRequirementFilter);
$this->decisions = new Decisions($this->pool);
$this->watchGraph = new RuleWatchGraph;
foreach ($this->rules as $rule) {
$this->watchGraph->insert(new RuleWatchNode($rule));
}
/* make decisions based on root require/fix assertions */
$this->makeAssertionRuleDecisions();
$this->io->writeError('Resolving dependencies through SAT', true, IOInterface::DEBUG);
$before = microtime(true);
$this->runSat();
$this->io->writeError('', true, IOInterface::DEBUG);
$this->io->writeError(sprintf('Dependency resolution completed in %.3f seconds', microtime(true) - $before), true, IOInterface::VERBOSE);
if (\count($this->problems) > 0) {
throw new SolverProblemsException($this->problems, $this->learnedPool);
}
return new LockTransaction($this->pool, $request->getPresentMap(), $request->getFixedPackagesMap(), $this->decisions);
}
/**
* Makes a decision and propagates it to all rules.
*
* Evaluates each term affected by the decision (linked through watches)
* If we find unit rules we make new decisions based on them
*
* @return Rule|null A rule on conflict, otherwise null.
*/
protected function propagate(int $level): ?Rule
{
while ($this->decisions->validOffset($this->propagateIndex)) {
$decision = $this->decisions->atOffset($this->propagateIndex);
$conflict = $this->watchGraph->propagateLiteral(
$decision[Decisions::DECISION_LITERAL],
$level,
$this->decisions
);
$this->propagateIndex++;
if ($conflict !== null) {
return $conflict;
}
}
return null;
}
/**
* Reverts a decision at the given level.
*/
private function revert(int $level): void
{
while (!$this->decisions->isEmpty()) {
$literal = $this->decisions->lastLiteral();
if ($this->decisions->undecided($literal)) {
break;
}
$decisionLevel = $this->decisions->decisionLevel($literal);
if ($decisionLevel <= $level) {
break;
}
$this->decisions->revertLast();
$this->propagateIndex = \count($this->decisions);
}
while (\count($this->branches) > 0 && $this->branches[\count($this->branches) - 1][self::BRANCH_LEVEL] >= $level) {
array_pop($this->branches);
}
}
/**
* setpropagatelearn
*
* add free decision (a positive literal) to decision queue
* increase level and propagate decision
* return if no conflict.
*
* in conflict case, analyze conflict rule, add resulting
* rule to learnt rule set, make decision from learnt
* rule (always unit) and re-propagate.
*
* returns the new solver level or 0 if unsolvable
*/
private function setPropagateLearn(int $level, int $literal, Rule $rule): int
{
$level++;
$this->decisions->decide($literal, $level, $rule);
while (true) {
$rule = $this->propagate($level);
if (null === $rule) {
break;
}
if ($level === 1) {
$this->analyzeUnsolvable($rule);
return 0;
}
// conflict
[$learnLiteral, $newLevel, $newRule, $why] = $this->analyze($level, $rule);
if ($newLevel <= 0 || $newLevel >= $level) {
throw new SolverBugException(
"Trying to revert to invalid level ".$newLevel." from level ".$level."."
);
}
$level = $newLevel;
$this->revert($level);
$this->rules->add($newRule, RuleSet::TYPE_LEARNED);
$this->learnedWhy[spl_object_hash($newRule)] = $why;
$ruleNode = new RuleWatchNode($newRule);
$ruleNode->watch2OnHighest($this->decisions);
$this->watchGraph->insert($ruleNode);
$this->decisions->decide($learnLiteral, $level, $newRule);
}
return $level;
}
/**
* @param non-empty-list<int> $decisionQueue
*/
private function selectAndInstall(int $level, array $decisionQueue, Rule $rule): int
{
// choose best package to install from decisionQueue
$literals = $this->policy->selectPreferredPackages($this->pool, $decisionQueue, $rule->getRequiredPackage());
$selectedLiteral = array_shift($literals);
// if there are multiple candidates, then branch
if (\count($literals) > 0) {
$this->branches[] = [$literals, $level];
}
return $this->setPropagateLearn($level, $selectedLiteral, $rule);
}
/**
* @return array{int, int, GenericRule, int}
*/
protected function analyze(int $level, Rule $rule): array
{
$analyzedRule = $rule;
$ruleLevel = 1;
$num = 0;
$l1num = 0;
$seen = [];
$learnedLiteral = null;
$otherLearnedLiterals = [];
$decisionId = \count($this->decisions);
$this->learnedPool[] = [];
while (true) {
$this->learnedPool[\count($this->learnedPool) - 1][] = $rule;
foreach ($rule->getLiterals() as $literal) {
// multiconflictrule is really a bunch of rules in one, so some may not have finished propagating yet
if ($rule instanceof MultiConflictRule && !$this->decisions->decided($literal)) {
continue;
}
// skip the one true literal
if ($this->decisions->satisfy($literal)) {
continue;
}
if (isset($seen[abs($literal)])) {
continue;
}
$seen[abs($literal)] = true;
$l = $this->decisions->decisionLevel($literal);
if (1 === $l) {
$l1num++;
} elseif ($level === $l) {
$num++;
} else {
// not level1 or conflict level, add to new rule
$otherLearnedLiterals[] = $literal;
if ($l > $ruleLevel) {
$ruleLevel = $l;
}
}
}
unset($literal);
$l1retry = true;
while ($l1retry) {
$l1retry = false;
if (0 === $num && 0 === --$l1num) {
// all level 1 literals done
break 2;
}
while (true) {
if ($decisionId <= 0) {
throw new SolverBugException(
"Reached invalid decision id $decisionId while looking through $rule for a literal present in the analyzed rule $analyzedRule."
);
}
$decisionId--;
$decision = $this->decisions->atOffset($decisionId);
$literal = $decision[Decisions::DECISION_LITERAL];
if (isset($seen[abs($literal)])) {
break;
}
}
unset($seen[abs($literal)]);
if (0 !== $num && 0 === --$num) {
if ($literal < 0) {
$this->testFlagLearnedPositiveLiteral = true;
}
$learnedLiteral = -$literal;
if (0 === $l1num) {
break 2;
}
foreach ($otherLearnedLiterals as $otherLiteral) {
unset($seen[abs($otherLiteral)]);
}
// only level 1 marks left
$l1num++;
$l1retry = true;
} else {
$decision = $this->decisions->atOffset($decisionId);
$rule = $decision[Decisions::DECISION_REASON];
if ($rule instanceof MultiConflictRule) {
// there is only ever exactly one positive decision in a MultiConflictRule
foreach ($rule->getLiterals() as $ruleLiteral) {
if (!isset($seen[abs($ruleLiteral)]) && $this->decisions->satisfy(-$ruleLiteral)) {
$this->learnedPool[\count($this->learnedPool) - 1][] = $rule;
$l = $this->decisions->decisionLevel($ruleLiteral);
if (1 === $l) {
$l1num++;
} elseif ($level === $l) {
$num++;
} else {
// not level1 or conflict level, add to new rule
$otherLearnedLiterals[] = $ruleLiteral;
if ($l > $ruleLevel) {
$ruleLevel = $l;
}
}
$seen[abs($ruleLiteral)] = true;
break;
}
}
$l1retry = true;
}
}
}
$decision = $this->decisions->atOffset($decisionId);
$rule = $decision[Decisions::DECISION_REASON];
}
$why = \count($this->learnedPool) - 1;
if (null === $learnedLiteral) {
throw new SolverBugException(
"Did not find a learnable literal in analyzed rule $analyzedRule."
);
}
array_unshift($otherLearnedLiterals, $learnedLiteral);
$newRule = new GenericRule($otherLearnedLiterals, Rule::RULE_LEARNED, $why);
return [$learnedLiteral, $ruleLevel, $newRule, $why];
}
/**
* @param array<string, true> $ruleSeen
*/
private function analyzeUnsolvableRule(Problem $problem, Rule $conflictRule, array &$ruleSeen): void
{
$why = spl_object_hash($conflictRule);
$ruleSeen[$why] = true;
if ($conflictRule->getType() === RuleSet::TYPE_LEARNED) {
$learnedWhy = $this->learnedWhy[$why];
$problemRules = $this->learnedPool[$learnedWhy];
foreach ($problemRules as $problemRule) {
if (!isset($ruleSeen[spl_object_hash($problemRule)])) {
$this->analyzeUnsolvableRule($problem, $problemRule, $ruleSeen);
}
}
return;
}
if ($conflictRule->getType() === RuleSet::TYPE_PACKAGE) {
// package rules cannot be part of a problem
return;
}
$problem->nextSection();
$problem->addRule($conflictRule);
}
private function analyzeUnsolvable(Rule $conflictRule): void
{
$problem = new Problem();
$problem->addRule($conflictRule);
$ruleSeen = [];
$this->analyzeUnsolvableRule($problem, $conflictRule, $ruleSeen);
$this->problems[] = $problem;
$seen = [];
$literals = $conflictRule->getLiterals();
foreach ($literals as $literal) {
// skip the one true literal
if ($this->decisions->satisfy($literal)) {
continue;
}
$seen[abs($literal)] = true;
}
foreach ($this->decisions as $decision) {
$decisionLiteral = $decision[Decisions::DECISION_LITERAL];
// skip literals that are not in this rule
if (!isset($seen[abs($decisionLiteral)])) {
continue;
}
$why = $decision[Decisions::DECISION_REASON];
$problem->addRule($why);
$this->analyzeUnsolvableRule($problem, $why, $ruleSeen);
$literals = $why->getLiterals();
foreach ($literals as $literal) {
// skip the one true literal
if ($this->decisions->satisfy($literal)) {
continue;
}
$seen[abs($literal)] = true;
}
}
}
private function runSat(): void
{
$this->propagateIndex = 0;
/*
* here's the main loop:
* 1) propagate new decisions (only needed once)
* 2) fulfill root requires/fixed packages
* 3) fulfill all unresolved rules
* 4) minimalize solution if we had choices
* if we encounter a problem, we rewind to a safe level and restart
* with step 1
*/
$level = 1;
$systemLevel = $level + 1;
while (true) {
if (1 === $level) {
$conflictRule = $this->propagate($level);
if (null !== $conflictRule) {
$this->analyzeUnsolvable($conflictRule);
return;
}
}
// handle root require/fixed package rules
if ($level < $systemLevel) {
$iterator = $this->rules->getIteratorFor(RuleSet::TYPE_REQUEST);
foreach ($iterator as $rule) {
if ($rule->isEnabled()) {
$decisionQueue = [];
$noneSatisfied = true;
foreach ($rule->getLiterals() as $literal) {
if ($this->decisions->satisfy($literal)) {
$noneSatisfied = false;
break;
}
if ($literal > 0 && $this->decisions->undecided($literal)) {
$decisionQueue[] = $literal;
}
}
if ($noneSatisfied && \count($decisionQueue) > 0) {
// if any of the options in the decision queue are fixed, only use those
$prunedQueue = [];
foreach ($decisionQueue as $literal) {
if (isset($this->fixedMap[abs($literal)])) {
$prunedQueue[] = $literal;
}
}
if (\count($prunedQueue) > 0) {
$decisionQueue = $prunedQueue;
}
}
if ($noneSatisfied && \count($decisionQueue) > 0) {
$oLevel = $level;
$level = $this->selectAndInstall($level, $decisionQueue, $rule);
if (0 === $level) {
return;
}
if ($level <= $oLevel) {
break;
}
}
}
}
$systemLevel = $level + 1;
// root requires/fixed packages left
$iterator->next();
if ($iterator->valid()) {
continue;
}
}
if ($level < $systemLevel) {
$systemLevel = $level;
}
$rulesCount = \count($this->rules);
$pass = 1;
$this->io->writeError('Looking at all rules.', true, IOInterface::DEBUG);
for ($i = 0, $n = 0; $n < $rulesCount; $i++, $n++) {
if ($i === $rulesCount) {
if (1 === $pass) {
$this->io->writeError("Something's changed, looking at all rules again (pass #$pass)", false, IOInterface::DEBUG);
} else {
$this->io->overwriteError("Something's changed, looking at all rules again (pass #$pass)", false, null, IOInterface::DEBUG);
}
$i = 0;
$pass++;
}
$rule = $this->rules->ruleById[$i];
$literals = $rule->getLiterals();
if ($rule->isDisabled()) {
continue;
}
$decisionQueue = [];
// make sure that
// * all negative literals are installed
// * no positive literal is installed
// i.e. the rule is not fulfilled and we
// just need to decide on the positive literals
//
foreach ($literals as $literal) {
if ($literal <= 0) {
if (!$this->decisions->decidedInstall($literal)) {
continue 2; // next rule
}
} else {
if ($this->decisions->decidedInstall($literal)) {
continue 2; // next rule
}
if ($this->decisions->undecided($literal)) {
$decisionQueue[] = $literal;
}
}
}
// need to have at least 2 item to pick from
if (\count($decisionQueue) < 2) {
continue;
}
$level = $this->selectAndInstall($level, $decisionQueue, $rule);
if (0 === $level) {
return;
}
// something changed, so look at all rules again
$rulesCount = \count($this->rules);
$n = -1;
}
if ($level < $systemLevel) {
continue;
}
// minimization step
if (\count($this->branches) > 0) {
$lastLiteral = null;
$lastLevel = null;
$lastBranchIndex = 0;
$lastBranchOffset = 0;
for ($i = \count($this->branches) - 1; $i >= 0; $i--) {
[$literals, $l] = $this->branches[$i];
foreach ($literals as $offset => $literal) {
if ($literal > 0 && $this->decisions->decisionLevel($literal) > $l + 1) {
$lastLiteral = $literal;
$lastBranchIndex = $i;
$lastBranchOffset = $offset;
$lastLevel = $l;
}
}
}
if ($lastLiteral !== null) {
assert($lastLevel !== null);
unset($this->branches[$lastBranchIndex][self::BRANCH_LITERALS][$lastBranchOffset]);
$level = $lastLevel;
$this->revert($level);
$why = $this->decisions->lastReason();
$level = $this->setPropagateLearn($level, $lastLiteral, $why);
if ($level === 0) {
return;
}
continue;
}
}
break;
}
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/PolicyInterface.php | src/Composer/DependencyResolver/PolicyInterface.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver;
use Composer\Package\PackageInterface;
use Composer\Semver\Constraint\Constraint;
/**
* @author Nils Adermann <naderman@naderman.de>
*/
interface PolicyInterface
{
/**
* @phpstan-param Constraint::STR_OP_* $operator
*/
public function versionCompare(PackageInterface $a, PackageInterface $b, string $operator): bool;
/**
* @param non-empty-list<int> $literals
* @return non-empty-list<int>
*/
public function selectPreferredPackages(Pool $pool, array $literals, ?string $requiredPackage = null): array;
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/SolverBugException.php | src/Composer/DependencyResolver/SolverBugException.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver;
/**
* @author Nils Adermann <naderman@naderman.de>
*/
class SolverBugException extends \RuntimeException
{
public function __construct(string $message)
{
parent::__construct(
$message."\nThis exception was most likely caused by a bug in Composer.\n".
"Please report the command you ran, the exact error you received, and your composer.json on https://github.com/composer/composer/issues - thank you!\n"
);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/RuleWatchNode.php | src/Composer/DependencyResolver/RuleWatchNode.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver;
/**
* Wrapper around a Rule which keeps track of the two literals it watches
*
* Used by RuleWatchGraph to store rules in two RuleWatchChains.
*
* @author Nils Adermann <naderman@naderman.de>
*/
class RuleWatchNode
{
/** @var int */
public $watch1;
/** @var int */
public $watch2;
/** @var Rule */
protected $rule;
/**
* Creates a new node watching the first and second literals of the rule.
*
* @param Rule $rule The rule to wrap
*/
public function __construct(Rule $rule)
{
$this->rule = $rule;
$literals = $rule->getLiterals();
$literalCount = \count($literals);
$this->watch1 = $literalCount > 0 ? $literals[0] : 0;
$this->watch2 = $literalCount > 1 ? $literals[1] : 0;
}
/**
* Places the second watch on the rule's literal, decided at the highest level
*
* Useful for learned rules where the literal for the highest rule is most
* likely to quickly lead to further decisions.
*
* @param Decisions $decisions The decisions made so far by the solver
*/
public function watch2OnHighest(Decisions $decisions): void
{
$literals = $this->rule->getLiterals();
// if there are only 2 elements, both are being watched anyway
if (\count($literals) < 3 || $this->rule instanceof MultiConflictRule) {
return;
}
$watchLevel = 0;
foreach ($literals as $literal) {
$level = $decisions->decisionLevel($literal);
if ($level > $watchLevel) {
$this->watch2 = $literal;
$watchLevel = $level;
}
}
}
/**
* Returns the rule this node wraps
*/
public function getRule(): Rule
{
return $this->rule;
}
/**
* Given one watched literal, this method returns the other watched literal
*
* @param int $literal The watched literal that should not be returned
* @return int A literal
*/
public function getOtherWatch(int $literal): int
{
if ($this->watch1 === $literal) {
return $this->watch2;
}
return $this->watch1;
}
/**
* Moves a watch from one literal to another
*
* @param int $from The previously watched literal
* @param int $to The literal to be watched now
*/
public function moveWatch(int $from, int $to): void
{
if ($this->watch1 === $from) {
$this->watch1 = $to;
} else {
$this->watch2 = $to;
}
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/RuleSet.php | src/Composer/DependencyResolver/RuleSet.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver;
use Composer\Repository\RepositorySet;
/**
* @author Nils Adermann <naderman@naderman.de>
* @implements \IteratorAggregate<Rule>
* @internal
* @final
*/
class RuleSet implements \IteratorAggregate, \Countable
{
// highest priority => lowest number
public const TYPE_PACKAGE = 0;
public const TYPE_REQUEST = 1;
public const TYPE_LEARNED = 4;
/**
* READ-ONLY: Lookup table for rule id to rule object
*
* @var array<int, Rule>
*/
public $ruleById = [];
public const TYPES = [
self::TYPE_PACKAGE => 'PACKAGE',
self::TYPE_REQUEST => 'REQUEST',
self::TYPE_LEARNED => 'LEARNED',
];
/** @var array<self::TYPE_*, Rule[]> */
protected $rules;
/** @var 0|positive-int */
protected $nextRuleId = 0;
/** @var array<int|string, Rule|Rule[]> */
protected $rulesByHash = [];
public function __construct()
{
foreach ($this->getTypes() as $type) {
$this->rules[$type] = [];
}
}
/**
* @param self::TYPE_* $type
*/
public function add(Rule $rule, $type): void
{
if (!isset(self::TYPES[$type])) {
throw new \OutOfBoundsException('Unknown rule type: ' . $type);
}
$hash = $rule->getHash();
// Do not add if rule already exists
if (isset($this->rulesByHash[$hash])) {
$potentialDuplicates = $this->rulesByHash[$hash];
if (\is_array($potentialDuplicates)) {
foreach ($potentialDuplicates as $potentialDuplicate) {
if ($rule->equals($potentialDuplicate)) {
return;
}
}
} else {
if ($rule->equals($potentialDuplicates)) {
return;
}
}
}
if (!isset($this->rules[$type])) {
$this->rules[$type] = [];
}
$this->rules[$type][] = $rule;
$this->ruleById[$this->nextRuleId] = $rule;
$rule->setType($type);
$this->nextRuleId++;
if (!isset($this->rulesByHash[$hash])) {
$this->rulesByHash[$hash] = $rule;
} elseif (\is_array($this->rulesByHash[$hash])) {
$this->rulesByHash[$hash][] = $rule;
} else {
$originalRule = $this->rulesByHash[$hash];
$this->rulesByHash[$hash] = [$originalRule, $rule];
}
}
public function count(): int
{
return $this->nextRuleId;
}
public function ruleById(int $id): Rule
{
return $this->ruleById[$id];
}
/** @return array<self::TYPE_*, Rule[]> */
public function getRules(): array
{
return $this->rules;
}
public function getIterator(): RuleSetIterator
{
return new RuleSetIterator($this->getRules());
}
/**
* @param self::TYPE_*|array<self::TYPE_*> $types
*/
public function getIteratorFor($types): RuleSetIterator
{
if (!\is_array($types)) {
$types = [$types];
}
$allRules = $this->getRules();
/** @var array<self::TYPE_*, Rule[]> $rules */
$rules = [];
foreach ($types as $type) {
$rules[$type] = $allRules[$type];
}
return new RuleSetIterator($rules);
}
/**
* @param array<self::TYPE_*>|self::TYPE_* $types
*/
public function getIteratorWithout($types): RuleSetIterator
{
if (!\is_array($types)) {
$types = [$types];
}
$rules = $this->getRules();
foreach ($types as $type) {
unset($rules[$type]);
}
return new RuleSetIterator($rules);
}
/**
* @return array{self::TYPE_PACKAGE, self::TYPE_REQUEST, self::TYPE_LEARNED}
*/
public function getTypes(): array
{
$types = self::TYPES;
return array_keys($types);
}
public function getPrettyString(?RepositorySet $repositorySet = null, ?Request $request = null, ?Pool $pool = null, bool $isVerbose = false): string
{
$string = "\n";
foreach ($this->rules as $type => $rules) {
$string .= str_pad(self::TYPES[$type], 8, ' ') . ": ";
foreach ($rules as $rule) {
$string .= ($repositorySet !== null && $request !== null && $pool !== null ? $rule->getPrettyString($repositorySet, $request, $pool, $isVerbose) : $rule)."\n";
}
$string .= "\n\n";
}
return $string;
}
public function __toString(): string
{
return $this->getPrettyString();
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/SecurityAdvisoryPoolFilter.php | src/Composer/DependencyResolver/SecurityAdvisoryPoolFilter.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver;
use Composer\Advisory\AuditConfig;
use Composer\Advisory\Auditor;
use Composer\Advisory\PartialSecurityAdvisory;
use Composer\Advisory\SecurityAdvisory;
use Composer\Package\PackageInterface;
use Composer\Package\RootPackageInterface;
use Composer\Repository\PlatformRepository;
use Composer\Repository\RepositoryInterface;
use Composer\Repository\RepositorySet;
use Composer\Semver\Constraint\Constraint;
/**
* @internal
*/
class SecurityAdvisoryPoolFilter
{
/** @var Auditor */
private $auditor;
/** @var AuditConfig $auditConfig */
private $auditConfig;
public function __construct(
Auditor $auditor,
AuditConfig $auditConfig
) {
$this->auditor = $auditor;
$this->auditConfig = $auditConfig;
}
/**
* @param array<RepositoryInterface> $repositories
*/
public function filter(Pool $pool, array $repositories, Request $request): Pool
{
if (!$this->auditConfig->blockInsecure) {
return $pool;
}
$repoSet = new RepositorySet();
foreach ($repositories as $repo) {
$repoSet->addRepository($repo);
}
$packagesForAdvisories = [];
foreach ($pool->getPackages() as $package) {
if (!$package instanceof RootPackageInterface && !PlatformRepository::isPlatformPackage($package->getName()) && !$request->isLockedPackage($package)) {
$packagesForAdvisories[] = $package;
}
}
$allAdvisories = $repoSet->getMatchingSecurityAdvisories($packagesForAdvisories, true, true);
if ($this->auditor->needsCompleteAdvisoryLoad($allAdvisories['advisories'], $this->auditConfig->ignoreListForBlocking)) {
$allAdvisories = $repoSet->getMatchingSecurityAdvisories($packagesForAdvisories, false, true);
}
$advisoryMap = $this->auditor->processAdvisories($allAdvisories['advisories'], $this->auditConfig->ignoreListForBlocking, $this->auditConfig->ignoreSeverityForBlocking)['advisories'];
$packages = [];
$securityRemovedVersions = [];
$abandonedRemovedVersions = [];
foreach ($pool->getPackages() as $package) {
if ($this->auditConfig->blockAbandoned && count($this->auditor->filterAbandonedPackages([$package], $this->auditConfig->ignoreAbandonedForBlocking)) !== 0) {
foreach ($package->getNames(false) as $packageName) {
$abandonedRemovedVersions[$packageName][$package->getVersion()] = $package->getPrettyVersion();
}
continue;
}
$matchingAdvisories = $this->getMatchingAdvisories($package, $advisoryMap);
if (count($matchingAdvisories) > 0) {
foreach ($package->getNames(false) as $packageName) {
$securityRemovedVersions[$packageName][$package->getVersion()] = $matchingAdvisories;
}
continue;
}
$packages[] = $package;
}
return new Pool($packages, $pool->getUnacceptableFixedOrLockedPackages(), $pool->getAllRemovedVersions(), $pool->getAllRemovedVersionsByPackage(), $securityRemovedVersions, $abandonedRemovedVersions);
}
/**
* @param array<string, array<PartialSecurityAdvisory|SecurityAdvisory>> $advisoryMap
* @return list<PartialSecurityAdvisory|SecurityAdvisory>
*/
private function getMatchingAdvisories(PackageInterface $package, array $advisoryMap): array
{
if ($package->isDev()) {
return [];
}
$matchingAdvisories = [];
foreach ($package->getNames(false) as $packageName) {
if (!isset($advisoryMap[$packageName])) {
continue;
}
$packageConstraint = new Constraint(Constraint::STR_OP_EQ, $package->getVersion());
foreach ($advisoryMap[$packageName] as $advisory) {
if ($advisory->affectedVersions->matches($packageConstraint)) {
$matchingAdvisories[] = $advisory;
}
}
}
return $matchingAdvisories;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/RuleSetIterator.php | src/Composer/DependencyResolver/RuleSetIterator.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver;
/**
* @author Nils Adermann <naderman@naderman.de>
* @implements \Iterator<RuleSet::TYPE_*|-1, Rule>
*/
class RuleSetIterator implements \Iterator
{
/** @var array<RuleSet::TYPE_*, Rule[]> */
protected $rules;
/** @var array<RuleSet::TYPE_*> */
protected $types;
/** @var int */
protected $currentOffset;
/** @var RuleSet::TYPE_*|-1 */
protected $currentType;
/** @var int */
protected $currentTypeOffset;
/**
* @param array<RuleSet::TYPE_*, Rule[]> $rules
*/
public function __construct(array $rules)
{
$this->rules = $rules;
$this->types = array_keys($rules);
sort($this->types);
$this->rewind();
}
public function current(): Rule
{
return $this->rules[$this->currentType][$this->currentOffset];
}
/**
* @return RuleSet::TYPE_*|-1
*/
public function key(): int
{
return $this->currentType;
}
public function next(): void
{
$this->currentOffset++;
if (!isset($this->rules[$this->currentType])) {
return;
}
if ($this->currentOffset >= \count($this->rules[$this->currentType])) {
$this->currentOffset = 0;
do {
$this->currentTypeOffset++;
if (!isset($this->types[$this->currentTypeOffset])) {
$this->currentType = -1;
break;
}
$this->currentType = $this->types[$this->currentTypeOffset];
} while (0 === \count($this->rules[$this->currentType]));
}
}
public function rewind(): void
{
$this->currentOffset = 0;
$this->currentTypeOffset = -1;
$this->currentType = -1;
do {
$this->currentTypeOffset++;
if (!isset($this->types[$this->currentTypeOffset])) {
$this->currentType = -1;
break;
}
$this->currentType = $this->types[$this->currentTypeOffset];
} while (0 === \count($this->rules[$this->currentType]));
}
public function valid(): bool
{
return isset($this->rules[$this->currentType], $this->rules[$this->currentType][$this->currentOffset]);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/DefaultPolicy.php | src/Composer/DependencyResolver/DefaultPolicy.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver;
use Composer\Package\AliasPackage;
use Composer\Package\BasePackage;
use Composer\Package\PackageInterface;
use Composer\Semver\CompilingMatcher;
use Composer\Semver\Constraint\Constraint;
use Composer\Util\Platform;
/**
* @author Nils Adermann <naderman@naderman.de>
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class DefaultPolicy implements PolicyInterface
{
/** @var bool */
private $preferStable;
/** @var bool */
private $preferLowest;
/** @var bool */
private $preferDevOverPrerelease;
/** @var array<string, string>|null */
private $preferredVersions;
/** @var array<int, array<string, non-empty-list<int>>> */
private $preferredPackageResultCachePerPool;
/** @var array<int, array<string, int>> */
private $sortingCachePerPool;
/**
* @param array<string, string>|null $preferredVersions Must be an array of package name => normalized version
*/
public function __construct(bool $preferStable = false, bool $preferLowest = false, ?array $preferredVersions = null)
{
$this->preferStable = $preferStable;
$this->preferLowest = $preferLowest;
$this->preferredVersions = $preferredVersions;
$this->preferDevOverPrerelease = (bool) Platform::getEnv('COMPOSER_PREFER_DEV_OVER_PRERELEASE');
}
/**
* @param string $operator One of Constraint::STR_OP_*
*
* @phpstan-param Constraint::STR_OP_* $operator
*/
public function versionCompare(PackageInterface $a, PackageInterface $b, string $operator): bool
{
if ($this->preferStable && ($stabA = $a->getStability()) !== ($stabB = $b->getStability())) {
if ($this->preferLowest && $this->preferDevOverPrerelease && 'stable' !== $stabA && 'stable' !== $stabB) {
// When COMPOSER_PREFER_DEV_OVER_PRERELEASE is set and no stable version has been
// released, "dev" should be considered more stable than "alpha", "beta" or "RC";
// this allows testing lowest versions with potential fixes applied
$stabA = 'dev' === $stabA ? 'stable' : $stabA;
$stabB = 'dev' === $stabB ? 'stable' : $stabB;
}
return BasePackage::STABILITIES[$stabA] < BasePackage::STABILITIES[$stabB];
}
// dev versions need to be compared as branches via matchSpecific's special treatment, the rest can be optimized with compiling matcher
if (($a->isDev() && str_starts_with($a->getVersion(), 'dev-')) || ($b->isDev() && str_starts_with($b->getVersion(), 'dev-'))) {
$constraint = new Constraint($operator, $b->getVersion());
$version = new Constraint('==', $a->getVersion());
return $constraint->matchSpecific($version, true);
}
return CompilingMatcher::match(new Constraint($operator, $b->getVersion()), Constraint::OP_EQ, $a->getVersion());
}
/**
* @param non-empty-list<int> $literals
* @return non-empty-list<int>
*/
public function selectPreferredPackages(Pool $pool, array $literals, ?string $requiredPackage = null): array
{
sort($literals);
$resultCacheKey = implode(',', $literals).$requiredPackage;
$poolId = spl_object_id($pool);
if (isset($this->preferredPackageResultCachePerPool[$poolId][$resultCacheKey])) {
return $this->preferredPackageResultCachePerPool[$poolId][$resultCacheKey];
}
$packages = $this->groupLiteralsByName($pool, $literals);
foreach ($packages as &$nameLiterals) {
usort($nameLiterals, function ($a, $b) use ($pool, $requiredPackage, $poolId): int {
$cacheKey = 'i'.$a.'.'.$b.$requiredPackage; // i prefix -> ignoreReplace = true
if (isset($this->sortingCachePerPool[$poolId][$cacheKey])) {
return $this->sortingCachePerPool[$poolId][$cacheKey];
}
return $this->sortingCachePerPool[$poolId][$cacheKey] = $this->compareByPriority($pool, $pool->literalToPackage($a), $pool->literalToPackage($b), $requiredPackage, true);
});
}
foreach ($packages as &$sortedLiterals) {
$sortedLiterals = $this->pruneToBestVersion($pool, $sortedLiterals);
$sortedLiterals = $this->pruneRemoteAliases($pool, $sortedLiterals);
}
$selected = array_merge(...array_values($packages));
// now sort the result across all packages to respect replaces across packages
usort($selected, function ($a, $b) use ($pool, $requiredPackage, $poolId): int {
$cacheKey = $a.'.'.$b.$requiredPackage; // no i prefix -> ignoreReplace = false
if (isset($this->sortingCachePerPool[$poolId][$cacheKey])) {
return $this->sortingCachePerPool[$poolId][$cacheKey];
}
return $this->sortingCachePerPool[$poolId][$cacheKey] = $this->compareByPriority($pool, $pool->literalToPackage($a), $pool->literalToPackage($b), $requiredPackage);
});
return $this->preferredPackageResultCachePerPool[$poolId][$resultCacheKey] = $selected;
}
/**
* @param non-empty-list<int> $literals
* @return non-empty-array<string, non-empty-list<int>>
*/
protected function groupLiteralsByName(Pool $pool, array $literals): array
{
$packages = [];
foreach ($literals as $literal) {
$packageName = $pool->literalToPackage($literal)->getName();
if (!isset($packages[$packageName])) {
$packages[$packageName] = [];
}
$packages[$packageName][] = $literal;
}
return $packages;
}
/**
* @protected
*/
public function compareByPriority(Pool $pool, BasePackage $a, BasePackage $b, ?string $requiredPackage = null, bool $ignoreReplace = false): int
{
// prefer aliases to the original package
if ($a->getName() === $b->getName()) {
$aAliased = $a instanceof AliasPackage;
$bAliased = $b instanceof AliasPackage;
if ($aAliased && !$bAliased) {
return -1; // use a
}
if (!$aAliased && $bAliased) {
return 1; // use b
}
}
if (!$ignoreReplace) {
// return original, not replaced
if ($this->replaces($a, $b)) {
return 1; // use b
}
if ($this->replaces($b, $a)) {
return -1; // use a
}
// for replacers not replacing each other, put a higher prio on replacing
// packages with the same vendor as the required package
if ($requiredPackage !== null && false !== ($pos = strpos($requiredPackage, '/'))) {
$requiredVendor = substr($requiredPackage, 0, $pos);
$aIsSameVendor = strpos($a->getName(), $requiredVendor) === 0;
$bIsSameVendor = strpos($b->getName(), $requiredVendor) === 0;
if ($bIsSameVendor !== $aIsSameVendor) {
return $aIsSameVendor ? -1 : 1;
}
}
}
// priority equal, sort by package id to make reproducible
if ($a->id === $b->id) {
return 0;
}
return ($a->id < $b->id) ? -1 : 1;
}
/**
* Checks if source replaces a package with the same name as target.
*
* Replace constraints are ignored. This method should only be used for
* prioritisation, not for actual constraint verification.
*/
protected function replaces(BasePackage $source, BasePackage $target): bool
{
foreach ($source->getReplaces() as $link) {
if ($link->getTarget() === $target->getName()
// && (null === $link->getConstraint() ||
// $link->getConstraint()->matches(new Constraint('==', $target->getVersion())))) {
) {
return true;
}
}
return false;
}
/**
* @param list<int> $literals
* @return list<int>
*/
protected function pruneToBestVersion(Pool $pool, array $literals): array
{
if ($this->preferredVersions !== null) {
$name = $pool->literalToPackage($literals[0])->getName();
if (isset($this->preferredVersions[$name])) {
$preferredVersion = $this->preferredVersions[$name];
$bestLiterals = [];
foreach ($literals as $literal) {
if ($pool->literalToPackage($literal)->getVersion() === $preferredVersion) {
$bestLiterals[] = $literal;
}
}
if (\count($bestLiterals) > 0) {
return $bestLiterals;
}
}
}
$operator = $this->preferLowest ? '<' : '>';
$bestLiterals = [$literals[0]];
$bestPackage = $pool->literalToPackage($literals[0]);
foreach ($literals as $i => $literal) {
if (0 === $i) {
continue;
}
$package = $pool->literalToPackage($literal);
if ($this->versionCompare($package, $bestPackage, $operator)) {
$bestPackage = $package;
$bestLiterals = [$literal];
} elseif ($this->versionCompare($package, $bestPackage, '==')) {
$bestLiterals[] = $literal;
}
}
return $bestLiterals;
}
/**
* Assumes that locally aliased (in root package requires) packages take priority over branch-alias ones
*
* If no package is a local alias, nothing happens
*
* @param list<int> $literals
* @return list<int>
*/
protected function pruneRemoteAliases(Pool $pool, array $literals): array
{
$hasLocalAlias = false;
foreach ($literals as $literal) {
$package = $pool->literalToPackage($literal);
if ($package instanceof AliasPackage && $package->isRootPackageAlias()) {
$hasLocalAlias = true;
break;
}
}
if (!$hasLocalAlias) {
return $literals;
}
$selected = [];
foreach ($literals as $literal) {
$package = $pool->literalToPackage($literal);
if ($package instanceof AliasPackage && $package->isRootPackageAlias()) {
$selected[] = $literal;
}
}
return $selected;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/Problem.php | src/Composer/DependencyResolver/Problem.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver;
use Composer\Advisory\PartialSecurityAdvisory;
use Composer\Advisory\SecurityAdvisory;
use Composer\Package\CompletePackageInterface;
use Composer\Package\AliasPackage;
use Composer\Package\BasePackage;
use Composer\Package\Link;
use Composer\Package\PackageInterface;
use Composer\Package\RootPackageInterface;
use Composer\Pcre\Preg;
use Composer\Repository\RepositorySet;
use Composer\Repository\LockArrayRepository;
use Composer\Semver\Constraint\Constraint;
use Composer\Semver\Constraint\ConstraintInterface;
use Composer\Package\Version\VersionParser;
use Composer\Repository\PlatformRepository;
use Composer\Semver\Constraint\MultiConstraint;
use Symfony\Component\Console\Formatter\OutputFormatter;
/**
* Represents a problem detected while solving dependencies
*
* @author Nils Adermann <naderman@naderman.de>
*/
class Problem
{
/**
* A map containing the id of each rule part of this problem as a key
* @var array<string, true>
*/
protected $reasonSeen;
/**
* A set of reasons for the problem, each is a rule or a root require and a rule
* @var array<int, array<int, Rule>>
*/
protected $reasons = [];
/** @var int */
protected $section = 0;
/**
* Add a rule as a reason
*
* @param Rule $rule A rule which is a reason for this problem
*/
public function addRule(Rule $rule): void
{
$this->addReason(spl_object_hash($rule), $rule);
}
/**
* Retrieve all reasons for this problem
*
* @return array<int, array<int, Rule>> The problem's reasons
*/
public function getReasons(): array
{
return $this->reasons;
}
/**
* A human readable textual representation of the problem's reasons
*
* @param array<int|string, BasePackage> $installedMap A map of all present packages
* @param array<Rule[]> $learnedPool
*/
public function getPrettyString(RepositorySet $repositorySet, Request $request, Pool $pool, bool $isVerbose, array $installedMap = [], array $learnedPool = []): string
{
// TODO doesn't this entirely defeat the purpose of the problem sections? what's the point of sections?
$reasons = array_merge(...array_reverse($this->reasons));
if (\count($reasons) === 1) {
reset($reasons);
$rule = current($reasons);
if ($rule->getReason() !== Rule::RULE_ROOT_REQUIRE) {
throw new \LogicException("Single reason problems must contain a root require rule.");
}
$reasonData = $rule->getReasonData();
$packageName = $reasonData['packageName'];
$constraint = $reasonData['constraint'];
$packages = $pool->whatProvides($packageName, $constraint);
if (\count($packages) === 0) {
return "\n ".implode(self::getMissingPackageReason($repositorySet, $request, $pool, $isVerbose, $packageName, $constraint));
}
}
usort($reasons, function (Rule $rule1, Rule $rule2) use ($pool) {
$rule1Prio = $this->getRulePriority($rule1);
$rule2Prio = $this->getRulePriority($rule2);
if ($rule1Prio !== $rule2Prio) {
return $rule2Prio - $rule1Prio;
}
return $this->getSortableString($pool, $rule1) <=> $this->getSortableString($pool, $rule2);
});
return self::formatDeduplicatedRules($reasons, ' ', $repositorySet, $request, $pool, $isVerbose, $installedMap, $learnedPool);
}
private function getSortableString(Pool $pool, Rule $rule): string
{
switch ($rule->getReason()) {
case Rule::RULE_ROOT_REQUIRE:
return $rule->getReasonData()['packageName'];
case Rule::RULE_FIXED:
return (string) $rule->getReasonData()['package'];
case Rule::RULE_PACKAGE_CONFLICT:
case Rule::RULE_PACKAGE_REQUIRES:
return $rule->getSourcePackage($pool) . '//' . $rule->getReasonData()->getPrettyString($rule->getSourcePackage($pool));
case Rule::RULE_PACKAGE_SAME_NAME:
case Rule::RULE_PACKAGE_ALIAS:
case Rule::RULE_PACKAGE_INVERSE_ALIAS:
return (string) $rule->getReasonData();
case Rule::RULE_LEARNED:
return implode('-', $rule->getLiterals());
}
// @phpstan-ignore deadCode.unreachable
throw new \LogicException('Unknown rule type: '.$rule->getReason());
}
private function getRulePriority(Rule $rule): int
{
switch ($rule->getReason()) {
case Rule::RULE_FIXED:
return 3;
case Rule::RULE_ROOT_REQUIRE:
return 2;
case Rule::RULE_PACKAGE_CONFLICT:
case Rule::RULE_PACKAGE_REQUIRES:
return 1;
case Rule::RULE_PACKAGE_SAME_NAME:
case Rule::RULE_LEARNED:
case Rule::RULE_PACKAGE_ALIAS:
case Rule::RULE_PACKAGE_INVERSE_ALIAS:
return 0;
}
// @phpstan-ignore deadCode.unreachable
throw new \LogicException('Unknown rule type: '.$rule->getReason());
}
/**
* @param Rule[] $rules
* @param array<int|string, BasePackage> $installedMap A map of all present packages
* @param array<Rule[]> $learnedPool
* @internal
*/
public static function formatDeduplicatedRules(array $rules, string $indent, RepositorySet $repositorySet, Request $request, Pool $pool, bool $isVerbose, array $installedMap = [], array $learnedPool = []): string
{
$messages = [];
$templates = [];
$parser = new VersionParser;
$deduplicatableRuleTypes = [Rule::RULE_PACKAGE_REQUIRES, Rule::RULE_PACKAGE_CONFLICT];
foreach ($rules as $rule) {
$message = $rule->getPrettyString($repositorySet, $request, $pool, $isVerbose, $installedMap, $learnedPool);
if (in_array($rule->getReason(), $deduplicatableRuleTypes, true) && Preg::isMatchStrictGroups('{^(?P<package>\S+) (?P<version>\S+) (?P<type>requires|conflicts)}', $message, $m)) {
$message = str_replace('%', '%%', $message);
$template = Preg::replace('{^\S+ \S+ }', '%s%s ', $message);
$messages[] = $template;
$templates[$template][$m[1]][$parser->normalize($m[2])] = $m[2];
$sourcePackage = $rule->getSourcePackage($pool);
foreach ($pool->getRemovedVersionsByPackage(spl_object_hash($sourcePackage)) as $version => $prettyVersion) {
$templates[$template][$m[1]][$version] = $prettyVersion;
}
} elseif ($message !== '') {
$messages[] = $message;
}
}
$result = [];
foreach (array_unique($messages) as $message) {
if (isset($templates[$message])) {
foreach ($templates[$message] as $package => $versions) {
uksort($versions, 'version_compare');
if (!$isVerbose) {
$versions = self::condenseVersionList($versions, 1);
}
if (\count($versions) > 1) {
// remove the s from requires/conflicts to correct grammar
$message = Preg::replace('{^(%s%s (?:require|conflict))s}', '$1', $message);
$result[] = sprintf($message, $package, '['.implode(', ', $versions).']');
} else {
$result[] = sprintf($message, $package, ' '.reset($versions));
}
}
} else {
$result[] = $message;
}
}
return "\n$indent- ".implode("\n$indent- ", $result);
}
public function isCausedByLock(RepositorySet $repositorySet, Request $request, Pool $pool): bool
{
foreach ($this->reasons as $sectionRules) {
foreach ($sectionRules as $rule) {
if ($rule->isCausedByLock($repositorySet, $request, $pool)) {
return true;
}
}
}
return false;
}
/**
* Store a reason descriptor but ignore duplicates
*
* @param string $id A canonical identifier for the reason
* @param Rule $reason The reason descriptor
*/
protected function addReason(string $id, Rule $reason): void
{
// TODO: if a rule is part of a problem description in two sections, isn't this going to remove a message
// that is important to understand the issue?
if (!isset($this->reasonSeen[$id])) {
$this->reasonSeen[$id] = true;
$this->reasons[$this->section][] = $reason;
}
}
public function nextSection(): void
{
$this->section++;
}
/**
* @internal
* @return array{0: string, 1: string}
*/
public static function getMissingPackageReason(RepositorySet $repositorySet, Request $request, Pool $pool, bool $isVerbose, string $packageName, ?ConstraintInterface $constraint = null): array
{
if (PlatformRepository::isPlatformPackage($packageName)) {
// handle php/php-*/hhvm
if (0 === stripos($packageName, 'php') || $packageName === 'hhvm') {
$version = self::getPlatformPackageVersion($pool, $packageName, phpversion());
$msg = "- Root composer.json requires ".$packageName.self::constraintToText($constraint).' but ';
if (defined('HHVM_VERSION') || ($packageName === 'hhvm' && count($pool->whatProvides($packageName)) > 0)) {
return [$msg, 'your HHVM version does not satisfy that requirement.'];
}
if ($packageName === 'hhvm') {
return [$msg, 'HHVM was not detected on this machine, make sure it is in your PATH.'];
}
if (null === $version) {
return [$msg, 'the '.$packageName.' package is disabled by your platform config. Enable it again with "composer config platform.'.$packageName.' --unset".'];
}
return [$msg, 'your '.$packageName.' version ('. $version .') does not satisfy that requirement.'];
}
// handle php extensions
if (0 === stripos($packageName, 'ext-')) {
if (false !== strpos($packageName, ' ')) {
return ['- ', "PHP extension ".$packageName.' should be required as '.str_replace(' ', '-', $packageName).'.'];
}
$ext = substr($packageName, 4);
$msg = "- Root composer.json requires PHP extension ".$packageName.self::constraintToText($constraint).' but ';
$version = self::getPlatformPackageVersion($pool, $packageName, phpversion($ext) === false ? '0' : phpversion($ext));
if (null === $version) {
$providersStr = self::getProvidersList($repositorySet, $packageName, 5);
if ($providersStr !== null) {
$providersStr = "\n\n Alternatively you can require one of these packages that provide the extension (or parts of it):\n".
" <warning>Keep in mind that the suggestions are automated and may not be valid or safe to use</warning>\n$providersStr";
}
if (extension_loaded($ext)) {
return [
$msg,
'the '.$packageName.' package is disabled by your platform config. Enable it again with "composer config platform.'.$packageName.' --unset".' . $providersStr,
];
}
return [$msg, 'it is missing from your system. Install or enable PHP\'s '.$ext.' extension.' . $providersStr];
}
return [$msg, 'it has the wrong version installed ('.$version.').'];
}
// handle linked libs
if (0 === stripos($packageName, 'lib-')) {
if (strtolower($packageName) === 'lib-icu') {
$error = extension_loaded('intl') ? 'it has the wrong version installed, try upgrading the intl extension.' : 'it is missing from your system, make sure the intl extension is loaded.';
return ["- Root composer.json requires linked library ".$packageName.self::constraintToText($constraint).' but ', $error];
}
$providersStr = self::getProvidersList($repositorySet, $packageName, 5);
if ($providersStr !== null) {
$providersStr = "\n\n Alternatively you can require one of these packages that provide the library (or parts of it):\n".
" <warning>Keep in mind that the suggestions are automated and may not be valid or safe to use</warning>\n$providersStr";
}
return ["- Root composer.json requires linked library ".$packageName.self::constraintToText($constraint).' but ', 'it has the wrong version installed or is missing from your system, make sure to load the extension providing it.'.$providersStr];
}
}
$lockedPackage = null;
foreach ($request->getLockedPackages() as $package) {
if ($package->getName() === $packageName) {
$lockedPackage = $package;
if ($pool->isUnacceptableFixedOrLockedPackage($package)) {
return ["- ", $package->getPrettyName().' is fixed to '.$package->getPrettyVersion().' (lock file version) by a partial update but that version is rejected by your minimum-stability. Make sure you list it as an argument for the update command.'];
}
break;
}
}
if ($constraint instanceof Constraint && $constraint->getOperator() === Constraint::STR_OP_EQ && Preg::isMatch('{^dev-.*#.*}', $constraint->getPrettyString())) {
$newConstraint = Preg::replace('{ +as +([^,\s|]+)$}', '', $constraint->getPrettyString());
$packages = $repositorySet->findPackages($packageName, new MultiConstraint([
new Constraint(Constraint::STR_OP_EQ, $newConstraint),
new Constraint(Constraint::STR_OP_EQ, str_replace('#', '+', $newConstraint)),
], false));
if (\count($packages) > 0) {
return ["- Root composer.json requires $packageName".self::constraintToText($constraint) . ', ', 'found '.self::getPackageList($packages, $isVerbose, $pool, $constraint).'. The # character in branch names is replaced by a + character. Make sure to require it as "'.str_replace('#', '+', $constraint->getPrettyString()).'".'];
}
}
// first check if the actual requested package is found in normal conditions
// if so it must mean it is rejected by another constraint than the one given here
$packages = $repositorySet->findPackages($packageName, $constraint);
if (\count($packages) > 0) {
$rootReqs = $repositorySet->getRootRequires();
if (isset($rootReqs[$packageName])) {
$filtered = array_filter($packages, static function ($p) use ($rootReqs, $packageName): bool {
return $rootReqs[$packageName]->matches(new Constraint('==', $p->getVersion()));
});
if (0 === count($filtered)) {
return ["- Root composer.json requires $packageName".self::constraintToText($constraint) . ', ', 'found '.self::getPackageList($packages, $isVerbose, $pool, $constraint).' but '.(self::hasMultipleNames($packages) ? 'these conflict' : 'it conflicts').' with your root composer.json require ('.$rootReqs[$packageName]->getPrettyString().').'];
}
}
$tempReqs = $repositorySet->getTemporaryConstraints();
foreach (reset($packages)->getNames() as $name) {
if (isset($tempReqs[$name])) {
$filtered = array_filter($packages, static function ($p) use ($tempReqs, $name): bool {
return $tempReqs[$name]->matches(new Constraint('==', $p->getVersion()));
});
if (0 === count($filtered)) {
return ["- Root composer.json requires $name".self::constraintToText($constraint) . ', ', 'found '.self::getPackageList($packages, $isVerbose, $pool, $constraint).' but '.(self::hasMultipleNames($packages) ? 'these conflict' : 'it conflicts').' with your temporary update constraint ('.$name.':'.$tempReqs[$name]->getPrettyString().').'];
}
}
}
if ($lockedPackage !== null) {
$fixedConstraint = new Constraint('==', $lockedPackage->getVersion());
$filtered = array_filter($packages, static function ($p) use ($fixedConstraint): bool {
return $fixedConstraint->matches(new Constraint('==', $p->getVersion()));
});
if (0 === count($filtered)) {
return ["- Root composer.json requires $packageName".self::constraintToText($constraint) . ', ', 'found '.self::getPackageList($packages, $isVerbose, $pool, $constraint).' but the package is fixed to '.$lockedPackage->getPrettyVersion().' (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command.'];
}
}
$nonLockedPackages = array_filter($packages, static function ($p): bool {
return !$p->getRepository() instanceof LockArrayRepository;
});
if (0 === \count($nonLockedPackages)) {
return ["- Root composer.json requires $packageName".self::constraintToText($constraint) . ', ', 'found '.self::getPackageList($packages, $isVerbose, $pool, $constraint).' in the lock file but not in remote repositories, make sure you avoid updating this package to keep the one from the lock file.'];
}
if ($pool->isAbandonedRemovedPackageVersion($packageName, $constraint)) {
return ["- Root composer.json requires $packageName".self::constraintToText($constraint) . ', ', 'found '.self::getPackageList($packages, $isVerbose, $pool, $constraint).' but these were not loaded, because they are abandoned and you configured "block-abandoned" to true in your "audit" config.'];
}
if ($pool->isSecurityRemovedPackageVersion($packageName, $constraint)) {
$advisories = $repositorySet->getMatchingSecurityAdvisories($packages, false, true);
if (isset($advisories['advisories'][$packageName]) && \count($advisories['advisories'][$packageName]) > 0) {
$advisoriesList = array_map(static function (SecurityAdvisory $advisory): string {
if ($advisory->link !== null && $advisory->link !== '') {
return '<href='.OutputFormatter::escape($advisory->link).'>'.$advisory->advisoryId.'</>';
}
if (str_starts_with($advisory->advisoryId, 'PKSA-')) {
return '<href='.OutputFormatter::escape('https://packagist.org/security-advisories/'.$advisory->advisoryId).'>'.$advisory->advisoryId.'</>';
}
return $advisory->advisoryId;
}, $advisories['advisories'][$packageName]);
} else {
$advisoriesList = array_map(static function (string $advisoryId): string {
if (str_starts_with($advisoryId, 'PKSA-')) {
return '<href='.OutputFormatter::escape('https://packagist.org/security-advisories/'.$advisoryId).'>'.$advisoryId.'</>';
}
return $advisoryId;
}, $pool->getSecurityAdvisoryIdentifiersForPackageVersion($packageName, $constraint));
}
return ["- Root composer.json requires $packageName".self::constraintToText($constraint) . ', ', 'found '.self::getPackageList($packages, $isVerbose, $pool, $constraint).' but these were not loaded, because they are affected by security advisories ("' . implode('", "', $advisoriesList). '"). Go to https://packagist.org/security-advisories/ to find advisory details. To ignore the advisories, add them to the audit "ignore" config. To turn the feature off entirely, you can set "block-insecure" to false in your "audit" config.'];
}
return ["- Root composer.json requires $packageName".self::constraintToText($constraint) . ', ', 'found '.self::getPackageList($packages, $isVerbose, $pool, $constraint).' but these were not loaded, likely because '.(self::hasMultipleNames($packages) ? 'they conflict' : 'it conflicts').' with another require.'];
}
// check if the package is found when bypassing stability checks
$packages = $repositorySet->findPackages($packageName, $constraint, RepositorySet::ALLOW_UNACCEPTABLE_STABILITIES);
if (\count($packages) > 0) {
// we must first verify if a valid package would be found in a lower priority repository
$allReposPackages = $repositorySet->findPackages($packageName, $constraint, RepositorySet::ALLOW_SHADOWED_REPOSITORIES);
if (\count($allReposPackages) > 0) {
return self::computeCheckForLowerPrioRepo($pool, $isVerbose, $packageName, $packages, $allReposPackages, 'minimum-stability', $constraint);
}
return ["- Root composer.json requires $packageName".self::constraintToText($constraint) . ', ', 'found '.self::getPackageList($packages, $isVerbose, $pool, $constraint).' but '.(self::hasMultipleNames($packages) ? 'these do' : 'it does').' not match your minimum-stability.'];
}
// check if the package is found when bypassing the constraint and stability checks
$packages = $repositorySet->findPackages($packageName, null, RepositorySet::ALLOW_UNACCEPTABLE_STABILITIES);
if (\count($packages) > 0) {
// we must first verify if a valid package would be found in a lower priority repository
$allReposPackages = $repositorySet->findPackages($packageName, $constraint, RepositorySet::ALLOW_SHADOWED_REPOSITORIES);
if (\count($allReposPackages) > 0) {
return self::computeCheckForLowerPrioRepo($pool, $isVerbose, $packageName, $packages, $allReposPackages, 'constraint', $constraint);
}
$suffix = '';
if ($constraint instanceof Constraint && $constraint->getVersion() === 'dev-master') {
foreach ($packages as $candidate) {
if (in_array($candidate->getVersion(), ['dev-default', 'dev-main'], true)) {
$suffix = ' Perhaps dev-master was renamed to '.$candidate->getPrettyVersion().'?';
break;
}
}
}
// check if the root package is a name match and hint the dependencies on root troubleshooting article
$allReposPackages = $packages;
$topPackage = reset($allReposPackages);
if ($topPackage instanceof RootPackageInterface) {
$suffix = ' See https://getcomposer.org/dep-on-root for details and assistance.';
}
return ["- Root composer.json requires $packageName".self::constraintToText($constraint) . ', ', 'found '.self::getPackageList($packages, $isVerbose, $pool, $constraint).' but '.(self::hasMultipleNames($packages) ? 'these do' : 'it does').' not match the constraint.' . $suffix];
}
if (!Preg::isMatch('{^[A-Za-z0-9_./-]+$}', $packageName)) {
$illegalChars = Preg::replace('{[A-Za-z0-9_./-]+}', '', $packageName);
return ["- Root composer.json requires $packageName, it ", 'could not be found, it looks like its name is invalid, "'.$illegalChars.'" is not allowed in package names.'];
}
$providersStr = self::getProvidersList($repositorySet, $packageName, 15);
if ($providersStr !== null) {
return ["- Root composer.json requires $packageName".self::constraintToText($constraint).", it ", "could not be found in any version, but the following packages provide it:\n".$providersStr." Consider requiring one of these to satisfy the $packageName requirement."];
}
return ["- Root composer.json requires $packageName, it ", "could not be found in any version, there may be a typo in the package name."];
}
/**
* @internal
* @param PackageInterface[] $packages
*/
public static function getPackageList(array $packages, bool $isVerbose, ?Pool $pool = null, ?ConstraintInterface $constraint = null, bool $useRemovedVersionGroup = false): string
{
$prepared = [];
$hasDefaultBranch = [];
foreach ($packages as $package) {
$prepared[$package->getName()]['name'] = $package->getPrettyName();
$prepared[$package->getName()]['versions'][$package->getVersion()] = $package->getPrettyVersion().($package instanceof AliasPackage ? ' (alias of '.$package->getAliasOf()->getPrettyVersion().')' : '');
if ($pool !== null && $constraint !== null) {
foreach ($pool->getRemovedVersions($package->getName(), $constraint) as $version => $prettyVersion) {
$prepared[$package->getName()]['versions'][$version] = $prettyVersion;
}
}
if ($pool !== null && $useRemovedVersionGroup) {
foreach ($pool->getRemovedVersionsByPackage(spl_object_hash($package)) as $version => $prettyVersion) {
$prepared[$package->getName()]['versions'][$version] = $prettyVersion;
}
}
if ($package->isDefaultBranch()) {
$hasDefaultBranch[$package->getName()] = true;
}
}
$preparedStrings = [];
foreach ($prepared as $name => $package) {
// remove the implicit default branch alias to avoid cruft in the display
if (isset($package['versions'][VersionParser::DEFAULT_BRANCH_ALIAS], $hasDefaultBranch[$name])) {
unset($package['versions'][VersionParser::DEFAULT_BRANCH_ALIAS]);
}
uksort($package['versions'], 'version_compare');
if (!$isVerbose) {
$package['versions'] = self::condenseVersionList($package['versions'], 4);
}
$preparedStrings[] = $package['name'].'['.implode(', ', $package['versions']).']';
}
return implode(', ', $preparedStrings);
}
/**
* @param string $version the effective runtime version of the platform package
* @return ?string a version string or null if it appears the package was artificially disabled
*/
private static function getPlatformPackageVersion(Pool $pool, string $packageName, string $version): ?string
{
$available = $pool->whatProvides($packageName);
if (\count($available) > 0) {
$selected = null;
foreach ($available as $pkg) {
if ($pkg->getRepository() instanceof PlatformRepository) {
$selected = $pkg;
break;
}
}
if ($selected === null) {
$selected = reset($available);
}
// must be a package providing/replacing and not a real platform package
if ($selected->getName() !== $packageName) {
/** @var Link $link */
foreach (array_merge(array_values($selected->getProvides()), array_values($selected->getReplaces())) as $link) {
if ($link->getTarget() === $packageName) {
return $link->getPrettyConstraint().' '.substr($link->getDescription(), 0, -1).'d by '.$selected->getPrettyString();
}
}
}
$version = $selected->getPrettyVersion();
$extra = $selected->getExtra();
if ($selected instanceof CompletePackageInterface && isset($extra['config.platform']) && $extra['config.platform'] === true) {
$version .= '; ' . str_replace('Package ', '', (string) $selected->getDescription());
}
} else {
return null;
}
return $version;
}
/**
* @param array<string|int, string> $versions an array of pretty versions, with normalized versions as keys
* @return list<string> a list of pretty versions and '...' where versions were removed
*/
private static function condenseVersionList(array $versions, int $max, int $maxDev = 16): array
{
if (count($versions) <= $max) {
return array_values($versions);
}
$filtered = [];
$byMajor = [];
foreach ($versions as $version => $pretty) {
if (0 === stripos((string) $version, 'dev-')) {
$byMajor['dev'][] = $pretty;
} else {
$byMajor[Preg::replace('{^(\d+)\..*}', '$1', (string) $version)][] = $pretty;
}
}
foreach ($byMajor as $majorVersion => $versionsForMajor) {
$maxVersions = $majorVersion === 'dev' ? $maxDev : $max;
if (count($versionsForMajor) > $maxVersions) {
// output only 1st and last versions
$filtered[] = $versionsForMajor[0];
$filtered[] = '...';
$filtered[] = $versionsForMajor[count($versionsForMajor) - 1];
} else {
$filtered = array_merge($filtered, $versionsForMajor);
}
}
return $filtered;
}
/**
* @param PackageInterface[] $packages
*/
private static function hasMultipleNames(array $packages): bool
{
$name = null;
foreach ($packages as $package) {
if ($name === null || $name === $package->getName()) {
$name = $package->getName();
} else {
return true;
}
}
return false;
}
/**
* @param non-empty-array<PackageInterface> $higherRepoPackages
* @param non-empty-array<PackageInterface> $allReposPackages
* @return array{0: string, 1: string}
*/
private static function computeCheckForLowerPrioRepo(Pool $pool, bool $isVerbose, string $packageName, array $higherRepoPackages, array $allReposPackages, string $reason, ?ConstraintInterface $constraint = null): array
{
$nextRepoPackages = [];
$nextRepo = null;
foreach ($allReposPackages as $package) {
if ($nextRepo === null || $nextRepo === $package->getRepository()) {
$nextRepoPackages[] = $package;
$nextRepo = $package->getRepository();
} else {
break;
}
}
assert(null !== $nextRepo);
if (\count($higherRepoPackages) > 0) {
$topPackage = reset($higherRepoPackages);
if ($topPackage instanceof RootPackageInterface) {
return [
"- Root composer.json requires $packageName".self::constraintToText($constraint).', it is ',
'satisfiable by '.self::getPackageList($nextRepoPackages, $isVerbose, $pool, $constraint).' from '.$nextRepo->getRepoName().' but '.$topPackage->getPrettyName().' '.$topPackage->getPrettyVersion().' is the root package and cannot be modified. See https://getcomposer.org/dep-on-root for details and assistance.',
];
}
}
if ($nextRepo instanceof LockArrayRepository) {
$singular = count($higherRepoPackages) === 1;
$suggestion = 'Make sure you either fix the '.$reason.' or avoid updating this package to keep the one present in the lock file ('.self::getPackageList($nextRepoPackages, $isVerbose, $pool, $constraint).').';
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | true |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/RuleWatchGraph.php | src/Composer/DependencyResolver/RuleWatchGraph.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver;
/**
* The RuleWatchGraph efficiently propagates decisions to other rules
*
* All rules generated for solving a SAT problem should be inserted into the
* graph. When a decision on a literal is made, the graph can be used to
* propagate the decision to all other rules involving the literal, leading to
* other trivial decisions resulting from unit clauses.
*
* @author Nils Adermann <naderman@naderman.de>
*/
class RuleWatchGraph
{
/** @var array<int, RuleWatchChain> */
protected $watchChains = [];
/**
* Inserts a rule node into the appropriate chains within the graph
*
* The node is prepended to the watch chains for each of the two literals it
* watches.
*
* Assertions are skipped because they only depend on a single package and
* have no alternative literal that could be true, so there is no need to
* watch changes in any literals.
*
* @param RuleWatchNode $node The rule node to be inserted into the graph
*/
public function insert(RuleWatchNode $node): void
{
if ($node->getRule()->isAssertion()) {
return;
}
if (!$node->getRule() instanceof MultiConflictRule) {
foreach ([$node->watch1, $node->watch2] as $literal) {
if (!isset($this->watchChains[$literal])) {
$this->watchChains[$literal] = new RuleWatchChain;
}
$this->watchChains[$literal]->unshift($node);
}
} else {
foreach ($node->getRule()->getLiterals() as $literal) {
if (!isset($this->watchChains[$literal])) {
$this->watchChains[$literal] = new RuleWatchChain;
}
$this->watchChains[$literal]->unshift($node);
}
}
}
/**
* Propagates a decision on a literal to all rules watching the literal
*
* If a decision, e.g. +A has been made, then all rules containing -A, e.g.
* (-A|+B|+C) now need to satisfy at least one of the other literals, so
* that the rule as a whole becomes true, since with +A applied the rule
* is now (false|+B|+C) so essentially (+B|+C).
*
* This means that all rules watching the literal -A need to be updated to
* watch 2 other literals which can still be satisfied instead. So literals
* that conflict with previously made decisions are not an option.
*
* Alternatively it can occur that a unit clause results: e.g. if in the
* above example the rule was (-A|+B), then A turning true means that
* B must now be decided true as well.
*
* @param int $decidedLiteral The literal which was decided (A in our example)
* @param int $level The level at which the decision took place and at which
* all resulting decisions should be made.
* @param Decisions $decisions Used to check previous decisions and to
* register decisions resulting from propagation
* @return Rule|null If a conflict is found the conflicting rule is returned
*/
public function propagateLiteral(int $decidedLiteral, int $level, Decisions $decisions): ?Rule
{
// we invert the decided literal here, example:
// A was decided => (-A|B) now requires B to be true, so we look for
// rules which are fulfilled by -A, rather than A.
$literal = -$decidedLiteral;
if (!isset($this->watchChains[$literal])) {
return null;
}
$chain = $this->watchChains[$literal];
$chain->rewind();
while ($chain->valid()) {
$node = $chain->current();
if (!$node->getRule() instanceof MultiConflictRule) {
$otherWatch = $node->getOtherWatch($literal);
if (!$node->getRule()->isDisabled() && !$decisions->satisfy($otherWatch)) {
$ruleLiterals = $node->getRule()->getLiterals();
$alternativeLiterals = array_filter($ruleLiterals, static function ($ruleLiteral) use ($literal, $otherWatch, $decisions): bool {
return $literal !== $ruleLiteral &&
$otherWatch !== $ruleLiteral &&
!$decisions->conflict($ruleLiteral);
});
if (\count($alternativeLiterals) > 0) {
reset($alternativeLiterals);
$this->moveWatch($literal, current($alternativeLiterals), $node);
continue;
}
if ($decisions->conflict($otherWatch)) {
return $node->getRule();
}
$decisions->decide($otherWatch, $level, $node->getRule());
}
} else {
foreach ($node->getRule()->getLiterals() as $otherLiteral) {
if ($literal !== $otherLiteral && !$decisions->satisfy($otherLiteral)) {
if ($decisions->conflict($otherLiteral)) {
return $node->getRule();
}
$decisions->decide($otherLiteral, $level, $node->getRule());
}
}
}
$chain->next();
}
return null;
}
/**
* Moves a rule node from one watch chain to another
*
* The rule node's watched literals are updated accordingly.
*
* @param int $fromLiteral A literal the node used to watch
* @param int $toLiteral A literal the node should watch now
* @param RuleWatchNode $node The rule node to be moved
*/
protected function moveWatch(int $fromLiteral, int $toLiteral, RuleWatchNode $node): void
{
if (!isset($this->watchChains[$toLiteral])) {
$this->watchChains[$toLiteral] = new RuleWatchChain;
}
$node->moveWatch($fromLiteral, $toLiteral);
$this->watchChains[$fromLiteral]->remove();
$this->watchChains[$toLiteral]->unshift($node);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/RuleWatchChain.php | src/Composer/DependencyResolver/RuleWatchChain.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver;
/**
* An extension of SplDoublyLinkedList with seek and removal of current element
*
* SplDoublyLinkedList only allows deleting a particular offset and has no
* method to set the internal iterator to a particular offset.
*
* @author Nils Adermann <naderman@naderman.de>
* @extends \SplDoublyLinkedList<RuleWatchNode>
*/
class RuleWatchChain extends \SplDoublyLinkedList
{
/**
* Moves the internal iterator to the specified offset
*
* @param int $offset The offset to seek to.
*/
public function seek(int $offset): void
{
$this->rewind();
for ($i = 0; $i < $offset; $i++, $this->next());
}
/**
* Removes the current element from the list
*
* As SplDoublyLinkedList only allows deleting a particular offset and
* incorrectly sets the internal iterator if you delete the current value
* this method sets the internal iterator back to the following element
* using the seek method.
*/
public function remove(): void
{
$offset = $this->key();
$this->offsetUnset($offset);
$this->seek($offset);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/SolverProblemsException.php | src/Composer/DependencyResolver/SolverProblemsException.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver;
use Composer\Util\IniHelper;
use Composer\Repository\RepositorySet;
/**
* @author Nils Adermann <naderman@naderman.de>
*
* @method self::ERROR_DEPENDENCY_RESOLUTION_FAILED getCode()
*/
class SolverProblemsException extends \RuntimeException
{
public const ERROR_DEPENDENCY_RESOLUTION_FAILED = 2;
/** @var Problem[] */
protected $problems;
/** @var array<Rule[]> */
protected $learnedPool;
/**
* @param Problem[] $problems
* @param array<Rule[]> $learnedPool
*/
public function __construct(array $problems, array $learnedPool)
{
$this->problems = $problems;
$this->learnedPool = $learnedPool;
parent::__construct('Failed resolving dependencies with '.\count($problems).' problems, call getPrettyString to get formatted details', self::ERROR_DEPENDENCY_RESOLUTION_FAILED);
}
public function getPrettyString(RepositorySet $repositorySet, Request $request, Pool $pool, bool $isVerbose, bool $isDevExtraction = false): string
{
$installedMap = $request->getPresentMap(true);
$missingExtensions = [];
$isCausedByLock = false;
$problems = [];
foreach ($this->problems as $problem) {
$problems[] = $problem->getPrettyString($repositorySet, $request, $pool, $isVerbose, $installedMap, $this->learnedPool)."\n";
$missingExtensions = array_merge($missingExtensions, $this->getExtensionProblems($problem->getReasons()));
$isCausedByLock = $isCausedByLock || $problem->isCausedByLock($repositorySet, $request, $pool);
}
$i = 1;
$text = "\n";
foreach (array_unique($problems) as $problem) {
$text .= " Problem ".($i++).$problem;
}
$hints = [];
if (!$isDevExtraction && (str_contains($text, 'could not be found') || str_contains($text, 'no matching package found'))) {
$hints[] = "Potential causes:\n - A typo in the package name\n - The package is not available in a stable-enough version according to your minimum-stability setting\n see <https://getcomposer.org/doc/04-schema.md#minimum-stability> for more details.\n - It's a private package and you forgot to add a custom repository to find it\n\nRead <https://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.";
}
if (\count($missingExtensions) > 0) {
$hints[] = $this->createExtensionHint($missingExtensions);
}
if ($isCausedByLock && !$isDevExtraction && !$request->getUpdateAllowTransitiveRootDependencies()) {
$hints[] = "Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.";
}
if (str_contains($text, 'found composer-plugin-api[2.0.0] but it does not match') && str_contains($text, '- ocramius/package-versions')) {
$hints[] = "<warning>ocramius/package-versions only provides support for Composer 2 in 1.8+, which requires PHP 7.4.</warning>\nIf you can not upgrade PHP you can require <info>composer/package-versions-deprecated</info> to resolve this with PHP 7.0+.";
}
if (!class_exists('PHPUnit\Framework\TestCase', false)) {
if (str_contains($text, 'found composer-plugin-api[2.0.0] but it does not match')) {
$hints[] = "You are using Composer 2, which some of your plugins seem to be incompatible with. Make sure you update your plugins or report a plugin-issue to ask them to support Composer 2.";
}
}
if (\count($hints) > 0) {
$text .= "\n" . implode("\n\n", $hints);
}
return $text;
}
/**
* @return Problem[]
*/
public function getProblems(): array
{
return $this->problems;
}
/**
* @param string[] $missingExtensions
*/
private function createExtensionHint(array $missingExtensions): string
{
$paths = IniHelper::getAll();
if ('' === $paths[0]) {
if (count($paths) === 1) {
return '';
}
array_shift($paths);
}
$ignoreExtensionsArguments = implode(" ", array_map(static function ($extension) {
return "--ignore-platform-req=$extension";
}, array_unique($missingExtensions)));
$text = "To enable extensions, verify that they are enabled in your .ini files:\n - ";
$text .= implode("\n - ", $paths);
$text .= "\nYou can also run `php --ini` in a terminal to see which files are used by PHP in CLI mode.";
$text .= "\nAlternatively, you can run Composer with `$ignoreExtensionsArguments` to temporarily ignore these required extensions.";
return $text;
}
/**
* @param Rule[][] $reasonSets
* @return string[]
*/
private function getExtensionProblems(array $reasonSets): array
{
$missingExtensions = [];
foreach ($reasonSets as $reasonSet) {
foreach ($reasonSet as $rule) {
$required = $rule->getRequiredPackage();
if (null !== $required && 0 === strpos($required, 'ext-')) {
$missingExtensions[$required] = 1;
}
}
}
return array_keys($missingExtensions);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/LocalRepoTransaction.php | src/Composer/DependencyResolver/LocalRepoTransaction.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver;
use Composer\Repository\InstalledRepositoryInterface;
use Composer\Repository\RepositoryInterface;
/**
* @author Nils Adermann <naderman@naderman.de>
* @internal
*/
class LocalRepoTransaction extends Transaction
{
public function __construct(RepositoryInterface $lockedRepository, InstalledRepositoryInterface $localRepository)
{
parent::__construct(
$localRepository->getPackages(),
$lockedRepository->getPackages()
);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/RuleSetGenerator.php | src/Composer/DependencyResolver/RuleSetGenerator.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver;
use Composer\Filter\PlatformRequirementFilter\IgnoreListPlatformRequirementFilter;
use Composer\Filter\PlatformRequirementFilter\PlatformRequirementFilterFactory;
use Composer\Filter\PlatformRequirementFilter\PlatformRequirementFilterInterface;
use Composer\Package\BasePackage;
use Composer\Package\AliasPackage;
/**
* @author Nils Adermann <naderman@naderman.de>
* @phpstan-import-type ReasonData from Rule
*/
class RuleSetGenerator
{
/** @var PolicyInterface */
protected $policy;
/** @var Pool */
protected $pool;
/** @var RuleSet */
protected $rules;
/** @var array<int, BasePackage> */
protected $addedMap = [];
/** @var array<string, BasePackage[]> */
protected $addedPackagesByNames = [];
public function __construct(PolicyInterface $policy, Pool $pool)
{
$this->policy = $policy;
$this->pool = $pool;
$this->rules = new RuleSet;
}
/**
* Creates a new rule for the requirements of a package
*
* This rule is of the form (-A|B|C), where B and C are the providers of
* one requirement of the package A.
*
* @param BasePackage $package The package with a requirement
* @param BasePackage[] $providers The providers of the requirement
* @param Rule::RULE_* $reason A RULE_* constant describing the reason for generating this rule
* @param mixed $reasonData Any data, e.g. the requirement name, that goes with the reason
* @return Rule|null The generated rule or null if tautological
*
* @phpstan-param ReasonData $reasonData
*/
protected function createRequireRule(BasePackage $package, array $providers, $reason, $reasonData): ?Rule
{
$literals = [-$package->id];
foreach ($providers as $provider) {
// self fulfilling rule?
if ($provider === $package) {
return null;
}
$literals[] = $provider->id;
}
return new GenericRule($literals, $reason, $reasonData);
}
/**
* Creates a rule to install at least one of a set of packages
*
* The rule is (A|B|C) with A, B and C different packages. If the given
* set of packages is empty an impossible rule is generated.
*
* @param non-empty-array<BasePackage> $packages The set of packages to choose from
* @param Rule::RULE_* $reason A RULE_* constant describing the reason for
* generating this rule
* @param mixed $reasonData Additional data like the root require or fix request info
* @return Rule The generated rule
*
* @phpstan-param ReasonData $reasonData
*/
protected function createInstallOneOfRule(array $packages, $reason, $reasonData): Rule
{
$literals = [];
foreach ($packages as $package) {
$literals[] = $package->id;
}
return new GenericRule($literals, $reason, $reasonData);
}
/**
* Creates a rule for two conflicting packages
*
* The rule for conflicting packages A and B is (-A|-B). A is called the issuer
* and B the provider.
*
* @param BasePackage $issuer The package declaring the conflict
* @param BasePackage $provider The package causing the conflict
* @param Rule::RULE_* $reason A RULE_* constant describing the reason for generating this rule
* @param mixed $reasonData Any data, e.g. the package name, that goes with the reason
* @return ?Rule The generated rule
*
* @phpstan-param ReasonData $reasonData
*/
protected function createRule2Literals(BasePackage $issuer, BasePackage $provider, $reason, $reasonData): ?Rule
{
// ignore self conflict
if ($issuer === $provider) {
return null;
}
return new Rule2Literals(-$issuer->id, -$provider->id, $reason, $reasonData);
}
/**
* @param non-empty-array<BasePackage> $packages
* @param Rule::RULE_* $reason A RULE_* constant
* @param mixed $reasonData
*
* @phpstan-param ReasonData $reasonData
*/
protected function createMultiConflictRule(array $packages, $reason, $reasonData): Rule
{
$literals = [];
foreach ($packages as $package) {
$literals[] = -$package->id;
}
if (\count($literals) === 2) {
return new Rule2Literals($literals[0], $literals[1], $reason, $reasonData);
}
return new MultiConflictRule($literals, $reason, $reasonData);
}
/**
* Adds a rule unless it duplicates an existing one of any type
*
* To be able to directly pass in the result of one of the rule creation
* methods null is allowed which will not insert a rule.
*
* @param RuleSet::TYPE_* $type A TYPE_* constant defining the rule type
* @param Rule $newRule The rule about to be added
*/
private function addRule($type, ?Rule $newRule = null): void
{
if (null === $newRule) {
return;
}
$this->rules->add($newRule, $type);
}
protected function addRulesForPackage(BasePackage $package, PlatformRequirementFilterInterface $platformRequirementFilter): void
{
/** @var \SplQueue<BasePackage> */
$workQueue = new \SplQueue;
$workQueue->enqueue($package);
while (!$workQueue->isEmpty()) {
$package = $workQueue->dequeue();
if (isset($this->addedMap[$package->id])) {
continue;
}
$this->addedMap[$package->id] = $package;
if (!$package instanceof AliasPackage) {
foreach ($package->getNames(false) as $name) {
$this->addedPackagesByNames[$name][] = $package;
}
} else {
$workQueue->enqueue($package->getAliasOf());
$this->addRule(RuleSet::TYPE_PACKAGE, $this->createRequireRule($package, [$package->getAliasOf()], Rule::RULE_PACKAGE_ALIAS, $package));
// aliases must be installed with their main package, so create a rule the other way around as well
$this->addRule(RuleSet::TYPE_PACKAGE, $this->createRequireRule($package->getAliasOf(), [$package], Rule::RULE_PACKAGE_INVERSE_ALIAS, $package->getAliasOf()));
// if alias package has no self.version requires, its requirements do not
// need to be added as the aliased package processing will take care of it
if (!$package->hasSelfVersionRequires()) {
continue;
}
}
foreach ($package->getRequires() as $link) {
$constraint = $link->getConstraint();
if ($platformRequirementFilter->isIgnored($link->getTarget())) {
continue;
} elseif ($platformRequirementFilter instanceof IgnoreListPlatformRequirementFilter) {
$constraint = $platformRequirementFilter->filterConstraint($link->getTarget(), $constraint);
}
$possibleRequires = $this->pool->whatProvides($link->getTarget(), $constraint);
$this->addRule(RuleSet::TYPE_PACKAGE, $this->createRequireRule($package, $possibleRequires, Rule::RULE_PACKAGE_REQUIRES, $link));
foreach ($possibleRequires as $require) {
$workQueue->enqueue($require);
}
}
}
}
protected function addConflictRules(PlatformRequirementFilterInterface $platformRequirementFilter): void
{
/** @var BasePackage $package */
foreach ($this->addedMap as $package) {
foreach ($package->getConflicts() as $link) {
// even if conflict ends up being with an alias, there would be at least one actual package by this name
if (!isset($this->addedPackagesByNames[$link->getTarget()])) {
continue;
}
$constraint = $link->getConstraint();
if ($platformRequirementFilter->isIgnored($link->getTarget())) {
continue;
} elseif ($platformRequirementFilter instanceof IgnoreListPlatformRequirementFilter) {
$constraint = $platformRequirementFilter->filterConstraint($link->getTarget(), $constraint, false);
}
$conflicts = $this->pool->whatProvides($link->getTarget(), $constraint);
foreach ($conflicts as $conflict) {
// define the conflict rule for regular packages, for alias packages it's only needed if the name
// matches the conflict exactly, otherwise the name match is by provide/replace which means the
// package which this is an alias of will conflict anyway, so no need to create additional rules
if (!$conflict instanceof AliasPackage || $conflict->getName() === $link->getTarget()) {
$this->addRule(RuleSet::TYPE_PACKAGE, $this->createRule2Literals($package, $conflict, Rule::RULE_PACKAGE_CONFLICT, $link));
}
}
}
}
foreach ($this->addedPackagesByNames as $name => $packages) {
if (\count($packages) > 1) {
$reason = Rule::RULE_PACKAGE_SAME_NAME;
$this->addRule(RuleSet::TYPE_PACKAGE, $this->createMultiConflictRule($packages, $reason, $name));
}
}
}
protected function addRulesForRequest(Request $request, PlatformRequirementFilterInterface $platformRequirementFilter): void
{
foreach ($request->getFixedPackages() as $package) {
if ($package->id === -1) {
// fixed package was not added to the pool as it did not pass the stability requirements, this is fine
if ($this->pool->isUnacceptableFixedOrLockedPackage($package)) {
continue;
}
// otherwise, looks like a bug
throw new \LogicException("Fixed package ".$package->getPrettyString()." was not added to solver pool.");
}
$this->addRulesForPackage($package, $platformRequirementFilter);
$rule = $this->createInstallOneOfRule([$package], Rule::RULE_FIXED, [
'package' => $package,
]);
$this->addRule(RuleSet::TYPE_REQUEST, $rule);
}
foreach ($request->getRequires() as $packageName => $constraint) {
if ($platformRequirementFilter->isIgnored($packageName)) {
continue;
} elseif ($platformRequirementFilter instanceof IgnoreListPlatformRequirementFilter) {
$constraint = $platformRequirementFilter->filterConstraint($packageName, $constraint);
}
$packages = $this->pool->whatProvides($packageName, $constraint);
if (\count($packages) > 0) {
foreach ($packages as $package) {
$this->addRulesForPackage($package, $platformRequirementFilter);
}
$rule = $this->createInstallOneOfRule($packages, Rule::RULE_ROOT_REQUIRE, [
'packageName' => $packageName,
'constraint' => $constraint,
]);
$this->addRule(RuleSet::TYPE_REQUEST, $rule);
}
}
}
protected function addRulesForRootAliases(PlatformRequirementFilterInterface $platformRequirementFilter): void
{
foreach ($this->pool->getPackages() as $package) {
// ensure that rules for root alias packages and aliases of packages which were loaded are also loaded
// even if the alias itself isn't required, otherwise a package could be installed without its alias which
// leads to unexpected behavior
if (!isset($this->addedMap[$package->id]) &&
$package instanceof AliasPackage &&
($package->isRootPackageAlias() || isset($this->addedMap[$package->getAliasOf()->id]))
) {
$this->addRulesForPackage($package, $platformRequirementFilter);
}
}
}
public function getRulesFor(Request $request, ?PlatformRequirementFilterInterface $platformRequirementFilter = null): RuleSet
{
$platformRequirementFilter = $platformRequirementFilter ?? PlatformRequirementFilterFactory::ignoreNothing();
$this->addRulesForRequest($request, $platformRequirementFilter);
$this->addRulesForRootAliases($platformRequirementFilter);
$this->addConflictRules($platformRequirementFilter);
// Remove references to packages
$this->addedMap = $this->addedPackagesByNames = [];
$rules = $this->rules;
$this->rules = new RuleSet;
return $rules;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/Rule.php | src/Composer/DependencyResolver/Rule.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver;
use Composer\Package\AliasPackage;
use Composer\Package\BasePackage;
use Composer\Package\Link;
use Composer\Repository\PlatformRepository;
use Composer\Repository\RepositorySet;
use Composer\Package\Version\VersionParser;
use Composer\Semver\Constraint\Constraint;
use Composer\Semver\Constraint\ConstraintInterface;
/**
* @author Nils Adermann <naderman@naderman.de>
* @author Ruben Gonzalez <rubenrua@gmail.com>
* @phpstan-type ReasonData Link|BasePackage|string|int|array{packageName: string, constraint: ConstraintInterface}|array{package: BasePackage}
*/
abstract class Rule
{
// reason constants and // their reason data contents
public const RULE_ROOT_REQUIRE = 2; // array{packageName: string, constraint: ConstraintInterface}
public const RULE_FIXED = 3; // array{package: BasePackage}
public const RULE_PACKAGE_CONFLICT = 6; // Link
public const RULE_PACKAGE_REQUIRES = 7; // Link
public const RULE_PACKAGE_SAME_NAME = 10; // string (package name)
public const RULE_LEARNED = 12; // int (rule id)
public const RULE_PACKAGE_ALIAS = 13; // BasePackage
public const RULE_PACKAGE_INVERSE_ALIAS = 14; // BasePackage
// bitfield defs
private const BITFIELD_TYPE = 0;
private const BITFIELD_REASON = 8;
private const BITFIELD_DISABLED = 16;
/** @var int */
protected $bitfield;
/** @var Request */
protected $request;
/**
* @var Link|BasePackage|ConstraintInterface|string
* @phpstan-var ReasonData
*/
protected $reasonData;
/**
* @param self::RULE_* $reason A RULE_* constant describing the reason for generating this rule
* @param mixed $reasonData
*
* @phpstan-param ReasonData $reasonData
*/
public function __construct($reason, $reasonData)
{
$this->reasonData = $reasonData;
$this->bitfield = (0 << self::BITFIELD_DISABLED) |
($reason << self::BITFIELD_REASON) |
(255 << self::BITFIELD_TYPE);
}
/**
* @return list<int>
*/
abstract public function getLiterals(): array;
/**
* @return int|string
*/
abstract public function getHash();
abstract public function __toString(): string;
abstract public function equals(Rule $rule): bool;
/**
* @return self::RULE_*
*/
public function getReason(): int
{
return ($this->bitfield & (255 << self::BITFIELD_REASON)) >> self::BITFIELD_REASON;
}
/**
* @phpstan-return ReasonData
*/
public function getReasonData()
{
return $this->reasonData;
}
public function getRequiredPackage(): ?string
{
switch ($this->getReason()) {
case self::RULE_ROOT_REQUIRE:
return $this->getReasonData()['packageName'];
case self::RULE_FIXED:
return $this->getReasonData()['package']->getName();
case self::RULE_PACKAGE_REQUIRES:
return $this->getReasonData()->getTarget();
}
return null;
}
/**
* @param RuleSet::TYPE_* $type
*/
public function setType($type): void
{
$this->bitfield = ($this->bitfield & ~(255 << self::BITFIELD_TYPE)) | ((255 & $type) << self::BITFIELD_TYPE);
}
public function getType(): int
{
return ($this->bitfield & (255 << self::BITFIELD_TYPE)) >> self::BITFIELD_TYPE;
}
public function disable(): void
{
$this->bitfield = ($this->bitfield & ~(255 << self::BITFIELD_DISABLED)) | (1 << self::BITFIELD_DISABLED);
}
public function enable(): void
{
$this->bitfield &= ~(255 << self::BITFIELD_DISABLED);
}
public function isDisabled(): bool
{
return 0 !== (($this->bitfield & (255 << self::BITFIELD_DISABLED)) >> self::BITFIELD_DISABLED);
}
public function isEnabled(): bool
{
return 0 === (($this->bitfield & (255 << self::BITFIELD_DISABLED)) >> self::BITFIELD_DISABLED);
}
abstract public function isAssertion(): bool;
public function isCausedByLock(RepositorySet $repositorySet, Request $request, Pool $pool): bool
{
if ($this->getReason() === self::RULE_PACKAGE_REQUIRES) {
if (PlatformRepository::isPlatformPackage($this->getReasonData()->getTarget())) {
return false;
}
if ($request->getLockedRepository() !== null) {
foreach ($request->getLockedRepository()->getPackages() as $package) {
if ($package->getName() === $this->getReasonData()->getTarget()) {
if ($pool->isUnacceptableFixedOrLockedPackage($package)) {
return true;
}
if (!$this->getReasonData()->getConstraint()->matches(new Constraint('=', $package->getVersion()))) {
return true;
}
// required package was locked but has been unlocked and still matches
if (!$request->isLockedPackage($package)) {
return true;
}
break;
}
}
}
}
if ($this->getReason() === self::RULE_ROOT_REQUIRE) {
if (PlatformRepository::isPlatformPackage($this->getReasonData()['packageName'])) {
return false;
}
if ($request->getLockedRepository() !== null) {
foreach ($request->getLockedRepository()->getPackages() as $package) {
if ($package->getName() === $this->getReasonData()['packageName']) {
if ($pool->isUnacceptableFixedOrLockedPackage($package)) {
return true;
}
if (!$this->getReasonData()['constraint']->matches(new Constraint('=', $package->getVersion()))) {
return true;
}
break;
}
}
}
}
return false;
}
/**
* @internal
*/
public function getSourcePackage(Pool $pool): BasePackage
{
$literals = $this->getLiterals();
switch ($this->getReason()) {
case self::RULE_PACKAGE_CONFLICT:
$package1 = $this->deduplicateDefaultBranchAlias($pool->literalToPackage($literals[0]));
$package2 = $this->deduplicateDefaultBranchAlias($pool->literalToPackage($literals[1]));
$reasonData = $this->getReasonData();
// swap literals if they are not in the right order with package2 being the conflicter
if ($reasonData->getSource() === $package1->getName()) {
[$package2, $package1] = [$package1, $package2];
}
return $package2;
case self::RULE_PACKAGE_REQUIRES:
$sourceLiteral = $literals[0];
$sourcePackage = $this->deduplicateDefaultBranchAlias($pool->literalToPackage($sourceLiteral));
return $sourcePackage;
default:
throw new \LogicException('Not implemented');
}
}
/**
* @param BasePackage[] $installedMap
* @param array<Rule[]> $learnedPool
*/
public function getPrettyString(RepositorySet $repositorySet, Request $request, Pool $pool, bool $isVerbose, array $installedMap = [], array $learnedPool = []): string
{
$literals = $this->getLiterals();
switch ($this->getReason()) {
case self::RULE_ROOT_REQUIRE:
$reasonData = $this->getReasonData();
$packageName = $reasonData['packageName'];
$constraint = $reasonData['constraint'];
$packages = $pool->whatProvides($packageName, $constraint);
if (0 === \count($packages)) {
return 'No package found to satisfy root composer.json require '.$packageName.' '.$constraint->getPrettyString();
}
$packagesNonAlias = array_values(array_filter($packages, static function ($p): bool {
return !($p instanceof AliasPackage);
}));
if (\count($packagesNonAlias) === 1) {
$package = $packagesNonAlias[0];
if ($request->isLockedPackage($package)) {
return $package->getPrettyName().' is locked to version '.$package->getPrettyVersion()." and an update of this package was not requested.";
}
}
return 'Root composer.json requires '.$packageName.' '.$constraint->getPrettyString().' -> satisfiable by '.$this->formatPackagesUnique($pool, $packages, $isVerbose, $constraint).'.';
case self::RULE_FIXED:
$package = $this->deduplicateDefaultBranchAlias($this->getReasonData()['package']);
if ($request->isLockedPackage($package)) {
return $package->getPrettyName().' is locked to version '.$package->getPrettyVersion().' and an update of this package was not requested.';
}
return $package->getPrettyName().' is present at version '.$package->getPrettyVersion() . ' and cannot be modified by Composer';
case self::RULE_PACKAGE_CONFLICT:
$package1 = $this->deduplicateDefaultBranchAlias($pool->literalToPackage($literals[0]));
$package2 = $this->deduplicateDefaultBranchAlias($pool->literalToPackage($literals[1]));
$conflictTarget = $package1->getPrettyString();
$reasonData = $this->getReasonData();
// swap literals if they are not in the right order with package2 being the conflicter
if ($reasonData->getSource() === $package1->getName()) {
[$package2, $package1] = [$package1, $package2];
$conflictTarget = $package1->getPrettyName().' '.$reasonData->getPrettyConstraint();
}
// if the conflict is not directly against the package but something it provides/replaces,
// we try to find that link to display a better message
if ($reasonData->getTarget() !== $package1->getName()) {
$provideType = null;
$provided = null;
foreach ($package1->getProvides() as $provide) {
if ($provide->getTarget() === $reasonData->getTarget()) {
$provideType = 'provides';
$provided = $provide->getPrettyConstraint();
break;
}
}
foreach ($package1->getReplaces() as $replace) {
if ($replace->getTarget() === $reasonData->getTarget()) {
$provideType = 'replaces';
$provided = $replace->getPrettyConstraint();
break;
}
}
if (null !== $provideType) {
$conflictTarget = $reasonData->getTarget().' '.$reasonData->getPrettyConstraint().' ('.$package1->getPrettyString().' '.$provideType.' '.$reasonData->getTarget().' '.$provided.')';
}
}
return $package2->getPrettyString().' conflicts with '.$conflictTarget.'.';
case self::RULE_PACKAGE_REQUIRES:
assert(\count($literals) > 0);
$sourceLiteral = array_shift($literals);
$sourcePackage = $this->deduplicateDefaultBranchAlias($pool->literalToPackage($sourceLiteral));
$reasonData = $this->getReasonData();
$requires = [];
foreach ($literals as $literal) {
$requires[] = $pool->literalToPackage($literal);
}
$text = $reasonData->getPrettyString($sourcePackage);
if (\count($requires) > 0) {
$text .= ' -> satisfiable by ' . $this->formatPackagesUnique($pool, $requires, $isVerbose, $reasonData->getConstraint()) . '.';
} else {
$targetName = $reasonData->getTarget();
$reason = Problem::getMissingPackageReason($repositorySet, $request, $pool, $isVerbose, $targetName, $reasonData->getConstraint());
return $text . ' -> ' . $reason[1];
}
return $text;
case self::RULE_PACKAGE_SAME_NAME:
$packageNames = [];
foreach ($literals as $literal) {
$package = $pool->literalToPackage($literal);
$packageNames[$package->getName()] = true;
}
unset($literal);
$replacedName = $this->getReasonData();
if (\count($packageNames) > 1) {
if (!isset($packageNames[$replacedName])) {
$reason = 'They '.(\count($literals) === 2 ? 'both' : 'all').' replace '.$replacedName.' and thus cannot coexist.';
} else {
$replacerNames = $packageNames;
unset($replacerNames[$replacedName]);
$replacerNames = array_keys($replacerNames);
if (\count($replacerNames) === 1) {
$reason = $replacerNames[0] . ' replaces ';
} else {
$reason = '['.implode(', ', $replacerNames).'] replace ';
}
$reason .= $replacedName.' and thus cannot coexist with it.';
}
$installedPackages = [];
$removablePackages = [];
foreach ($literals as $literal) {
if (isset($installedMap[abs($literal)])) {
$installedPackages[] = $pool->literalToPackage($literal);
} else {
$removablePackages[] = $pool->literalToPackage($literal);
}
}
if (\count($installedPackages) > 0 && \count($removablePackages) > 0) {
return $this->formatPackagesUnique($pool, $removablePackages, $isVerbose, null, true).' cannot be installed as that would require removing '.$this->formatPackagesUnique($pool, $installedPackages, $isVerbose, null, true).'. '.$reason;
}
return 'Only one of these can be installed: '.$this->formatPackagesUnique($pool, $literals, $isVerbose, null, true).'. '.$reason;
}
return 'You can only install one version of a package, so only one of these can be installed: ' . $this->formatPackagesUnique($pool, $literals, $isVerbose, null, true) . '.';
case self::RULE_LEARNED:
/** @TODO currently still generates way too much output to be helpful, and in some cases can even lead to endless recursion */
// if (isset($learnedPool[$this->getReasonData()])) {
// echo $this->getReasonData()."\n";
// $learnedString = ', learned rules:' . Problem::formatDeduplicatedRules($learnedPool[$this->getReasonData()], ' ', $repositorySet, $request, $pool, $isVerbose, $installedMap, $learnedPool);
// } else {
// $learnedString = ' (reasoning unavailable)';
// }
$learnedString = ' (conflict analysis result)';
if (\count($literals) === 1) {
$ruleText = $pool->literalToPrettyString($literals[0], $installedMap);
} else {
$groups = [];
foreach ($literals as $literal) {
$package = $pool->literalToPackage($literal);
if (isset($installedMap[$package->id])) {
$group = $literal > 0 ? 'keep' : 'remove';
} else {
$group = $literal > 0 ? 'install' : 'don\'t install';
}
$groups[$group][] = $this->deduplicateDefaultBranchAlias($package);
}
$ruleTexts = [];
foreach ($groups as $group => $packages) {
$ruleTexts[] = $group . (\count($packages) > 1 ? ' one of' : '').' ' . $this->formatPackagesUnique($pool, $packages, $isVerbose);
}
$ruleText = implode(' | ', $ruleTexts);
}
return 'Conclusion: '.$ruleText.$learnedString;
case self::RULE_PACKAGE_ALIAS:
$aliasPackage = $pool->literalToPackage($literals[0]);
// avoid returning content like "9999999-dev is an alias of dev-master" as it is useless
if ($aliasPackage->getVersion() === VersionParser::DEFAULT_BRANCH_ALIAS) {
return '';
}
$package = $this->deduplicateDefaultBranchAlias($pool->literalToPackage($literals[1]));
return $aliasPackage->getPrettyString() .' is an alias of '.$package->getPrettyString().' and thus requires it to be installed too.';
case self::RULE_PACKAGE_INVERSE_ALIAS:
// inverse alias rules work the other way around than above
$aliasPackage = $pool->literalToPackage($literals[1]);
// avoid returning content like "9999999-dev is an alias of dev-master" as it is useless
if ($aliasPackage->getVersion() === VersionParser::DEFAULT_BRANCH_ALIAS) {
return '';
}
$package = $this->deduplicateDefaultBranchAlias($pool->literalToPackage($literals[0]));
return $aliasPackage->getPrettyString() .' is an alias of '.$package->getPrettyString().' and must be installed with it.';
default:
$ruleText = '';
foreach ($literals as $i => $literal) {
if ($i !== 0) {
$ruleText .= '|';
}
$ruleText .= $pool->literalToPrettyString($literal, $installedMap);
}
return '('.$ruleText.')';
}
}
/**
* @param array<int|BasePackage> $literalsOrPackages An array containing packages or literals
*/
protected function formatPackagesUnique(Pool $pool, array $literalsOrPackages, bool $isVerbose, ?ConstraintInterface $constraint = null, bool $useRemovedVersionGroup = false): string
{
$packages = [];
foreach ($literalsOrPackages as $package) {
$packages[] = \is_object($package) ? $package : $pool->literalToPackage($package);
}
return Problem::getPackageList($packages, $isVerbose, $pool, $constraint, $useRemovedVersionGroup);
}
private function deduplicateDefaultBranchAlias(BasePackage $package): BasePackage
{
if ($package instanceof AliasPackage && $package->getPrettyVersion() === VersionParser::DEFAULT_BRANCH_ALIAS) {
$package = $package->getAliasOf();
}
return $package;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/Operation/UpdateOperation.php | src/Composer/DependencyResolver/Operation/UpdateOperation.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver\Operation;
use Composer\Package\PackageInterface;
use Composer\Package\Version\VersionParser;
/**
* Solver update operation.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
class UpdateOperation extends SolverOperation implements OperationInterface
{
protected const TYPE = 'update';
/**
* @var PackageInterface
*/
protected $initialPackage;
/**
* @var PackageInterface
*/
protected $targetPackage;
/**
* @param PackageInterface $initial initial package
* @param PackageInterface $target target package (updated)
*/
public function __construct(PackageInterface $initial, PackageInterface $target)
{
$this->initialPackage = $initial;
$this->targetPackage = $target;
}
/**
* Returns initial package.
*/
public function getInitialPackage(): PackageInterface
{
return $this->initialPackage;
}
/**
* Returns target package.
*/
public function getTargetPackage(): PackageInterface
{
return $this->targetPackage;
}
/**
* @inheritDoc
*/
public function show($lock): string
{
return self::format($this->initialPackage, $this->targetPackage, $lock);
}
public static function format(PackageInterface $initialPackage, PackageInterface $targetPackage, bool $lock = false): string
{
$fromVersion = $initialPackage->getFullPrettyVersion();
$toVersion = $targetPackage->getFullPrettyVersion();
if ($fromVersion === $toVersion && $initialPackage->getSourceReference() !== $targetPackage->getSourceReference()) {
$fromVersion = $initialPackage->getFullPrettyVersion(true, PackageInterface::DISPLAY_SOURCE_REF);
$toVersion = $targetPackage->getFullPrettyVersion(true, PackageInterface::DISPLAY_SOURCE_REF);
} elseif ($fromVersion === $toVersion && $initialPackage->getDistReference() !== $targetPackage->getDistReference()) {
$fromVersion = $initialPackage->getFullPrettyVersion(true, PackageInterface::DISPLAY_DIST_REF);
$toVersion = $targetPackage->getFullPrettyVersion(true, PackageInterface::DISPLAY_DIST_REF);
}
$actionName = VersionParser::isUpgrade($initialPackage->getVersion(), $targetPackage->getVersion()) ? 'Upgrading' : 'Downgrading';
return $actionName.' <info>'.$initialPackage->getPrettyName().'</info> (<comment>'.$fromVersion.'</comment> => <comment>'.$toVersion.'</comment>)';
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/Operation/OperationInterface.php | src/Composer/DependencyResolver/Operation/OperationInterface.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver\Operation;
/**
* Solver operation interface.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
interface OperationInterface
{
/**
* Returns operation type.
*
* @return string
*/
public function getOperationType();
/**
* Serializes the operation in a human readable format
*
* @param bool $lock Whether this is an operation on the lock file
* @return string
*/
public function show(bool $lock);
/**
* Serializes the operation in a human readable format
*
* @return string
*/
public function __toString();
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/Operation/UninstallOperation.php | src/Composer/DependencyResolver/Operation/UninstallOperation.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver\Operation;
use Composer\Package\PackageInterface;
/**
* Solver uninstall operation.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
class UninstallOperation extends SolverOperation implements OperationInterface
{
protected const TYPE = 'uninstall';
/**
* @var PackageInterface
*/
protected $package;
public function __construct(PackageInterface $package)
{
$this->package = $package;
}
/**
* Returns package instance.
*/
public function getPackage(): PackageInterface
{
return $this->package;
}
/**
* @inheritDoc
*/
public function show($lock): string
{
return self::format($this->package, $lock);
}
public static function format(PackageInterface $package, bool $lock = false): string
{
return 'Removing <info>'.$package->getPrettyName().'</info> (<comment>'.$package->getFullPrettyVersion().'</comment>)';
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/Operation/MarkAliasInstalledOperation.php | src/Composer/DependencyResolver/Operation/MarkAliasInstalledOperation.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver\Operation;
use Composer\Package\AliasPackage;
/**
* Solver install operation.
*
* @author Nils Adermann <naderman@naderman.de>
*/
class MarkAliasInstalledOperation extends SolverOperation implements OperationInterface
{
protected const TYPE = 'markAliasInstalled';
/**
* @var AliasPackage
*/
protected $package;
public function __construct(AliasPackage $package)
{
$this->package = $package;
}
/**
* Returns package instance.
*/
public function getPackage(): AliasPackage
{
return $this->package;
}
/**
* @inheritDoc
*/
public function show($lock): string
{
return 'Marking <info>'.$this->package->getPrettyName().'</info> (<comment>'.$this->package->getFullPrettyVersion().'</comment>) as installed, alias of <info>'.$this->package->getAliasOf()->getPrettyName().'</info> (<comment>'.$this->package->getAliasOf()->getFullPrettyVersion().'</comment>)';
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/Operation/MarkAliasUninstalledOperation.php | src/Composer/DependencyResolver/Operation/MarkAliasUninstalledOperation.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver\Operation;
use Composer\Package\AliasPackage;
/**
* Solver install operation.
*
* @author Nils Adermann <naderman@naderman.de>
*/
class MarkAliasUninstalledOperation extends SolverOperation implements OperationInterface
{
protected const TYPE = 'markAliasUninstalled';
/**
* @var AliasPackage
*/
protected $package;
public function __construct(AliasPackage $package)
{
$this->package = $package;
}
/**
* Returns package instance.
*/
public function getPackage(): AliasPackage
{
return $this->package;
}
/**
* @inheritDoc
*/
public function show($lock): string
{
return 'Marking <info>'.$this->package->getPrettyName().'</info> (<comment>'.$this->package->getFullPrettyVersion().'</comment>) as uninstalled, alias of <info>'.$this->package->getAliasOf()->getPrettyName().'</info> (<comment>'.$this->package->getAliasOf()->getFullPrettyVersion().'</comment>)';
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/DependencyResolver/Operation/SolverOperation.php | src/Composer/DependencyResolver/Operation/SolverOperation.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\DependencyResolver\Operation;
/**
* Abstract operation class.
*
* @author Aleksandr Bezpiatov <aleksandr.bezpiatov@spryker.com>
*/
abstract class SolverOperation implements OperationInterface
{
/**
* @abstract must be redefined by extending classes
*/
protected const TYPE = '';
/**
* Returns operation type.
*/
public function getOperationType(): string
{
return static::TYPE;
}
/**
* @inheritDoc
*/
public function __toString()
{
return $this->show(false);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.