aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/shirabe/src/factory.rs
blob: 6dc2fbd032ee448dafc92288ee3127a844f0432b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
//! ref: composer/src/Composer/Factory.php

use indexmap::IndexMap;

use shirabe_external_packages::symfony::component::console::formatter::output_formatter::OutputFormatter;
use shirabe_external_packages::symfony::component::console::formatter::output_formatter_style::OutputFormatterStyle;
use shirabe_external_packages::symfony::component::console::output::console_output::ConsoleOutput;
use shirabe_php_shim::{
    InvalidArgumentException, PATHINFO_EXTENSION, PHP_EOL, Phar, PhpMixed, RuntimeException,
    UnexpectedValueException, ZipArchive, array_keys, array_replace_recursive, class_exists,
    dirname, extension_loaded, file_exists, file_get_contents, file_put_contents, implode,
    in_array, is_array, is_dir, is_file, is_string, json_decode, pathinfo, realpath, str_replace,
    strpos, strtr, substr, trim,
};

use crate::autoload::autoload_generator::AutoloadGenerator;
use crate::cache::Cache;
use crate::composer::Composer;
use crate::config::Config;
use crate::config::json_config_source::JsonConfigSource;
use crate::downloader::download_manager::DownloadManager;
use crate::downloader::file_downloader::FileDownloader;
use crate::downloader::fossil_downloader::FossilDownloader;
use crate::downloader::git_downloader::GitDownloader;
use crate::downloader::gzip_downloader::GzipDownloader;
use crate::downloader::hg_downloader::HgDownloader;
use crate::downloader::path_downloader::PathDownloader;
use crate::downloader::perforce_downloader::PerforceDownloader;
use crate::downloader::phar_downloader::PharDownloader;
use crate::downloader::rar_downloader::RarDownloader;
use crate::downloader::svn_downloader::SvnDownloader;
use crate::downloader::tar_downloader::TarDownloader;
use crate::downloader::transport_exception::TransportException;
use crate::downloader::xz_downloader::XzDownloader;
use crate::downloader::zip_downloader::ZipDownloader;
use crate::event_dispatcher::event::Event;
use crate::event_dispatcher::event_dispatcher::EventDispatcher;
use crate::exception::no_ssl_exception::NoSslException;
use crate::installer::binary_installer::BinaryInstaller;
use crate::installer::installation_manager::InstallationManager;
use crate::installer::library_installer::LibraryInstaller;
use crate::installer::metapackage_installer::MetapackageInstaller;
use crate::installer::plugin_installer::PluginInstaller;
use crate::io::io_interface::IOInterface;
use crate::json::json_file::JsonFile;
use crate::json::json_validation_exception::JsonValidationException;
use crate::package::archiver::archive_manager::ArchiveManager;
use crate::package::archiver::phar_archiver::PharArchiver;
use crate::package::archiver::zip_archiver::ZipArchiver;
use crate::package::loader::root_package_loader::RootPackageLoader;
use crate::package::locker::Locker;
use crate::package::root_package_interface::RootPackageInterface;
use crate::package::version::version_guesser::VersionGuesser;
use crate::package::version::version_parser::VersionParser;
use crate::partial_composer::PartialComposer;
use crate::plugin::plugin_events::PluginEvents;
use crate::plugin::plugin_manager::PluginManager;
use crate::repository::filesystem_repository::FilesystemRepository;
use crate::repository::installed_filesystem_repository::InstalledFilesystemRepository;
use crate::repository::installed_repository_interface::InstalledRepositoryInterface;
use crate::repository::repository_factory::RepositoryFactory;
use crate::repository::repository_manager::RepositoryManager;
use crate::util::filesystem::Filesystem;
use crate::util::http_downloader::HttpDownloader;
use crate::util::r#loop::Loop;
use crate::util::platform::Platform;
use crate::util::process_executor::ProcessExecutor;
use crate::util::silencer::Silencer;

/// Either a configuration array or a filename to read from. PHP's `$localConfig` accepts both.
pub enum LocalConfigInput {
    Path(String),
    Data(IndexMap<String, PhpMixed>),
}

/// PHP's `$disablePlugins` accepts `bool|'local'|'global'`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DisablePlugins {
    None,
    All,
    Local,
    Global,
}

impl DisablePlugins {
    fn is_disabled_at_all(self) -> bool {
        !matches!(self, DisablePlugins::None)
    }
}

/// Creates a configured instance of composer.
pub struct Factory;

impl Factory {
    fn get_home_dir() -> anyhow::Result<String> {
        let home = Platform::get_env("COMPOSER_HOME");
        if let Some(h) = home {
            if !h.is_empty() {
                return Ok(h);
            }
        }

        if Platform::is_windows() {
            if Platform::get_env("APPDATA")
                .map(|s| s.is_empty())
                .unwrap_or(true)
            {
                return Err(anyhow::anyhow!(RuntimeException {
                    message:
                        "The APPDATA or COMPOSER_HOME environment variable must be set for composer to run correctly"
                            .to_string(),
                    code: 0,
                }));
            }

            let appdata = Platform::get_env("APPDATA").unwrap_or_default();
            return Ok(format!(
                "{}/Composer",
                trim(&strtr(&appdata, "\\", "/"), Some("/"))
            ));
        }

        let user_dir = Self::get_user_dir()?;
        let mut dirs: Vec<String> = Vec::new();

        if Self::use_xdg() {
            // XDG Base Directory Specifications
            let mut xdg_config = Platform::get_env("XDG_CONFIG_HOME").unwrap_or_default();
            if xdg_config.is_empty() {
                xdg_config = format!("{}/.config", user_dir);
            }

            dirs.push(format!("{}/composer", xdg_config));
        }

        dirs.push(format!("{}/.composer", user_dir));

        // select first dir which exists of: $XDG_CONFIG_HOME/composer or ~/.composer
        for dir in &dirs {
            let dir_copy = dir.clone();
            let exists =
                Silencer::call(|| Ok::<bool, anyhow::Error>(is_dir(&dir_copy))).unwrap_or(false);
            if exists {
                return Ok(dir.clone());
            }
        }

        // if none exists, we default to first defined one (XDG one if system uses it, or ~/.composer otherwise)
        Ok(dirs[0].clone())
    }

