Test Failed
Push — master ( 61ab03...c8a89b )
by Dispositif
02:49
created

GoogleLivresTemplate::googleUrlEncode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of dispositif/wikibot application
4
 * 2019 : Philippe M. <[email protected]>
5
 * For the full copyright and MIT license information, please view the LICENSE file.
6
 */
7
8
declare(strict_types=1);
9
10
namespace App\Domain\Models\Wiki;
11
12
use App\Domain\Publisher\GoogleBooksUtil;
13
use DomainException;
14
use Exception;
15
16
/**
17
 * https://fr.wikipedia.org/wiki/Mod%C3%A8le:Google_Livres
18
 * Le premier paramètre (ou id) est obligatoire.
19
 * Le deuxième (ou titre) est requis si on ne veut pas fabriquer le lien brut (inclusion {{ouvrage}} 'Lire en ligne')
20
 * Class GoogleLivresTemplate.
21
 */
22
class GoogleLivresTemplate extends AbstractWikiTemplate
23
{
24
    const WIKITEMPLATE_NAME = 'Google Livres';
25
26
    const REQUIRED_PARAMETERS = ['id'];
27
28
    const MINIMUM_PARAMETERS = ['id' => ''];
29
30
    const PARAM_ALIAS
31
        = [
32
            '1' => 'id',
33
            '2' => 'titre',
34
            'surligné' => 'surligne',
35
            'BuchID' => 'id',
36
        ];
37
38
    /**
39
     * @var array
40
     */
41
    protected $parametersByOrder
42
        = ['id', 'titre', 'couv', 'page', 'romain', 'page autre', 'surligne'];
43
44
    /**
45
     * Create {Google Book} from URL.
46
     * See also https://fr.wikipedia.org/wiki/Utilisateur:Jack_ma/GB
47
     * https://stackoverflow.com/questions/11584551/need-information-on-query-parameters-for-google-books-e-g-difference-between-d.
48
     *
49
     * @param string $url
50
     *
51
     * @return GoogleLivresTemplate|null
52
     * @throws Exception
53
     */
54
    public static function createFromURL(string $url): ?self
55
    {
56
        if (!GoogleBooksUtil::isGoogleBookURL($url)) {
57
            throw new DomainException('not a Google Book URL');
58
        }
59
        $gooDat = GoogleBooksUtil::parseGoogleBookQuery($url);
60
61
        if (empty($gooDat['id'])) {
62
            throw new DomainException("no GoogleBook 'id' in URL");
63
        }
64
        if (!preg_match('#[0-9A-Za-z_\-]{12}#', $gooDat['id'])) {
65
            throw new DomainException("GoogleBook 'id' malformed [0-9A-Za-z_\-]{12}");
66
        }
67
68
        $data = self::mapGooData($gooDat);
69
70
        $template = new self();
71
        $template->hydrate($data);
72
73
        return $template;
74
    }
75
76
    /**
77
     * Mapping Google URL data to {Google Livres} data.
78
     *
79
     * @param array $gooData
80
     *
81
     * @return array
82
     */
83
    private static function mapGooData(array $gooData): array
84
    {
85
        $data = [];
86
        $data['id'] = $gooData['id'];
87
88
        // show cover ?
89
        if (isset($gooData['printsec']) && 'frontcover' === $gooData['printsec']) {
90
            $data['couv'] = '1';
91
        }
92
93
        // page number
94
        if (!empty($gooData['pg'])) {
95
            $data['page autre'] = $gooData['pg'];
96
97
            //  pg=PAx => "page=x"
98
            if (preg_match('/^PA([0-9]+)$/', $gooData['pg'], $matches) > 0) {
99
                $data['page'] = $matches[1];
100
                unset($data['page autre']);
101
            }
102
            //  pg=PRx => "page=x|romain=1"
103
            if (preg_match('/^PR([0-9]+)$/', $gooData['pg'], $matches) > 0) {
104
                $data['page'] = $matches[1];
105
                $data['romain'] = '1';
106
                unset($data['page autre']);
107
            }
108
        }
109
        // q : keywords search / dq : quoted phrase search
110
        // affichage Google : dq ignoré si q existe
111
        if (!empty($gooData['dq']) || !empty($gooData['q'])) {
112
            $data['surligne'] = $gooData['q'] ?? $gooData['dq']; // q prévaut
113
            $data['surligne'] = GoogleBooksUtil::googleUrlEncode($data['surligne']);
114
        }
115
116
        return $data;
117
    }
118
119
    /**
120
     * Check if Google URL or wiki {Google Books} template.
121
     *
122
     * @param string $text
123
     *
124
     * @return bool
125
     */
126
    public static function isGoogleBookValue(string $text): bool
127
    {
128
        if (true === GoogleBooksUtil::isGoogleBookURL($text)) {
129
            return true;
130
        }
131
        if (preg_match('#^{{[ \n]*Google (Livres|Books)[^}]+}}$#i', $text) > 0) {
132
            return true;
133
        }
134
135
        return false;
136
    }
137
138
    /**
139
     * Serialize the wiki-template.
140
     * Improvement : force param order : id/titre/...
141
     *
142
     * @param bool|null $cleanOrder
143
     *
144
     * @return string
145
     */
146
    public function serialize(?bool $cleanOrder = true): string
147
    {
148
        $text = parent::serialize();
149
150
        // Documentation suggère non affichage de ces 2 paramètres
151
        return str_replace(['id=', 'titre='], '', $text);
152
    }
153
}
154