Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
3 / 3
CRAP
100.00% covered (success)
100.00%
1 / 1
LexemeFormsMerger
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
3 / 3
6
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 merge
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
4
 mergeForms
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3namespace Wikibase\Lexeme\Domain\Merge;
4
5use Wikibase\DataModel\Services\Statement\GuidGenerator;
6use Wikibase\Lexeme\DataAccess\ChangeOp\ChangeOpFormAdd;
7use Wikibase\Lexeme\DataAccess\ChangeOp\ChangeOpFormClone;
8use Wikibase\Lexeme\Domain\Merge\Validator\FormMergeability;
9use Wikibase\Lexeme\Domain\Model\Form;
10use Wikibase\Lexeme\Domain\Model\Lexeme;
11use Wikibase\Repo\ChangeOp\ChangeOps;
12use Wikibase\Repo\Merge\StatementsMerger;
13
14/**
15 * @license GPL-2.0-or-later
16 */
17class LexemeFormsMerger {
18
19    /**
20     * @var StatementsMerger
21     */
22    private $statementsMerger;
23
24    /**
25     * @var GuidGenerator
26     */
27    private $guidGenerator;
28
29    public function __construct(
30        StatementsMerger $statementsMerger,
31        GuidGenerator $guidGenerator
32    ) {
33        $this->statementsMerger = $statementsMerger;
34        $this->guidGenerator = $guidGenerator;
35    }
36
37    /**
38     * This receives Lexeme, not Form as it needs awareness of the Lexeme (id)
39     *
40     * @param Lexeme $source
41     * @param Lexeme $target Will be modified by reference
42     */
43    public function merge( Lexeme $source, Lexeme $target ) {
44        $formMergeability = new FormMergeability();
45
46        $changeOps = new ChangeOps();
47
48        foreach ( $source->getForms()->toArray() as $sourceForm ) {
49            foreach ( $target->getForms()->toArray() as $targetForm ) {
50                if ( $formMergeability->validate( $sourceForm, $targetForm ) ) {
51                    $this->mergeForms( $sourceForm, $targetForm );
52                    continue 2; // source form will only be merged into first matching target form
53                }
54            }
55
56            $changeOps->add(
57                new ChangeOpFormAdd(
58                    new ChangeOpFormClone( $sourceForm, $this->guidGenerator )
59                )
60            );
61        }
62
63        $changeOps->apply( $target );
64    }
65
66    private function mergeForms( Form $source, Form $target ) {
67        $target->getRepresentations()->addAll( $source->getRepresentations() );
68        $this->statementsMerger->merge( $source, $target );
69    }
70
71}