    fn get_cache_dir(home: &str) -> anyhow::Result<String> {
        let cache_dir = Platform::get_env("COMPOSER_CACHE_DIR").unwrap_or_default();
        if !cache_dir.is_empty() {
            return Ok(cache_dir);
        }

        let home_env = Platform::get_env("COMPOSER_HOME").unwrap_or_default();
        if !home_env.is_empty() {
            return Ok(format!("{}/cache", home_env));
        }

        if Platform::is_windows() {
            let mut cache_dir = Platform::get_env("LOCALAPPDATA").unwrap_or_default();
            if !cache_dir.is_empty() {
                cache_dir = format!("{}/Composer", cache_dir);
            } else {
                cache_dir = format!("{}/cache", home);
            }

            return Ok(trim(&strtr(&cache_dir, "\\", "/"), Some("/")));
        }

        let user_dir = Self::get_user_dir()?;
        if Platform::php_os() == "Darwin" {
            // Migrate existing cache dir in old location if present
            if is_dir(&format!("{}/cache", home))
                && !is_dir(&format!("{}/Library/Caches/composer", user_dir))
            {
                let from = format!("{}/cache", home);
                let to = format!("{}/Library/Caches/composer", user_dir);
                let _ = Silencer::call(|| Ok::<bool, anyhow::Error>(Platform::rename(&from, &to)));
            }

            return Ok(format!("{}/Library/Caches/composer", user_dir));
        }

        if home == format!("{}/.composer", user_dir).as_str() && is_dir(&format!("{}/cache", home))
        {
            return Ok(format!("{}/cache", home));
        }

        if Self::use_xdg() {
            let xdg_cache = Platform::get_env("XDG_CACHE_HOME").unwrap_or_default();
            let xdg_cache = if xdg_cache.is_empty() {
                format!("{}/.cache", user_dir)
            } else {
                xdg_cache
            };

            return Ok(format!("{}/composer", xdg_cache));
        }

        Ok(format!("{}/cache", home))
    }

    fn get_data_dir(home: &str) -> anyhow::Result<String> {
        let home_env = Platform::get_env("COMPOSER_HOME").unwrap_or_default();
        if !home_env.is_empty() {
            return Ok(home_env);
        }

        if Platform::is_windows() {
            return Ok(strtr(home, "\\", "/"));
        }

        let user_dir = Self::get_user_dir()?;
        if home != format!("{}/.composer", user_dir) && Self::use_xdg() {
            let xdg_data = Platform::get_env("XDG_DATA_HOME").unwrap_or_default();
            let xdg_data = if xdg_data.is_empty() {
                format!("{}/.local/share", user_dir)
            } else {
                xdg_data
            };

            return Ok(format!("{}/composer", xdg_data));
        }

        Ok(home.to_string())
    }

    pub fn create_config(
        io: Option<&dyn IOInterface>,
        cwd: Option<&str>,
    ) -> anyhow::Result<Config> {
        let cwd = match cwd {
            Some(s) => s.to_string(),
            None => Platform::get_cwd(true)?,
        };

        let mut config = Config::new(true, Some(cwd));

        // determine and add main dirs to the config
        let home = Self::get_home_dir()?;
        let mut defaults: IndexMap<String, PhpMixed> = IndexMap::new();
        let mut inner: IndexMap<String, PhpMixed> = IndexMap::new();
        inner.insert("home".to_string(), PhpMixed::String(home.clone()));
        inner.insert(
            "cache-dir".to_string(),
            PhpMixed::String(Self::get_cache_dir(&home)?),
        );
        inner.insert(
            "data-dir".to_string(),
            PhpMixed::String(Self::get_data_dir(&home)?),
        );
        defaults.insert(
            "config".to_string(),
            PhpMixed::Array(inner.into_iter().map(|(k, v)| (k, Box::new(v))).collect()),
        );
        config.merge(&defaults, Config::SOURCE_DEFAULT);

        // load global config
        let global_config_path = format!("{}/config.json", config.get_str("home")?);
        let mut file = JsonFile::new(global_config_path.clone(), None, io.map(|i| i.clone_box()))?;
        if file.exists() {
            if let Some(io_ref) = io {
                io_ref.write_error3(
                    &format!("Loading config file {}", file.get_path()),
                    true,
                    crate::io::io_interface::DEBUG,
                );
            }
            // TODO(phase-b): validate_json_schema takes ownership of JsonFile; recreate it
            Self::validate_json_schema(
                io,
                ValidateJsonInput::File(JsonFile::new(
                    global_config_path.clone(),
                    None,
                    io.map(|i| i.clone_box()),
                )?),
                JsonFile::LAX_SCHEMA,
                None,
            )?;
            let read_data = match file.read()? {
                PhpMixed::Array(map) => map
                    .into_iter()
                    .map(|(k, v)| (k, *v))
                    .collect::<IndexMap<_, _>>(),
                _ => IndexMap::new(),
            };
            let file_path_owned = file.get_path().to_string();
            config.merge(&read_data, &file_path_owned);
        }
        // TODO(phase-b): set_config_source takes Box<dyn ConfigSourceInterface>
        config.set_config_source(Box::new(JsonConfigSource::new(file, false)));

        let htaccess_protect = config.get("htaccess-protect").as_bool().unwrap_or(false);
        if htaccess_protect {
            // 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
            let dirs = [
                config.get_str("home")?,
                config.get_str("cache-dir")?,
                config.get_str("data-dir")?,
            ];
            for dir in &dirs {
                if !file_exists(&format!("{}/.htaccess", dir)) {
                    if !is_dir(dir) {
                        let dir_owned = dir.clone();
                        let _ = Silencer::call(|| {
                            Ok::<bool, anyhow::Error>(Platform::mkdir(&dir_owned, 0o777, true))
                        });
                    }
                    let path = format!("{}/.htaccess", dir);
                    let _ = Silencer::call(|| {
                        Ok::<Option<i64>, anyhow::Error>(file_put_contents(&path, b"Deny from all"))
                    });
                }
            }
        }

        // load global auth file
        let auth_file_path = format!("{}/auth.json", config.get_str("home")?);
        let mut auth_file = JsonFile::new(auth_file_path.clone(), None, io.map(|i| i.clone_box()))?;
        if auth_file.exists() {
            if let Some(io_ref) = io {
                io_ref.write_error3(
                    &format!("Loading config file {}", auth_file.get_path()),
                    true,
                    crate::io::io_interface::DEBUG,
                );
            }
            // TODO(phase-b): validate_json_schema takes ownership; recreate JsonFile
            Self::validate_json_schema(
                io,
                ValidateJsonInput::File(JsonFile::new(
                    auth_file_path.clone(),
                    None,
                    io.map(|i| i.clone_box()),
                )?),
                JsonFile::AUTH_SCHEMA,
                None,
            )?;
            let read_data: IndexMap<String, PhpMixed> = match auth_file.read()? {
                PhpMixed::Array(map) => map.into_iter().map(|(k, v)| (k, *v)).collect(),
                _ => IndexMap::new(),
            };
            let mut wrapped: IndexMap<String, PhpMixed> = IndexMap::new();
            wrapped.insert(
                "config".to_string(),
                PhpMixed::Array(
                    read_data
                        .into_iter()
                        .map(|(k, v)| (k, Box::new(v)))
                        .collect(),
                ),
            );
            let auth_path_owned = auth_file.get_path().to_string();
            config.merge(&wrapped, &auth_path_owned);
        }
        // TODO(phase-b): set_auth_config_source takes Box<dyn ConfigSourceInterface>
        config.set_auth_config_source(Box::new(JsonConfigSource::new(auth_file, true)));

        Self::load_composer_auth_env(&mut config, io)?;

        Ok(config)
    }

