aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/shirabe/src/package/locker.rs
blob: 9522e55e5e031442d0afd25c7bac097d91739679 (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
//! ref: composer/src/Composer/Package/Locker.php

use anyhow::Result;
use indexmap::IndexMap;

use shirabe_external_packages::composer::pcre::{CaptureKey, Preg};
use shirabe_external_packages::seld::json_lint::ParsingException;
use shirabe_php_shim::{
    DATE_RFC3339, LogicException, PhpMixed, RuntimeException, array_intersect, array_keys,
    array_map, array_merge, call_user_func, file_get_contents, filemtime, function_exists, hash,
    in_array, is_array, is_int, ksort, realpath, reset_first, sprintf, strcmp, strtolower, touch,
    trim, usort,
};

use crate::installer::InstallationManager;
use crate::io::IOInterface;
use crate::json::JsonFile;
use crate::package::AliasPackage;
use crate::package::BasePackage;
use crate::package::CompleteAliasPackage;
use crate::package::Link;
use crate::package::PackageInterface;
use crate::package::RootPackageInterface;
use crate::package::dumper::ArrayDumper;
use crate::package::loader::ArrayLoader;
use crate::package::loader::LoaderInterface;
use crate::package::version::VersionParser;
use crate::plugin::plugin_interface::{self, PluginInterface};
use crate::repository::FindPackageConstraint;
use crate::repository::InstalledRepository;
use crate::repository::LockArrayRepository;
use crate::repository::PlatformRepository;
use crate::repository::RootPackageRepository;
use crate::util::Git as GitUtil;
use crate::util::ProcessExecutor;

/// Reads/writes project lockfile (composer.lock).
#[derive(Debug)]
pub struct Locker {
    /// @var JsonFile
    lock_file: JsonFile,
    /// @var InstallationManager
    installation_manager: std::rc::Rc<std::cell::RefCell<InstallationManager>>,
    /// @var string
    hash: String,
    /// @var string
    content_hash: String,
    /// @var ArrayLoader
    loader: ArrayLoader,
    /// @var ArrayDumper
    dumper: ArrayDumper,
    /// @var ProcessExecutor
    process: std::rc::Rc<std::cell::RefCell<ProcessExecutor>>,
    /// @var mixed[]|null
    lock_data_cache: std::cell::RefCell<Option<IndexMap<String, PhpMixed>>>,
    /// @var bool
    virtual_file_written: bool,
}

impl Locker {
    /// Initializes packages locker.
    pub fn new(
        io: Box<dyn IOInterface>,
        lock_file: JsonFile,
        installation_manager: std::rc::Rc<std::cell::RefCell<InstallationManager>>,
        composer_file_contents: &str,
        process: std::rc::Rc<std::cell::RefCell<ProcessExecutor>>,
    ) -> Self {
        Self {
            lock_file,
            installation_manager,
            hash: hash("md5", composer_file_contents),
            content_hash: Self::get_content_hash(composer_file_contents).unwrap_or_default(),
            loader: ArrayLoader::new(None, true),
            dumper: ArrayDumper::new(),
            process,
            lock_data_cache: std::cell::RefCell::new(None),
            virtual_file_written: false,
        }
    }

    /// @internal
    pub fn get_json_file(&self) -> &JsonFile {
        &self.lock_file
    }

    /// Returns the md5 hash of the sorted content of the composer file.
    pub fn get_content_hash(composer_file_contents: &str) -> Result<String> {
        let content = JsonFile::parse_json(Some(composer_file_contents), Some("composer.json"))?;
        // TODO(phase-b): parse_json returns PhpMixed; downstream expects map-like access
        let content_map: IndexMap<String, PhpMixed> = match &content {
            PhpMixed::Array(m) => m.iter().map(|(k, v)| (k.clone(), (**v).clone())).collect(),
            _ => IndexMap::new(),
        };

        let relevant_keys: Vec<&str> = vec![
            "name",
            "version",
            "require",
            "require-dev",
            "conflict",
            "replace",
            "provide",
            "minimum-stability",
            "prefer-stable",
            "repositories",
            "extra",
        ];

        let mut relevant_content: IndexMap<String, PhpMixed> = IndexMap::new();

        let content_keys: Vec<String> = array_keys(&content_map);
        let relevant_keys_strings: Vec<String> =
            relevant_keys.iter().map(|s| s.to_string()).collect();
        let intersected = array_intersect(&relevant_keys_strings, &content_keys);
        for key in intersected {
            if let Some(value) = content_map.get(&key) {
                relevant_content.insert(key, value.clone());
            }
        }
        let platform_value = content_map.get("config").and_then(|v| match v {
            PhpMixed::Array(m) => m.get("platform").cloned(),
            _ => None,
        });
        if let Some(platform) = platform_value {
            let mut config_map: IndexMap<String, Box<PhpMixed>> = IndexMap::new();
            config_map.insert("platform".to_string(), platform);
            relevant_content.insert("config".to_string(), PhpMixed::Array(config_map));
        }

        ksort(&mut relevant_content);

        Ok(hash(
            "md5",
            &JsonFile::encode(
                &PhpMixed::Array(
                    relevant_content
                        .into_iter()
                        .map(|(k, v)| (k, Box::new(v)))
                        .collect(),
                ),
                0,
            ),
        ))
    }

    /// Checks whether locker has been locked (lockfile found).
    pub fn is_locked(&mut self) -> bool {
        if !self.virtual_file_written && !self.lock_file.exists() {
            return false;
        }

        let data_result = self.get_lock_data();
        if let Ok(data) = data_result {
            return data.contains_key("packages");
        }
        false
    }

    /// Checks whether the lock file is still up to date with the current hash
    pub fn is_fresh(&mut self) -> Result<bool> {
        let lock = self.lock_file.read()?;
        let lock_map: IndexMap<String, PhpMixed> = match lock {
            PhpMixed::Array(m) => m.into_iter().map(|(k, v)| (k, *v)).collect(),
            _ => IndexMap::new(),
        };

        let content_hash = lock_map.get("content-hash");
        if content_hash.is_some() && !shirabe_php_shim::empty(content_hash.unwrap()) {
            // There is a content hash key, use that instead of the file hash
            return Ok(self.content_hash == content_hash.unwrap().as_string().unwrap_or(""));
        }

        // BC support for old lock files without content-hash
        let lock_hash = lock_map.get("hash");
        if lock_hash.is_some() && !shirabe_php_shim::empty(lock_hash.unwrap()) {
            return Ok(self.hash == lock_hash.unwrap().as_string().unwrap_or(""));
        }

        // should not be reached unless the lock file is corrupted, so assume it's out of date
        Ok(false)
    }

    /// Searches and returns an array of locked packages, retrieved from registered repositories.
    pub fn get_locked_repository(&mut self, with_dev_reqs: bool) -> Result<LockArrayRepository> {
        let lock_data = self.get_lock_data()?;
        // TODO(phase-b): LockArrayRepository has no `new` constructor yet
        let mut packages: LockArrayRepository = todo!("LockArrayRepository::new(vec![])");

        let mut locked_packages = lock_data
            .get("packages")
            .cloned()
            .unwrap_or(PhpMixed::List(vec![]));
        if with_dev_reqs {
            if let Some(packages_dev) = lock_data.get("packages-dev").cloned() {
                locked_packages = array_merge(locked_packages, packages_dev);
            } else {
                return Err(RuntimeException {
                    message: "The lock file does not contain require-dev information, run install with the --no-dev option or delete it and run composer update to generate a new lock file.".to_string(),
                    code: 0,
                }
                .into());
            }
        }

        if shirabe_php_shim::empty(&locked_packages) {
            return Ok(packages);
        }

        // PHP: if (isset($lockedPackages[0]['name']))
        let has_name = if let PhpMixed::List(list) = &locked_packages {
            list.first()
                .map(|v| match v.as_ref() {
                    PhpMixed::Array(m) => m.contains_key("name"),
                    _ => false,
                })
                .unwrap_or(false)
        } else {
            false
        };
        if has_name {
            let mut package_by_name: IndexMap<String, Box<dyn BasePackage>> = IndexMap::new();
            if let PhpMixed::List(list) = locked_packages {
                for info in list {
                    if let PhpMixed::Array(m) = info.as_ref() {
                        let info_map: IndexMap<String, PhpMixed> =
                            m.iter().map(|(k, v)| (k.clone(), (**v).clone())).collect();
                        let package = self.loader.load(info_map, None)?;
                        // TODO(phase-b): PHP shares the package between repository and map (Rc<dyn BasePackage>)
                        let _name = package.get_name().to_string();
                        let _ = (&mut packages, &mut package_by_name, package);
                        todo!(
                            "packages.add_package(package); package_by_name.insert(name, package); + AliasPackage downcast"
                        );
                    }
                }
            }

            if let Some(aliases) = lock_data.get("aliases") {
                if let PhpMixed::List(alias_list) = aliases {
                    for alias in alias_list {
                        if let PhpMixed::Array(m) = alias.as_ref() {
                            let alias_pkg_name = m
                                .get("package")
                                .and_then(|v| v.as_string())
                                .unwrap_or("")
                                .to_string();
                            // TODO(phase-b): Box<dyn BasePackage> is not Clone; PHP semantics need Rc<dyn BasePackage>
                            if let Some(base_pkg) = package_by_name.get(&alias_pkg_name) {
                                let mut alias_pkg = CompleteAliasPackage::new(
                                    todo!("phase-b: downcast Box<BasePackage> to CompletePackage"),
                                    m.get("alias_normalized")
                                        .and_then(|v| v.as_string())
                                        .unwrap_or("")
                                        .to_string(),
                                    m.get("alias")
                                        .and_then(|v| v.as_string())
                                        .unwrap_or("")
                                        .to_string(),
                                );
                                // TODO(phase-b): set_root_package_alias missing on CompleteAliasPackage
                                let _ = base_pkg;
                                // TODO(phase-b): packages.add_package(Box::new(alias_pkg))
                                let _ = alias_pkg;
                            }
                        }
                    }
                }
            }

            return Ok(packages);
        }

        Err(RuntimeException {
            message:
                "Your composer.lock is invalid. Run \"composer update\" to generate a new one."
                    .to_string(),
            code: 0,
        }
        .into())
    }

    /// @return string[] Names of dependencies installed through require-dev
    pub fn get_dev_package_names(&mut self) -> Result<Vec<String>> {
        let mut names: Vec<String> = vec![];
        let lock_data = self.get_lock_data()?;
        if let Some(PhpMixed::List(list)) = lock_data.get("packages-dev") {
            for package in list {
                if let PhpMixed::Array(m) = package.as_ref() {
                    names.push(strtolower(
                        m.get("name").and_then(|v| v.as_string()).unwrap_or(""),
                    ));
                }
            }
        }

        Ok(names)
    }

    /// Returns the platform requirements stored in the lock file
    pub fn get_platform_requirements(&mut self, with_dev_reqs: bool) -> Result<Vec<Link>> {
        let lock_data = self.get_lock_data()?;
        let mut requirements: IndexMap<String, Link> = IndexMap::new();

        let platform_value = lock_data.get("platform");
        if platform_value.is_some() && !shirabe_php_shim::empty(platform_value.unwrap()) {
            requirements = self.loader.parse_links(
                "__root__",
                "1.0.0",
                Link::TYPE_REQUIRE,
                match platform_value.unwrap() {
                    PhpMixed::Array(m) => {
                        m.iter().map(|(k, v)| (k.clone(), (**v).clone())).collect()
                    }
                    _ => IndexMap::new(),
                },
            )?;
        }

        let platform_dev_value = lock_data.get("platform-dev");
        if with_dev_reqs
            && platform_dev_value.is_some()
            && !shirabe_php_shim::empty(platform_dev_value.unwrap())
        {
            let dev_requirements = self.loader.parse_links(
                "__root__",
                "1.0.0",
                Link::TYPE_REQUIRE,
                match platform_dev_value.unwrap() {
                    PhpMixed::Array(m) => {
                        m.iter().map(|(k, v)| (k.clone(), (**v).clone())).collect()
                    }
                    _ => IndexMap::new(),
                },
            )?;

            for (k, v) in dev_requirements {
                requirements.insert(k, v);
            }
        }

        Ok(requirements.into_iter().map(|(_, v)| v).collect())
    }

    /// @return key-of<BasePackage::STABILITIES>
    pub fn get_minimum_stability(&mut self) -> Result<String> {
        let lock_data = self.get_lock_data()?;

        Ok(lock_data
            .get("minimum-stability")
            .and_then(|v| v.as_string())
            .unwrap_or("stable")
            .to_string())
    }

    /// @return array<string, string>
    pub fn get_stability_flags(&mut self) -> Result<IndexMap<String, String>> {
        let lock_data = self.get_lock_data()?;

        Ok(lock_data
            .get("stability-flags")
            .and_then(|v| match v {
                PhpMixed::Array(m) => Some(
                    m.iter()
                        .map(|(k, v)| (k.clone(), v.as_string().unwrap_or("").to_string()))
                        .collect(),
                ),
                _ => None,
            })
            .unwrap_or_default())
    }

    pub fn get_prefer_stable(&mut self) -> Result<Option<bool>> {
        let lock_data = self.get_lock_data()?;

        // return null if not set to allow caller logic to choose the
        // right behavior since old lock files have no prefer-stable
        Ok(lock_data.get("prefer-stable").and_then(|v| v.as_bool()))
    }

    pub fn get_prefer_lowest(&mut self) -> Result<Option<bool>> {
        let lock_data = self.get_lock_data()?;

        Ok(lock_data.get("prefer-lowest").and_then(|v| v.as_bool()))
    }

    /// @return array<string, string>
    pub fn get_platform_overrides(&mut self) -> Result<IndexMap<String, String>> {
        let lock_data = self.get_lock_data()?;

        Ok(lock_data
            .get("platform-overrides")
            .and_then(|v| match v {
                PhpMixed::Array(m) => Some(
                    m.iter()
                        .map(|(k, v)| (k.clone(), v.as_string().unwrap_or("").to_string()))
                        .collect(),
                ),
                _ => None,
            })
            .unwrap_or_default())
    }

    /// @return string[][]
    pub fn get_aliases(&mut self) -> Result<Vec<IndexMap<String, String>>> {
        let lock_data = self.get_lock_data()?;

        Ok(lock_data
            .get("aliases")
            .and_then(|v| match v {
                PhpMixed::List(list) => Some(
                    list.iter()
                        .filter_map(|v| match v.as_ref() {
                            PhpMixed::Array(m) => Some(
                                m.iter()
                                    .map(|(k, v)| {
                                        (k.clone(), v.as_string().unwrap_or("").to_string())
                                    })
                                    .collect(),
                            ),
                            _ => None,
                        })
                        .collect(),
                ),
                _ => None,
            })
            .unwrap_or_default())
    }

    pub fn get_plugin_api(&mut self) -> Result<String> {
        let lock_data = self.get_lock_data()?;

        Ok(lock_data
            .get("plugin-api-version")
            .and_then(|v| v.as_string())
            .unwrap_or("1.1.0")
            .to_string())
    }

    /// @return array<string, mixed>
    pub fn get_lock_data(&mut self) -> Result<IndexMap<String, PhpMixed>> {
        if let Some(cache) = self.lock_data_cache.borrow().clone() {
            return Ok(cache);
        }

        if !self.lock_file.exists() {
            return Err(LogicException {
                message: "No lockfile found. Unable to read locked packages".to_string(),
                code: 0,
            }
            .into());
        }

        let data_php = self.lock_file.read()?;
        let data: IndexMap<String, PhpMixed> = match data_php {
            PhpMixed::Array(m) => m.into_iter().map(|(k, v)| (k, *v)).collect(),
            _ => IndexMap::new(),
        };
        *self.lock_data_cache.borrow_mut() = Some(data.clone());
        Ok(data)
    }

    /// Locks provided data into lockfile.
    pub fn set_lock_data(
        &mut self,
        packages: Vec<Box<dyn PackageInterface>>,
        dev_packages: Option<Vec<Box<dyn PackageInterface>>>,
        platform_reqs: IndexMap<String, String>,
        platform_dev_reqs: IndexMap<String, String>,
        aliases: Vec<IndexMap<String, PhpMixed>>,
        minimum_stability: &str,
        stability_flags: IndexMap<String, i64>,
        prefer_stable: bool,
        prefer_lowest: bool,
        platform_overrides: IndexMap<String, PhpMixed>,
        write: bool,
    ) -> Result<bool> {
        // keep old default branch names normalized to DEFAULT_BRANCH_ALIAS for BC as that is how Composer 1 outputs the lock file
        // when loading the lock file the version is anyway ignored in Composer 2, so it has no adverse effect
        let aliases: Vec<IndexMap<String, PhpMixed>> = array_map(
            |alias: &IndexMap<String, PhpMixed>| {
                let mut alias = alias.clone();
                let version = alias
                    .get("version")
                    .and_then(|v| v.as_string())
                    .unwrap_or("")
                    .to_string();
                if in_array(
                    PhpMixed::String(version),
                    &PhpMixed::List(vec![
                        Box::new(PhpMixed::String("dev-master".to_string())),
                        Box::new(PhpMixed::String("dev-trunk".to_string())),
                        Box::new(PhpMixed::String("dev-default".to_string())),
                    ]),
                    true,
                ) {
                    alias.insert(
                        "version".to_string(),
                        PhpMixed::String(VersionParser::DEFAULT_BRANCH_ALIAS.to_string()),
                    );
                }
                alias
            },
            &aliases,
        );

        let mut lock: IndexMap<String, PhpMixed> = IndexMap::new();
        lock.insert(
            "_readme".to_string(),
            PhpMixed::List(vec![
                Box::new(PhpMixed::String(
                    "This file locks the dependencies of your project to a known state".to_string(),
                )),
                Box::new(PhpMixed::String(
                    "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies".to_string(),
                )),
                Box::new(PhpMixed::String(
                    format!("This file is @{}ated automatically", "gener"),
                )),
            ]),
        );
        lock.insert(
            "content-hash".to_string(),
            PhpMixed::String(self.content_hash.clone()),
        );
        lock.insert("packages".to_string(), self.lock_packages(&packages)?);
        lock.insert("packages-dev".to_string(), PhpMixed::Null);
        lock.insert(
            "aliases".to_string(),
            PhpMixed::List(
                aliases
                    .iter()
                    .map(|m| {
                        Box::new(PhpMixed::Array(
                            m.iter()
                                .map(|(k, v)| (k.clone(), Box::new(v.clone())))
                                .collect(),
                        ))
                    })
                    .collect(),
            ),
        );
        lock.insert(
            "minimum-stability".to_string(),
            PhpMixed::String(minimum_stability.to_string()),
        );
        lock.insert(
            "stability-flags".to_string(),
            PhpMixed::Array(
                stability_flags
                    .iter()
                    .map(|(k, v)| (k.clone(), Box::new(PhpMixed::Int(*v))))
                    .collect(),
            ),
        );
        lock.insert("prefer-stable".to_string(), PhpMixed::Bool(prefer_stable));
        lock.insert("prefer-lowest".to_string(), PhpMixed::Bool(prefer_lowest));

        if let Some(dev_packages) = dev_packages {
            lock.insert(
                "packages-dev".to_string(),
                self.lock_packages(&dev_packages)?,
            );
        }

        lock.insert(
            "platform".to_string(),
            PhpMixed::Array(
                platform_reqs
                    .iter()
                    .map(|(k, v)| (k.clone(), Box::new(PhpMixed::String(v.clone()))))
                    .collect(),
            ),
        );
        lock.insert(
            "platform-dev".to_string(),
            PhpMixed::Array(
                platform_dev_reqs
                    .iter()
                    .map(|(k, v)| (k.clone(), Box::new(PhpMixed::String(v.clone()))))
                    .collect(),
            ),
        );
        if platform_overrides.len() > 0 {
            lock.insert(
                "platform-overrides".to_string(),
                PhpMixed::Array(
                    platform_overrides
                        .into_iter()
                        .map(|(k, v)| (k, Box::new(v)))
                        .collect(),
                ),
            );
        }
        lock.insert(
            "plugin-api-version".to_string(),
            PhpMixed::String(plugin_interface::PLUGIN_API_VERSION.to_string()),
        );

        let lock = self.fixup_json_data_type(lock);

        let is_locked = match self.is_locked_result() {
            Ok(b) => b,
            Err(e) => {
                // TODO(phase-b): catch only ParsingException
                if e.downcast_ref::<ParsingException>().is_some() {
                    false
                } else {
                    return Err(e);
                }
            }
        };
        let current_data = if is_locked {
            self.get_lock_data().ok()
        } else {
            None
        };
        // TODO(phase-b): PhpMixed lacks PartialEq; PHP compares lock array with current data
        let differs = current_data
            .as_ref()
            .map(|c| !std::ptr::eq(c as *const _, &lock as *const _))
            .unwrap_or(true);
        if !is_locked || differs {
            if write {
                self.lock_file.write(PhpMixed::Array(
                    lock.into_iter().map(|(k, v)| (k, Box::new(v))).collect(),
                ))?;
                *self.lock_data_cache.borrow_mut() = None;
                self.virtual_file_written = false;
            } else {
                self.virtual_file_written = true;
                let parsed = JsonFile::parse_json(
                    Some(&JsonFile::encode_with_indent(
                        &PhpMixed::Array(lock.into_iter().map(|(k, v)| (k, Box::new(v))).collect()),
                        shirabe_php_shim::JSON_UNESCAPED_SLASHES
                            | shirabe_php_shim::JSON_PRETTY_PRINT
                            | shirabe_php_shim::JSON_UNESCAPED_UNICODE,
                        JsonFile::INDENT_DEFAULT,
                    )),
                    None,
                )?;
                let parsed_map: IndexMap<String, PhpMixed> = match parsed {
                    PhpMixed::Array(m) => m.into_iter().map(|(k, v)| (k, *v)).collect(),
                    _ => IndexMap::new(),
                };
                *self.lock_data_cache.borrow_mut() = Some(parsed_map);
            }

            return Ok(true);
        }

        Ok(false)
    }

    fn is_locked_result(&mut self) -> Result<bool> {
        Ok(self.is_locked())
    }

    /// Updates the lock file's hash in-place from a given composer.json's JsonFile
    pub fn update_hash<F>(
        &mut self,
        composer_json: &JsonFile,
        data_processor: Option<F>,
    ) -> Result<()>
    where
        F: FnOnce(IndexMap<String, PhpMixed>) -> IndexMap<String, PhpMixed>,
    {
        let contents = file_get_contents(&composer_json.get_path());
        let contents = match contents {
            Some(s) => s,
            None => {
                return Err(RuntimeException {
                    message: format!(
                        "Unable to read {} contents to update the lock file hash.",
                        composer_json.get_path()
                    ),
                    code: 0,
                }
                .into());
            }
        };

        let lock_mtime = filemtime(&self.lock_file.get_path());
        let lock_data_php = self.lock_file.read()?;
        let mut lock_data: IndexMap<String, PhpMixed> = match lock_data_php {
            PhpMixed::Array(m) => m.into_iter().map(|(k, v)| (k, *v)).collect(),
            _ => IndexMap::new(),
        };
        lock_data.insert(
            "content-hash".to_string(),
            PhpMixed::String(Self::get_content_hash(&contents)?),
        );
        if let Some(processor) = data_processor {
            lock_data = processor(lock_data);
        }

        self.lock_file.write(PhpMixed::Array(
            self.fixup_json_data_type(lock_data)
                .into_iter()
                .map(|(k, v)| (k, Box::new(v)))
                .collect(),
        ))?;
        *self.lock_data_cache.borrow_mut() = None;
        self.virtual_file_written = false;
        if let Some(mtime) = lock_mtime {
            if is_int(&PhpMixed::Int(mtime)) {
                // TODO(phase-b): touch() in php-shim doesn't accept mtime; need touch2
                let _ = mtime;
                let _ = touch(&self.lock_file.get_path());
            }
        }
        Ok(())
    }

    /// Ensures correct data types and ordering for the JSON lock format
    fn fixup_json_data_type(
        &self,
        mut lock_data: IndexMap<String, PhpMixed>,
    ) -> IndexMap<String, PhpMixed> {
        for key in ["stability-flags", "platform", "platform-dev"].iter() {
            let should_replace = lock_data
                .get(*key)
                .map(|v| match v {
                    PhpMixed::Array(m) => m.is_empty(),
                    _ => false,
                })
                .unwrap_or(false);
            if should_replace {
                // PHP: $lockData[$key] = new \stdClass();
                // TODO(phase-b): represent empty stdClass distinctly from empty array
                lock_data.insert(key.to_string(), PhpMixed::Array(IndexMap::new()));
            }
        }

        if let Some(PhpMixed::Array(m)) = lock_data.get_mut("stability-flags") {
            let mut as_map: IndexMap<String, PhpMixed> =
                m.iter().map(|(k, v)| (k.clone(), (**v).clone())).collect();
            ksort(&mut as_map);
            *m = as_map.into_iter().map(|(k, v)| (k, Box::new(v))).collect();
        }

        lock_data
    }

    /// @param PackageInterface[] $packages
    fn lock_packages(&mut self, packages: &[Box<dyn PackageInterface>]) -> Result<PhpMixed> {
        let mut locked: Vec<IndexMap<String, PhpMixed>> = vec![];

        for package in packages {
            // TODO(phase-b): `$package instanceof AliasPackage` downcast
            let package_as_alias: Option<&AliasPackage> = None;
            if package_as_alias.is_some() {
                continue;
            }

            let name = package.get_pretty_name();
            let version = package.get_pretty_version();

            if name.is_empty() || version.is_empty() {
                return Err(LogicException {
                    message: sprintf(
                        "Package \"%s\" has no version or name and can not be locked",
                        &[PhpMixed::String(package.to_string())],
                    ),
                    code: 0,
                }
                .into());
            }

            let mut spec = self.dumper.dump(&**package);
            spec.shift_remove("version_normalized");

            // always move time to the end of the package definition
            let time = spec.get("time").cloned();
            spec.shift_remove("time");
            let time = if package.is_dev() && package.get_installation_source() == Some("source") {
                // use the exact commit time of the current reference if it's a dev package
                let pkg_time = self.get_package_time(&**package)?;
                pkg_time.map(PhpMixed::String).or(time)
            } else {
                time
            };
            if let Some(t) = time {
                spec.insert("time".to_string(), t);
            }

            spec.shift_remove("installation-source");

            locked.push(spec);
        }

        usort(&mut locked, |a, b| {
            let comparison = strcmp(
                a.get("name").and_then(|v| v.as_string()).unwrap_or(""),
                b.get("name").and_then(|v| v.as_string()).unwrap_or(""),
            );

            if 0 != comparison {
                return comparison;
            }

            // If it is the same package, compare the versions to make the order deterministic
            strcmp(
                a.get("version").and_then(|v| v.as_string()).unwrap_or(""),
                b.get("version").and_then(|v| v.as_string()).unwrap_or(""),
            )
        });

        Ok(PhpMixed::List(
            locked
                .into_iter()
                .map(|m| {
                    Box::new(PhpMixed::Array(
                        m.into_iter().map(|(k, v)| (k, Box::new(v))).collect(),
                    ))
                })
                .collect(),
        ))
    }

    /// Returns the packages's datetime for its source reference.
    fn get_package_time(&mut self, package: &dyn PackageInterface) -> Result<Option<String>> {
        if !function_exists("proc_open") {
            return Ok(None);
        }

        let path = self
            .installation_manager
            .borrow_mut()
            .get_install_path(package);
        if path.is_none() {
            return Ok(None);
        }
        let path = realpath(&path.unwrap());
        let source_type = package.get_source_type();
        let mut datetime: Option<chrono::DateTime<chrono::Utc>> = None;

        if path.is_some()
            && in_array(
                PhpMixed::String(source_type.unwrap_or("").to_string()),
                &PhpMixed::List(vec![
                    Box::new(PhpMixed::String("git".to_string())),
                    Box::new(PhpMixed::String("hg".to_string())),
                ]),
                false,
            )
        {
            let source_ref = package
                .get_source_reference()
                .or_else(|| package.get_dist_reference())
                .unwrap_or("")
                .to_string();
            match source_type.unwrap_or("") {
                "git" => {
                    GitUtil::clean_env(&self.process);

                    let no_show_signature_flags =
                        GitUtil::get_no_show_signature_flags(&self.process);
                    let mut args: Vec<String> = vec![
                        "-n1".to_string(),
                        "--format=%ct".to_string(),
                        source_ref.clone(),
                    ];
                    args.extend(no_show_signature_flags);
                    let command = GitUtil::build_rev_list_command(&self.process, args);
                    let mut output = PhpMixed::Null;
                    if 0 == self.process.borrow_mut().execute(
                        PhpMixed::List(
                            command
                                .into_iter()
                                .map(|s| Box::new(PhpMixed::String(s)))
                                .collect(),
                        ),
                        Some(&mut output),
                        path.as_deref(),
                    )? {
                        let output_str = trim(
                            &GitUtil::parse_rev_list_output(
                                output.as_string().unwrap_or(""),
                                &self.process,
                            ),
                            None,
                        );
                        if Preg::is_match(r"{^\s*\d+\s*$}", &output_str).unwrap_or(false) {
                            // TODO(phase-b): new \DateTime('@'.trim($output), new \DateTimeZone('UTC'))
                            let ts = trim(&output_str, None).parse::<i64>().unwrap_or(0);
                            datetime = chrono::DateTime::from_timestamp(ts, 0);
                        }
                    }
                }
                "hg" => {
                    let mut output = PhpMixed::Null;
                    if 0 == self.process.borrow_mut().execute(
                        PhpMixed::List(vec![
                            Box::new(PhpMixed::String("hg".to_string())),
                            Box::new(PhpMixed::String("log".to_string())),
                            Box::new(PhpMixed::String("--template".to_string())),
                            Box::new(PhpMixed::String("{date|hgdate}".to_string())),
                            Box::new(PhpMixed::String("-r".to_string())),
                            Box::new(PhpMixed::String(source_ref.clone())),
                        ]),
                        Some(&mut output),
                        path.as_deref(),
                    )? {
                        let mut m: IndexMap<CaptureKey, String> = IndexMap::new();
                        if Preg::is_match_strict_groups3(
                            r"{^\s*(\d+)\s*}",
                            output.as_string().unwrap_or(""),
                            Some(&mut m),
                        )
                        .unwrap_or(false)
                        {
                            let ts = m
                                .get(&CaptureKey::ByIndex(1))
                                .cloned()
                                .unwrap_or_default()
                                .parse::<i64>()
                                .unwrap_or(0);
                            datetime = chrono::DateTime::from_timestamp(ts, 0);
                        }
                    }
                }
                _ => {}
            }
        }

        Ok(datetime.map(|d| d.format(DATE_RFC3339).to_string()))
    }

    /// @return array<string>
    pub fn get_missing_requirement_info(
        &mut self,
        package: &dyn RootPackageInterface,
        include_dev: bool,
    ) -> Result<Vec<String>> {
        let mut missing_requirement_info: Vec<String> = vec![];
        let mut missing_requirements = false;
        let mut sets: Vec<SetEntry> = vec![SetEntry {
            repo: Box::new(self.get_locked_repository(false)?),
            method: "getRequires".to_string(),
            description: "Required".to_string(),
        }];
        if include_dev == true {
            sets.push(SetEntry {
                repo: Box::new(self.get_locked_repository(true)?),
                method: "getDevRequires".to_string(),
                description: "Required (in require-dev)".to_string(),
            });
        }
        // TODO(phase-b): clone $package to a RootPackageRepository
        let root_repo = RootPackageRepository::new(todo!("phase-b: clone root package"));

        for set in &sets {
            let installed_repo = InstalledRepository::new(vec![/* set.repo, root_repo */]);

            // PHP: call_user_func([$package, $set['method']])
            // TODO(phase-b): dynamic method dispatch by name
            let links: Vec<Link> = vec![];
            for link in links {
                if PlatformRepository::is_platform_package(&link.get_target()) {
                    continue;
                }
                if link.get_pretty_constraint().ok() == Some("self.version") {
                    continue;
                }
                if installed_repo
                    .find_packages_with_replacers_and_providers(
                        &link.get_target(),
                        Some(FindPackageConstraint::Constraint(
                            link.get_constraint().clone(),
                        )),
                    )
                    .is_empty()
                {
                    let results = installed_repo
                        .find_packages_with_replacers_and_providers(&link.get_target(), None);

                    if !results.is_empty() {
                        // TODO(phase-b): reset_first requires Clone on dyn BasePackage; PHP returns shared reference
                        let provider: &Box<dyn BasePackage> =
                            todo!("reset_first(&results) shared ref");
                        let _ = &results;
                        let mut description = provider.get_pretty_version().to_string();
                        if provider.get_name() != link.get_target() {
                            'outer: for (method, text) in [
                                ("getReplaces", "replaced as %s by %s"),
                                ("getProvides", "provided as %s by %s"),
                            ]
                            .iter()
                            {
                                // TODO(phase-b): dynamic method dispatch
                                let provider_links: Vec<Link> = vec![];
                                let _ = method;
                                for provider_link in provider_links {
                                    if provider_link.get_target() == link.get_target() {
                                        description = sprintf(
                                            text,
                                            &[
                                                PhpMixed::String(
                                                    provider_link
                                                        .get_pretty_constraint()
                                                        .unwrap_or_default()
                                                        .to_string(),
                                                ),
                                                PhpMixed::String(format!(
                                                    "{} {}",
                                                    provider.get_pretty_name(),
                                                    provider.get_pretty_version()
                                                )),
                                            ],
                                        );
                                        break 'outer;
                                    }
                                }
                            }
                        }
                        missing_requirement_info.push(format!(
                            "- {} package \"{}\" is in the lock file as \"{}\" but that does not satisfy your constraint \"{}\".",
                            set.description,
                            link.get_target(),
                            description,
                            link.get_pretty_constraint().unwrap_or_default()
                        ));
                    } else {
                        missing_requirement_info.push(format!(
                            "- {} package \"{}\" is not present in the lock file.",
                            set.description,
                            link.get_target()
                        ));
                    }
                    missing_requirements = true;
                }
            }
            let _ = root_repo;
            let _ = installed_repo;
        }

        if missing_requirements {
            missing_requirement_info.push("This usually happens when composer files are incorrectly merged or the composer.json file is manually edited.".to_string());
            missing_requirement_info.push("Read more about correctly resolving merge conflicts https://getcomposer.org/doc/articles/resolving-merge-conflicts.md".to_string());
            missing_requirement_info.push("and prefer using the \"require\" command over editing the composer.json file directly https://getcomposer.org/doc/03-cli.md#require-r".to_string());
        }

        Ok(missing_requirement_info)
    }
}

struct SetEntry {
    repo: Box<LockArrayRepository>,
    method: String,
    description: String,
}

// Suppress unused-import warnings for items kept for parity with the PHP source.
#[allow(dead_code)]
fn _use_parity() {
    let _ = is_array;
    let _: PhpMixed = call_user_func("", &[]);
}