Passed
Push — master ( 034d7b...196627 )
by Sander
02:07
created

LinkPackages::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 8
rs 10
cc 1
nc 1
nop 3
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the composer-link plugin.
7
 *
8
 * Copyright (c) 2021-2022 Sander Visser <[email protected]>.
9
 *
10
 * For the full copyright and license information, please view the LICENSE.md
11
 * file that was distributed with this source code.
12
 *
13
 * @link https://github.com/SanderSander/composer-link
14
 */
15
16
namespace ComposerLink\Actions;
17
18
use Composer\Repository\RepositoryManager;
19
use ComposerLink\LinkedPackage;
20
use ComposerLink\LinkManager;
21
use ComposerLink\Repository\Repository;
22
23
/**
24
 * Links all packages that aren't linked, and updates the state of the linked package with the orignal package.
25
 */
26
class LinkPackages
27
{
28
    protected RepositoryManager $repositoryManager;
29
30
    protected Repository $repository;
31
32
    protected LinkManager $linkManager;
33
34
    public function __construct(
35
        LinkManager $linkManager,
36
        Repository $repository,
37
        RepositoryManager $repositoryManager
38
    ) {
39
        $this->linkManager = $linkManager;
40
        $this->repository = $repository;
41
        $this->repositoryManager = $repositoryManager;
42
    }
43
44
    public function execute(): void
45
    {
46
        foreach ($this->repository->all() as $package) {
47
            if (!$this->linkManager->isLinked($package)) {
48
                $this->linkAndUpdate($package);
49
            }
50
        }
51
52
        $this->repository->persist();
53
    }
54
55
    /**
56
     * It can happen, when a package is updated that we need to update the state of the linked package.
57
     * We do this here, before we link the package back in.
58
     */
59
    private function linkAndUpdate(LinkedPackage $package): void
60
    {
61
        $oldOriginalPackage = $package->getOriginalPackage();
62
        if (!is_null($oldOriginalPackage)) {
63
            $newOriginalPackage = $this->repositoryManager
64
                ->getLocalRepository()
65
                ->findPackage($oldOriginalPackage->getName(), '*');
66
            $package->setOriginalPackage($newOriginalPackage);
67
            $this->repository->store($package);
68
        }
69
70
        $this->linkManager->linkPackage($package);
71
    }
72
}
73