    pub fn get_composer_file() -> anyhow::Result<String> {
        let env = Platform::get_env("COMPOSER");
        if let Some(env_str) = env {
            let env_trimmed = trim(&env_str, Some(" \t\n\r\0\u{0B}"));
            if env_trimmed != "" {
                if is_dir(&env_trimmed) {
                    return Err(anyhow::anyhow!(RuntimeException {
                        message: format!(
                            "The COMPOSER environment variable is set to {} which is a directory, this variable should point to a composer.json or be left unset.",
                            env_trimmed
                        ),
                        code: 0,
                    }));
                }

                return Ok(env_trimmed);
            }
        }

        Ok("./composer.json".to_string())
    }

    pub fn get_lock_file(composer_file: &str) -> String {
        let ext = pathinfo(
            PhpMixed::String(composer_file.to_string()),
            PATHINFO_EXTENSION,
        );
        let is_json = match ext {
            PhpMixed::String(s) => s == "json",
            _ => false,
        };
        if is_json {
            format!(
                "{}lock",
                substr(composer_file, 0, Some(composer_file.len() as i64 - 4))
            )
        } else {
            format!("{}.lock", composer_file)
        }
    }

    pub fn create_additional_styles() -> IndexMap<String, OutputFormatterStyle> {
        let mut styles: IndexMap<String, OutputFormatterStyle> = IndexMap::new();
        styles.insert(
            "highlight".to_string(),
            OutputFormatterStyle::new(Some("red"), None, Some(vec![])),
        );
        styles.insert(
            "warning".to_string(),
            OutputFormatterStyle::new(Some("black"), Some("yellow"), Some(vec![])),
        );
        styles
    }

    pub fn create_output() -> ConsoleOutput {
        let _styles = Self::create_additional_styles();
        // TODO(phase-b): OutputFormatter::new signature and ConsoleOutput::new_with_formatter missing
        todo!(
            "create_output: wire OutputFormatter into ConsoleOutput once the symfony console stubs are completed"
        )
    }

    /// Creates a Composer instance
    pub fn create_composer(
        &self,
        io: &dyn IOInterface,
        local_config: Option<LocalConfigInput>,
        disable_plugins: DisablePlugins,
        cwd: Option<&str>,
        full_load: bool,
        disable_scripts: bool,
    ) -> anyhow::Result<PartialComposerOrComposer> {
        // if a custom composer.json path is given, we change the default cwd to be that file's directory
        let mut local_config = local_config;
        let mut cwd = cwd.map(|s| s.to_string());
        if let Some(LocalConfigInput::Path(ref s)) = local_config {
            if is_file(s) && cwd.is_none() {
                cwd = Some(dirname(s));
            }
        }

        let cwd = match cwd {
            Some(s) => s,
            None => Platform::get_cwd(true)?,
        };

        // load Composer configuration
        if local_config.is_none() {
            local_config = Some(LocalConfigInput::Path(Self::get_composer_file()?));
        }

        let mut local_config_source = Config::SOURCE_UNKNOWN.to_string();
        let mut composer_file: Option<String> = None;
        let mut local_config_data: IndexMap<String, PhpMixed> = IndexMap::new();
        if let Some(LocalConfigInput::Path(path)) = &local_config {
            composer_file = Some(path.clone());

            let mut file = JsonFile::new(path.clone(), None, Some(io.clone_box()))?;

            if !file.exists() {
                let message = if path == "./composer.json" || path == "composer.json" {
                    format!("Composer could not find a composer.json file in {}", cwd)
                } else {
                    format!("Composer could not find the config file: {}", path)
                };
                let instructions = if full_load {
                    "To initialize a project, please create a composer.json file. See https://getcomposer.org/basic-usage"
                } else {
                    ""
                };
                return Err(anyhow::anyhow!(InvalidArgumentException {
                    message: format!("{}{}{}", message, PHP_EOL, instructions),
                    code: 0,
                }));
            }

            if !Platform::is_input_completion_process() {
                if let Err(e) = file.validate_schema(JsonFile::LAX_SCHEMA, None) {
                    if let Some(jve) = e.downcast_ref::<JsonValidationException>() {
                        let errors = format!(
                            " - {}",
                            implode(&format!("{} - ", PHP_EOL), jve.get_errors())
                        );
                        let message = format!("{}:{}{}", jve.get_message(), PHP_EOL, errors);
                        return Err(anyhow::anyhow!(JsonValidationException::new(
                            message,
                            jve.get_errors().clone(),
                        )));
                    }
                    return Err(e);
                }
            }

            local_config_data = file
                .read()?
                .as_array()
                .map(|m| m.iter().map(|(k, v)| (k.clone(), (**v).clone())).collect())
                .unwrap_or_default();
            local_config_source = file.get_path().to_string();
        } else if let Some(LocalConfigInput::Data(data)) = local_config {
            local_config_data = data;
        }

        // Load config and override with local config/auth config
        let mut config = Self::create_config(Some(io), Some(&cwd))?;
        let is_global = local_config_source != Config::SOURCE_UNKNOWN
            && realpath(&config.get_str("home")?) == realpath(&dirname(&local_config_source));
        config.merge(&local_config_data, &local_config_source);

        if let Some(ref composer_file_path) = composer_file {
            io.write_error3(
                &format!(
                    "Loading config file {} ({})",
                    composer_file_path,
                    realpath(composer_file_path).unwrap_or_default()
                ),
                true,
                crate::io::io_interface::DEBUG,
            );
            config.set_config_source(Box::new(JsonConfigSource::new(
                JsonFile::new(
                    realpath(composer_file_path).unwrap_or_default(),
                    None,
                    Some(io.clone_box()),
                )?,
                false,
            )));

            let mut local_auth_file = JsonFile::new(
                format!(
                    "{}/auth.json",
                    dirname(&realpath(composer_file_path).unwrap_or_default())
                ),
                None,
                Some(io.clone_box()),
            )?;
            if local_auth_file.exists() {
                io.write_error3(
                    &format!("Loading config file {}", local_auth_file.get_path()),
                    true,
                    crate::io::io_interface::DEBUG,
                );
                // TODO(phase-b): validate_json_schema/ValidateJsonInput::File expects an owned
                // JsonFile (PHP class semantics share refs); needs Rc<RefCell<JsonFile>> refactor.
                let _ = &local_auth_file;
                let auth_read = local_auth_file.read()?;
                let mut wrapped: IndexMap<String, PhpMixed> = IndexMap::new();
                wrapped.insert("config".to_string(), auth_read);
                let auth_path = local_auth_file.get_path().to_string();
                config.merge(&wrapped, &auth_path);
                config.set_local_auth_config_source(Box::new(JsonConfigSource::new(
                    local_auth_file,
                    true,
                )));
            }
        }

        // make sure we load the auth env again over the local auth.json + composer.json config
        Self::load_composer_auth_env(&mut config, Some(io))?;

        let vendor_dir = config.get_str("vendor-dir")?;

        // wrap config into Rc<RefCell<...>> for shared ownership across composer + downloaders/utils
        let config = std::rc::Rc::new(std::cell::RefCell::new(config));

        // initialize composer
        let mut composer: PartialComposerOrComposer = if full_load {
            PartialComposerOrComposer::Full(Composer::new())
        } else {
            PartialComposerOrComposer::Partial(PartialComposer::default())
        };
        composer.set_config(std::rc::Rc::clone(&config));
        if is_global {
            composer.set_global();
        }

        if full_load {
            // load auth configs into the IO instance
            // TODO(phase-b): load_configuration requires &mut IOInterface; create_composer takes &dyn IOInterface
            // io.load_configuration(&mut *config.borrow_mut())?;

            // 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
            let installed_versions_path = format!(
                "{}/composer/installed.php",
                config.borrow_mut().get_str("vendor-dir")?
            );
            if !disable_plugins.is_disabled_at_all()
                && !disable_scripts
                && !class_exists("Composer\\InstalledVersions")
                && file_exists(&installed_versions_path)
            {
                // 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::safely_load_installed_versions(&installed_versions_path);
                }
            }
        }

