Passed
Branch master (fd6b1a)
by Dispositif
03:51 queued 01:13
created

SameAuthorValidator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
nc 1
nop 2
1
<?php
2
/*
3
 * This file is part of dispositif/wikibot application (@github)
4
 * 2019-2023 © Philippe M./Irønie  <[email protected]>
5
 * For the full copyright and MIT license information, view the license file.
6
 */
7
8
declare(strict_types=1);
9
10
namespace App\Domain\Transformers\Validator;
11
12
use App\Domain\Models\Wiki\OuvrageTemplate;
13
use App\Domain\Transformers\OuvrageMixTrait;
14
use App\Domain\Utils\WikiTextUtil;
15
use App\Domain\ValidatorInterface;
16
17
class SameAuthorValidator implements ValidatorInterface
18
{
19
    use OuvrageMixTrait;
20
21
    /**
22
     * @var OuvrageTemplate
23
     */
24
    protected $origin;
25
    /**
26
     * @var OuvrageTemplate
27
     */
28
    protected $book;
29
30
    public function __construct(OuvrageTemplate $origin, OuvrageTemplate $book)
31
    {
32
        $this->origin = $origin;
33
        $this->book = $book;
34
    }
35
36
    public function validate(): bool
37
    {
38
        if ($this->authorsFromBook($this->origin) === $this->authorsFromBook($this->book)) {
39
            return true;
40
        }
41
42
        // if there is only 2 char of difference (i.e. typo error)
43
        if (levenshtein($this->authorsFromBook($this->origin), $this->authorsFromBook($this->book)) <= 2) {
44
            return true;
45
        }
46
47
        // Si auteur manquant sur wikipedia
48
        return empty($this->authorsFromBook($this->origin));
49
    }
50
51
    /**
52
     * concatenation of parameters (firstname, lastname...) from every authors.
53
     * Todo: return array for comparing mixed authors (bob henri == henri bob).
54
     */
55
    protected function authorsFromBook(OuvrageTemplate $ouv): string
56
    {
57
        $text = '';
58
        $paramAuteurs = [
59
            'auteurs',
60
            'auteur1',
61
            'prénom1',
62
            'nom1',
63
            'auteur2',
64
            'prénom2',
65
            'nom2',
66
            'auteur3',
67
            'prénom3',
68
            'nom3',
69
            'auteur4',
70
            'prénom4',
71
            'nom4',
72
        ];
73
        foreach ($paramAuteurs as $param) {
74
            if (!empty($ouv->getParam($param))) {
75
                $value = str_replace(['.', ','], '', $ouv->getParam($param));
76
                // retire wikilien sur auteur
77
                if (!empty($value)) {
78
                    $text .= WikiTextUtil::unWikify($value);
79
                }
80
            }
81
        }
82
83
        return $this->stripAll($text);
84
    }
85
}