        let http_downloader = std::rc::Rc::new(std::cell::RefCell::new(
            Self::create_http_downloader(io, &config, IndexMap::new())?,
        ));
        let process = std::rc::Rc::new(std::cell::RefCell::new(ProcessExecutor::new(Some(
            io.clone_box(),
        ))));
        let r#loop = std::rc::Rc::new(std::cell::RefCell::new(Loop::new(
            std::rc::Rc::clone(&http_downloader),
            Some(std::rc::Rc::clone(&process)),
        )));
        composer.set_loop(r#loop.clone());

        // initialize event dispatcher
        let dispatcher = {
            let mut d = EventDispatcher::new(
                composer.as_partial(),
                io.clone_box(),
                Some(std::rc::Rc::clone(&process)),
            );
            d.set_run_scripts(!disable_scripts);
            std::rc::Rc::new(std::cell::RefCell::new(d))
        };
        composer.set_event_dispatcher(std::rc::Rc::clone(&dispatcher));

        // initialize repository manager
        let mut rm = RepositoryFactory::manager(
            io,
            &config,
            Some(std::rc::Rc::clone(&http_downloader)),
            Some(std::rc::Rc::clone(&dispatcher)),
            Some(std::rc::Rc::clone(&process)),
        )?;

        // force-set the version of the global package if not defined as
        // guessing it adds no value and only takes time
        if !full_load && !local_config_data.contains_key("version") {
            local_config_data.insert("version".to_string(), PhpMixed::String("1.0.0".to_string()));
        }

        // load package
        let parser = VersionParser::new();
        let guesser = VersionGuesser::new(
            std::rc::Rc::clone(&config),
            std::rc::Rc::clone(&process),
            parser.clone(),
            Some(io.clone_box()),
        );
        // TODO(phase-b): RepositoryManager is a PHP class — both composer.set_repository_manager()
        // and self.load_root_package() want ownership. Use a placeholder rm for the loader.
        let mut loader = self.load_root_package(
            todo!("share RepositoryManager via Rc<RefCell<>>"),
            std::rc::Rc::clone(&config),
            parser,
            guesser,
            io.clone_box(),
        );
        let package = loader.load(
            local_config_data
                .iter()
                .map(|(k, v)| (k.clone(), Box::new(v.clone())))
                .collect(),
            "Composer\\Package\\RootPackage",
            Some(&cwd),
        )?;
        // TODO(phase-b): set_package expects RootPackageInterface; loader returns BasePackage
        // composer.set_package(package);
        let _ = package;

        // load local repository
        self.add_local_repository(
            io,
            &mut rm,
            &vendor_dir,
            composer.get_package(),
            Some(&process),
        );
        composer.set_repository_manager(rm);

        // initialize installation manager
        let im = self.create_installation_manager(
            r#loop.clone(),
            io.clone_box(),
            Some(std::rc::Rc::clone(&dispatcher)),
        );
        // TODO(phase-b): set_installation_manager takes ownership; im needs sharing for create_default_installers
        composer.set_installation_manager(im);

        if let PartialComposerOrComposer::Full(ref mut composer_full) = composer {
            // initialize download manager
            let dm = self.create_download_manager(
                io,
                &config,
                &http_downloader,
                &process,
                Some(&dispatcher),
            )?;
            composer_full.set_download_manager(dm.clone());

            // initialize autoload generator
            let generator =
                AutoloadGenerator::new(std::rc::Rc::clone(&dispatcher), Some(io.clone_box()));
            composer_full.set_autoload_generator(generator);

            // initialize archive manager
            let am = self.create_archive_manager(&*config.borrow(), &dm, &r#loop)?;
            composer_full.set_archive_manager(am);
        }

        // add installers to the manager (must happen after download manager is created since they read it out of $composer)
        self.create_default_installers(&im, &composer, io, Some(&process));

        // init locker if possible
        if let PartialComposerOrComposer::Full(ref mut composer_full) = composer {
            if let Some(ref composer_file_path) = composer_file {
                let lock_file = Self::get_lock_file(composer_file_path);
                let lock_enabled = config
                    .borrow_mut()
                    .get("lock")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(true);
                if !lock_enabled && file_exists(&lock_file) {
                    io.write_error3(
                        &format!(
                            "<warning>{} is present but ignored as the \"lock\" config option is disabled.</warning>",
                            lock_file
                        ),
                        true,
                        crate::io::io_interface::NORMAL,
                    );
                }

                // TODO(phase-b): InstallationManager is a PHP class — needs Rc<RefCell<>> sharing
                let locker = Locker::new(
                    io.clone_box(),
                    JsonFile::new(
                        if lock_enabled {
                            lock_file
                        } else {
                            Platform::get_dev_null()
                        },
                        None,
                        Some(io.clone_box()),
                    )?,
                    todo!("InstallationManager clone"),
                    &file_get_contents(composer_file_path).unwrap_or_default(),
                    std::rc::Rc::clone(&process),
                );
                composer_full.set_locker(locker);
            } else {
                let lock_contents = JsonFile::encode(
                    &PhpMixed::Array(
                        local_config_data
                            .iter()
                            .map(|(k, v)| (k.clone(), Box::new(v.clone())))
                            .collect(),
                    ),
                    448,
                );
                // TODO(phase-b): InstallationManager is a PHP class — needs Rc<RefCell<>> sharing
                let locker = Locker::new(
                    io.clone_box(),
                    JsonFile::new(Platform::get_dev_null(), None, Some(io.clone_box()))?,
                    todo!("InstallationManager clone"),
                    &lock_contents,
                    std::rc::Rc::clone(&process),
                );
                composer_full.set_locker(locker);
            }
        }

        if let PartialComposerOrComposer::Full(ref mut composer_full) = composer {
            let mut global_composer: Option<PartialComposer> = None;
            if !composer_full.is_global() {
                global_composer = self.create_global_composer(
                    io,
                    &*config.borrow(),
                    disable_plugins,
                    disable_scripts,
                    false,
                );
            }

            let mut pm = self.create_plugin_manager(
                io,
                composer_full,
                global_composer.as_ref(),
                disable_plugins,
            );
            // TODO(phase-b): PluginManager is a PHP class; sharing pm before transferring requires Rc<RefCell<>>
            if composer_full.is_global() {
                pm.set_running_in_global_dir(true);
            }
            pm.load_installed_plugins();
            composer_full.set_plugin_manager(pm);
        }

        if full_load {
            let init_event = Event::from_name(PluginEvents::INIT.to_string());
            composer
                .get_event_dispatcher()
                .borrow_mut()
                .dispatch(Some(init_event.get_name()), Some(init_event))?;

            // once everything is initialized we can
            // purge packages from local repos if they have been deleted on the filesystem
            // TODO(phase-b): rm and im are owned by composer at this point; need to access via composer
            // self.purge_packages(rm.get_local_repository(), &mut im)?;
        }

        Ok(composer)
    }

    pub fn create_global(
        io: &dyn IOInterface,
        disable_plugins: DisablePlugins,
        disable_scripts: bool,
    ) -> Option<Composer> {
        let factory = Self;

        let config = Self::create_config(Some(io), None).ok()?;
        factory
            .create_global_composer(io, &config, disable_plugins, disable_scripts, true)
            .and_then(|pc| match pc {
                _ => None, // TODO(phase-b): downcast PartialComposer to Composer when fullLoad=true
            })
    }

    fn add_local_repository(
        &self,
        io: &dyn IOInterface,
        rm: &mut RepositoryManager,
        vendor_dir: &str,
        root_package: &dyn RootPackageInterface,
        process: Option<&std::rc::Rc<std::cell::RefCell<ProcessExecutor>>>,
    ) {
        let fs = process.map(|p| {
            std::rc::Rc::new(std::cell::RefCell::new(Filesystem::new(Some(
                std::rc::Rc::clone(p),
            ))))
        });

        rm.set_local_repository(Box::new(
            InstalledFilesystemRepository::new(
                JsonFile::new(
                    format!("{}/composer/installed.json", vendor_dir),
                    None,
                    Some(io.clone_box()),
                )
                .expect("installed.json path is always valid"),
                true,
                Some(RootPackageInterface::clone_box(root_package)),
                fs,
            )
            .expect("InstalledFilesystemRepository::new should not fail"),
        ));
    }

    fn create_global_composer(
        &self,
        io: &dyn IOInterface,
        config: &Config,
        disable_plugins: DisablePlugins,
        disable_scripts: bool,
        full_load: bool,
    ) -> Option<PartialComposer> {
        // make sure if disable plugins was 'local' it is now turned off
        let disable_plugins = if matches!(
            disable_plugins,
            DisablePlugins::Global | DisablePlugins::All
        ) {
            DisablePlugins::All
        } else {
            DisablePlugins::None
        };

        let composer = match self.create_composer(
            io,
            Some(LocalConfigInput::Path(format!(
                "{}/composer.json",
                config.get_str("home").ok()?
            ))),
            disable_plugins,
            Some(&config.get_str("home").ok()?),
            full_load,
            disable_scripts,
        ) {
            Ok(c) => Some(c.into_partial()),
            Err(e) => {
                io.write_error3(
                    &format!("Failed to initialize global composer: {}", e),
                    true,
                    crate::io::io_interface::DEBUG,
                );
                None
            }
        };

        composer
    }

    pub fn create_download_manager(
        &self,
        io: &dyn IOInterface,
        config: &std::rc::Rc<std::cell::RefCell<Config>>,
        http_downloader: &std::rc::Rc<std::cell::RefCell<HttpDownloader>>,
        process: &std::rc::Rc<std::cell::RefCell<ProcessExecutor>>,
        event_dispatcher: Option<&std::rc::Rc<std::cell::RefCell<EventDispatcher>>>,
    ) -> anyhow::Result<std::rc::Rc<std::cell::RefCell<DownloadManager>>> {
        // TODO(phase-b): cache is shared across all downloaders; PHP class semantics requires
        // either Rc<RefCell<Cache>> (with corresponding signature changes everywhere) or
        // making Cache cloneable. For now we don't construct a cache and pass None below.
        let _cache: Option<Cache> = None;
        if config
            .borrow_mut()
            .get("cache-files-ttl")
            .and_then(|v| v.as_int())
            .unwrap_or(0)
            > 0
        {
            let _ = Cache::new(
                io.clone_box(),
                &config.borrow_mut().get_str("cache-files-dir")?,
                Some("a-z0-9_./"),
                None,
                false,
            );
        }

        let fs = std::rc::Rc::new(std::cell::RefCell::new(Filesystem::new(Some(
            std::rc::Rc::clone(process),
        ))));

        let mut dm = DownloadManager::new(io.clone_box(), false, Some(std::rc::Rc::clone(&fs)));
        let preferred = config.borrow_mut().get("preferred-install");
        match preferred.as_string() {
            Some("dist") => {
                dm.set_prefer_dist(true);
            }
            Some("source") => {
                dm.set_prefer_source(true);
            }
            Some("auto") | _ => {
                // noop
            }
        }

        if let PhpMixed::Array(prefs) = preferred {
            dm.set_preferences(
                prefs
                    .into_iter()
                    .map(|(k, v)| {
                        (
                            k,
                            match *v {
                                PhpMixed::String(s) => s,
                                _ => String::new(),
                            },
                        )
                    })
                    .collect(),
            );
        }

        dm.set_downloader(
            "git",
            Box::new(GitDownloader::new(
                io.clone_box(),
                std::rc::Rc::clone(&config),
                Some(std::rc::Rc::clone(&process)),
                Some(std::rc::Rc::clone(&fs)),
            )),
        );
        dm.set_downloader(
            "svn",
            Box::new(SvnDownloader::new(
                io.clone_box(),
                std::rc::Rc::clone(&config),
                std::rc::Rc::clone(&process),
                std::rc::Rc::clone(&fs),
            )),
        );
        dm.set_downloader(
            "fossil",
            Box::new(FossilDownloader::new(
                io.clone_box(),
                std::rc::Rc::clone(&config),
                std::rc::Rc::clone(&process),
                std::rc::Rc::clone(&fs),
            )),
        );
        dm.set_downloader(
            "hg",
            Box::new(HgDownloader::new(
                io.clone_box(),
                std::rc::Rc::clone(&config),
                std::rc::Rc::clone(&process),
                std::rc::Rc::clone(&fs),
            )),
        );
        dm.set_downloader(
            "perforce",
            Box::new(PerforceDownloader::new(
                io.clone_box(),
                std::rc::Rc::clone(&config),
                std::rc::Rc::clone(&process),
                std::rc::Rc::clone(&fs),
            )),
        );
        dm.set_downloader(
            "zip",
            Box::new(ZipDownloader::new(
                io.clone_box(),
                std::rc::Rc::clone(&config),
                std::rc::Rc::clone(http_downloader),
                event_dispatcher.cloned(),
                None, // TODO(phase-b): shared Cache requires Rc<RefCell<Cache>>; see _cache
                std::rc::Rc::clone(&fs),
                std::rc::Rc::clone(&process),
            )),
        );
        dm.set_downloader(
            "rar",
            Box::new(RarDownloader::new(
                io.clone_box(),
                std::rc::Rc::clone(&config),
                std::rc::Rc::clone(http_downloader),
                event_dispatcher.cloned(),
                None, // TODO(phase-b): shared Cache requires Rc<RefCell<Cache>>; see _cache
                std::rc::Rc::clone(&fs),
                std::rc::Rc::clone(&process),
            )),
        );
        dm.set_downloader(
            "tar",
            Box::new(TarDownloader::new(
                io.clone_box(),
                std::rc::Rc::clone(&config),
                std::rc::Rc::clone(http_downloader),
                event_dispatcher.cloned(),
                None, // TODO(phase-b): shared Cache requires Rc<RefCell<Cache>>; see _cache
                std::rc::Rc::clone(&fs),
                std::rc::Rc::clone(&process),
            )),
        );
        dm.set_downloader(
            "gzip",
            Box::new(GzipDownloader::new(
                io.clone_box(),
                std::rc::Rc::clone(&config),
                std::rc::Rc::clone(http_downloader),
                event_dispatcher.cloned(),
                None, // TODO(phase-b): shared Cache requires Rc<RefCell<Cache>>; see _cache
                std::rc::Rc::clone(&fs),
                std::rc::Rc::clone(&process),
            )),
        );
        dm.set_downloader(
            "xz",
            Box::new(XzDownloader::new(
                io.clone_box(),
                std::rc::Rc::clone(&config),
                std::rc::Rc::clone(http_downloader),
                event_dispatcher.cloned(),
                None, // TODO(phase-b): shared Cache requires Rc<RefCell<Cache>>; see _cache
                std::rc::Rc::clone(&fs),
                std::rc::Rc::clone(&process),
            )),
        );
        dm.set_downloader(
            "phar",
            Box::new(PharDownloader::new(
                io.clone_box(),
                std::rc::Rc::clone(&config),
                std::rc::Rc::clone(http_downloader),
                event_dispatcher.cloned(),
                None, // TODO(phase-b): shared Cache requires Rc<RefCell<Cache>>; see _cache
                std::rc::Rc::clone(&fs),
                std::rc::Rc::clone(&process),
            )),
        );
        dm.set_downloader(
            "file",
            Box::new(FileDownloader::new(
                io.clone_box(),
                std::rc::Rc::clone(&config),
                std::rc::Rc::clone(http_downloader),
                event_dispatcher.cloned(),
                None, // TODO(phase-b): shared Cache requires Rc<RefCell<Cache>>; see _cache
                Some(std::rc::Rc::clone(&fs)),
                Some(std::rc::Rc::clone(&process)),
            )),
        );
        dm.set_downloader(
            "path",
            Box::new(PathDownloader::new(
                io.clone_box(),
                std::rc::Rc::clone(&config),
                std::rc::Rc::clone(http_downloader),
                event_dispatcher.cloned(),
                None, // TODO(phase-b): shared Cache requires Rc<RefCell<Cache>>; see _cache
                std::rc::Rc::clone(&fs),
                std::rc::Rc::clone(&process),
            )),
        );

        Ok(std::rc::Rc::new(std::cell::RefCell::new(dm)))
    }

    pub fn create_archive_manager(
        &self,
        _config: &Config,
        dm: &std::rc::Rc<std::cell::RefCell<DownloadManager>>,
        r#loop: &std::rc::Rc<std::cell::RefCell<Loop>>,
    ) -> anyhow::Result<ArchiveManager> {
        let mut am = ArchiveManager::new(dm.clone(), r#loop.clone());
        if class_exists("ZipArchive") {
            am.add_archiver(Box::new(ZipArchiver::new()));
        }
        if class_exists("Phar") {
            am.add_archiver(Box::new(PharArchiver::new()));
        }

        Ok(am)
    }

    fn create_plugin_manager(
        &self,
        io: &dyn IOInterface,
        composer: &Composer,
        global_composer: Option<&PartialComposer>,
        disable_plugins: DisablePlugins,
    ) -> PluginManager {
        // TODO(phase-b): PluginManager::new takes ownership of Composer/PartialComposer; PHP
        // class semantics requires Rc<RefCell<>> for shared access. Stubbed for now.
        let _ = (io, composer, global_composer, disable_plugins);
        todo!("PluginManager::new requires shared Composer/PartialComposer")
    }

    pub fn create_installation_manager(
        &self,
        r#loop: std::rc::Rc<std::cell::RefCell<Loop>>,
        io: Box<dyn IOInterface>,
        event_dispatcher: Option<std::rc::Rc<std::cell::RefCell<EventDispatcher>>>,
    ) -> InstallationManager {
        InstallationManager::new(r#loop, io, event_dispatcher)
    }

    fn create_default_installers(
        &self,
        im: &InstallationManager,
        composer: &PartialComposerOrComposer,
        io: &dyn IOInterface,
        process: Option<&std::rc::Rc<std::cell::RefCell<ProcessExecutor>>>,
    ) {
        let fs = std::rc::Rc::new(std::cell::RefCell::new(Filesystem::new(
            process.map(std::rc::Rc::clone),
        )));
        let bin_dir = trim(
            &composer
                .get_config()
                .borrow_mut()
                .get_str("bin-dir")
                .unwrap_or_default(),
            Some("/"),
        );
        let bin_compat = composer
            .get_config()
            .borrow_mut()
            .get_str("bin-compat")
            .unwrap_or_default();
        let vendor_dir = trim(
            &composer
                .get_config()
                .borrow_mut()
                .get_str("vendor-dir")
                .unwrap_or_default(),
            Some("/"),
        );
        // TODO(phase-b): BinaryInstaller is a PHP class so it can't be cloned. Sharing requires
        // Rc<RefCell<BinaryInstaller>>; for now construct one per installer.
        let _binary_installer = BinaryInstaller::new(
            io.clone_box(),
            bin_dir.clone(),
            bin_compat.clone(),
            Some(std::rc::Rc::clone(&fs)),
            Some(vendor_dir.clone()),
        );

        // TODO(phase-b): InstallationManager not clone-able; need shared Rc<RefCell<>>
        let _ = im;
    }

    fn purge_packages(
        &self,
        repo: &dyn InstalledRepositoryInterface,
        im: &mut InstallationManager,
    ) -> anyhow::Result<()> {
        for package in repo.get_packages() {
            if !im.is_package_installed(repo, package.as_ref())? {
                // TODO(phase-b): mutable access on repo trait object
                let _ = package;
            }
        }
        Ok(())
    }

    fn load_root_package(
        &self,
        rm: RepositoryManager,
        config: std::rc::Rc<std::cell::RefCell<Config>>,
        parser: VersionParser,
        guesser: VersionGuesser,
        io: Box<dyn IOInterface>,
    ) -> RootPackageLoader {
        RootPackageLoader::new(rm, config, Some(parser), Some(guesser), Some(io))
    }

    pub fn create(
        io: &dyn IOInterface,
        config: Option<LocalConfigInput>,
        disable_plugins: DisablePlugins,
        disable_scripts: bool,
    ) -> anyhow::Result<Composer> {
        let factory = Self;

        // 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
        let default_composer_file = Self::get_composer_file()?;
        let config_is_default = matches!(
            config.as_ref(),
            Some(LocalConfigInput::Path(p)) if *p == default_composer_file
        );
        let disable_plugins = if config.is_some()
            && !config_is_default
            && matches!(disable_plugins, DisablePlugins::None)
        {
            DisablePlugins::Local
        } else {
            disable_plugins
        };

        match factory.create_composer(io, config, disable_plugins, None, true, disable_scripts)? {
            PartialComposerOrComposer::Full(c) => Ok(c),
            PartialComposerOrComposer::Partial(_) => {
                // TODO(phase-b): unreachable when fullLoad=true; downcasting needs design.
                Err(anyhow::anyhow!(RuntimeException {
                    message: "Composer expected with fullLoad=true".to_string(),
                    code: 0,
                }))
            }
        }
    }

    /// If you are calling this in a plugin, you probably should instead use `$composer->getLoop()->getHttpDownloader()`
    pub fn create_http_downloader(
        io: &dyn IOInterface,
        config: &std::rc::Rc<std::cell::RefCell<Config>>,
        options: IndexMap<String, PhpMixed>,
    ) -> anyhow::Result<HttpDownloader> {
        // TODO(plugin): static `$warned` flag — port as a OnceCell or atomic in Phase B.
        static mut WARNED: bool = false;
        let mut disable_tls = 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
        let argv = shirabe_php_shim::server_argv();
        if !argv.is_empty()
            && argv.contains(&"disable-tls".to_string())
            && (argv.contains(&"conf".to_string()) || argv.contains(&"config".to_string()))
        {
            unsafe { WARNED = true };
            disable_tls = !extension_loaded("openssl");
        } else if config
            .borrow_mut()
            .get("disable-tls")
            .and_then(|v| v.as_bool())
            .unwrap_or(false)
        {
            if !unsafe { WARNED } {
                io.write_error3(
                    "<warning>You are running Composer with SSL/TLS protection disabled.</warning>",
                    true,
                    crate::io::io_interface::NORMAL,
                );
            }
            unsafe { WARNED = true };
            disable_tls = true;
        } else if !extension_loaded("openssl") {
            return Err(anyhow::anyhow!(NoSslException(RuntimeException {
                message:
                    "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."
                        .to_string(),
                code: 0,
            })));
        }
        let mut http_downloader_options: IndexMap<String, PhpMixed> = IndexMap::new();
        if !disable_tls {
            if "" != config.borrow_mut().get_str("cafile").unwrap_or_default() {
                let mut ssl_map: IndexMap<String, PhpMixed> = IndexMap::new();
                ssl_map.insert(
                    "cafile".to_string(),
                    PhpMixed::String(config.borrow_mut().get_str("cafile").unwrap_or_default()),
                );
                http_downloader_options.insert(
                    "ssl".to_string(),
                    PhpMixed::Array(ssl_map.into_iter().map(|(k, v)| (k, Box::new(v))).collect()),
                );
            }
            if "" != config.borrow_mut().get_str("capath").unwrap_or_default() {
                let existing_ssl = http_downloader_options
                    .get("ssl")
                    .and_then(|v| v.as_array())
                    .cloned()
                    .unwrap_or_default();
                let mut ssl_map: IndexMap<String, Box<PhpMixed>> = existing_ssl;
                ssl_map.insert(
                    "capath".to_string(),
                    Box::new(PhpMixed::String(
                        config.borrow_mut().get_str("capath").unwrap_or_default(),
                    )),
                );
                http_downloader_options.insert("ssl".to_string(), PhpMixed::Array(ssl_map));
            }
            http_downloader_options =
                array_replace_recursive(http_downloader_options, options.clone());
        }
        let http_downloader_result: anyhow::Result<HttpDownloader> = Ok(HttpDownloader::new(
            io.clone_box(),
            std::rc::Rc::clone(config),
            http_downloader_options,
            disable_tls,
        ));
        let http_downloader = match http_downloader_result {
            Ok(h) => h,
            Err(e) => {
                if let Some(te) = e.downcast_ref::<TransportException>() {
                    if strpos(&te.get_message(), "cafile").is_some() {
                        io.write3(
                            "<error>Unable to locate a valid CA certificate file. You must set a valid 'cafile' option.</error>",
                            true,
                            crate::io::io_interface::NORMAL,
                        );
                        io.write3(
                            "<error>A valid CA certificate file is required for SSL/TLS protection.</error>",
                            true,
                            crate::io::io_interface::NORMAL,
                        );
                        io.write3(
                            "<error>You can disable this error, at your own risk, by setting the 'disable-tls' option to true.</error>",
                            true,
                            crate::io::io_interface::NORMAL,
                        );
                    }
                }
                return Err(e);
            }
        };

        Ok(http_downloader)
    }

    fn load_composer_auth_env(
        config: &mut Config,
        io: Option<&dyn IOInterface>,
    ) -> anyhow::Result<()> {
        let composer_auth_env = Platform::get_env("COMPOSER_AUTH");
        let composer_auth_env_str = match composer_auth_env {
            Some(s) if !s.is_empty() => s,
            _ => return Ok(()),
        };

        let auth_data = json_decode(&composer_auth_env_str, false)?;
        if matches!(auth_data, PhpMixed::Null) {
            return Err(anyhow::anyhow!(UnexpectedValueException {
                message:
                    "COMPOSER_AUTH environment variable is malformed, should be a valid JSON object"
                        .to_string(),
                code: 0,
            }));
        }

        if let Some(io_ref) = io {
            io_ref.write_error3(
                "Loading auth config from COMPOSER_AUTH",
                true,
                crate::io::io_interface::DEBUG,
            );
        }
        Self::validate_json_schema(
            io,
            ValidateJsonInput::Data(auth_data.clone()),
            JsonFile::AUTH_SCHEMA,
            Some("COMPOSER_AUTH"),
        )?;
        let auth_data_assoc = json_decode(&composer_auth_env_str, true)?;
        if !matches!(auth_data_assoc, PhpMixed::Null) {
            let mut wrapped: IndexMap<String, PhpMixed> = IndexMap::new();
            wrapped.insert("config".to_string(), auth_data_assoc);
            config.merge(&wrapped, "COMPOSER_AUTH");
        }
        Ok(())
    }

    fn use_xdg() -> bool {
        // PHP: array_keys($_SERVER) — iterate env-style server vars
        for (key, _) in std::env::vars() {
            if strpos(&key, "XDG_") == Some(0) {
                return true;
            }
        }

        Silencer::call(|| Ok::<bool, anyhow::Error>(is_dir("/etc/xdg"))).unwrap_or(false)
    }

    fn get_user_dir() -> anyhow::Result<String> {
        let home = Platform::get_env("HOME").unwrap_or_default();
        if home.is_empty() {
            return Err(anyhow::anyhow!(RuntimeException {
                message:
                    "The HOME or COMPOSER_HOME environment variable must be set for composer to run correctly"
                        .to_string(),
                code: 0,
            }));
        }

        Ok(trim(&strtr(&home, "\\", "/"), Some("/")))
    }

    fn validate_json_schema(
        io: Option<&dyn IOInterface>,
        file_or_data: ValidateJsonInput,
        schema: i64,
        source: Option<&str>,
    ) -> anyhow::Result<()> {
        if Platform::is_input_completion_process() {
            return Ok(());
        }

        let result = match file_or_data {
            ValidateJsonInput::File(mut file) => file.validate_schema(schema, None),
            ValidateJsonInput::Data(data) => {
                let source = source.ok_or_else(|| {
                    anyhow::anyhow!(InvalidArgumentException {
                        message:
                            "$source is required to be provided if $fileOrData is arbitrary data"
                                .to_string(),
                        code: 0,
                    })
                })?;
                JsonFile::validate_json_schema(source, &data, schema, None)
            }
        };

        if let Err(e) = result {
            if let Some(jve) = e.downcast_ref::<JsonValidationException>() {
                let msg = format!(
                    "{}, this may result in errors and should be resolved:{} - {}",
                    jve.get_message(),
                    PHP_EOL,
                    implode(&format!("{} - ", PHP_EOL), jve.get_errors())
                );
                if let Some(io_ref) = io {
                    io_ref.write_error3(
                        &format!("<warning>{}</>", msg),
                        true,
                        crate::io::io_interface::NORMAL,
                    );
                } else {
                    return Err(anyhow::anyhow!(UnexpectedValueException {
                        message: msg,
                        code: 0
                    }));
                }
            } else {
                return Err(e);
            }
        }
        Ok(())
    }
}

enum ValidateJsonInput {
    File(JsonFile),
    Data(PhpMixed),
}

/// `Factory::createComposer` returns either a `Composer` (`$fullLoad=true`) or a `PartialComposer`.
pub enum PartialComposerOrComposer {
    Full(Composer),
    Partial(PartialComposer),
}

impl PartialComposerOrComposer {
    fn set_config(&mut self, config: std::rc::Rc<std::cell::RefCell<Config>>) {
        match self {
            Self::Full(c) => c.set_config(config),
            Self::Partial(p) => p.set_config(config),
        }
    }
    fn set_global(&mut self) {
        match self {
            Self::Full(c) => c.set_global(),
            Self::Partial(p) => p.set_global(),
        }
    }
    fn set_loop(&mut self, r#loop: std::rc::Rc<std::cell::RefCell<Loop>>) {
        match self {
            Self::Full(c) => c.set_loop(r#loop),
            Self::Partial(p) => p.set_loop(r#loop),
        }
    }
    fn set_event_dispatcher(
        &mut self,
        dispatcher: std::rc::Rc<std::cell::RefCell<EventDispatcher>>,
    ) {
        match self {
            Self::Full(c) => c.set_event_dispatcher(dispatcher),
            Self::Partial(p) => p.set_event_dispatcher(dispatcher),
        }
    }
    fn set_repository_manager(&mut self, rm: RepositoryManager) {
        match self {
            Self::Full(c) => c.set_repository_manager(rm),
            Self::Partial(p) => p.set_repository_manager(rm),
        }
    }
    fn set_installation_manager(&mut self, im: InstallationManager) {
        match self {
            Self::Full(c) => c.set_installation_manager(im),
            Self::Partial(p) => p.set_installation_manager(im),
        }
    }
    fn set_package(&mut self, package: Box<dyn RootPackageInterface>) {
        match self {
            Self::Full(c) => c.set_package(package),
            Self::Partial(p) => p.set_package(package),
        }
    }
    fn get_package(&self) -> &dyn RootPackageInterface {
        match self {
            Self::Full(c) => c.get_package(),
            Self::Partial(p) => p.get_package(),
        }
    }
    fn get_config(&self) -> &std::rc::Rc<std::cell::RefCell<Config>> {
        match self {
            Self::Full(c) => c.get_config(),
            Self::Partial(p) => p.get_config(),
        }
    }
    fn get_event_dispatcher(&self) -> &std::rc::Rc<std::cell::RefCell<EventDispatcher>> {
        match self {
            Self::Full(c) => c.get_event_dispatcher(),
            Self::Partial(p) => p.get_event_dispatcher(),
        }
    }
    fn as_partial(&self) -> PartialComposer {
        // TODO(phase-b): PHP class semantics requires sharing PartialComposer by reference;
        // currently returning a fresh default since PartialComposer is not Clone.
        PartialComposer::default()
    }
    fn into_partial(self) -> PartialComposer {
        match self {
            Self::Full(_) => PartialComposer::default(),
            Self::Partial(p) => p,
        }
    }
}