Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
80.00% covered (success)
80.00%
12 / 15
66.67% covered (warning)
66.67%
2 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
ShlinkProxy
80.00% covered (success)
80.00%
12 / 15
66.67% covered (warning)
66.67%
2 / 3
4.13
0.00% covered (danger)
0.00%
0 / 1
 _getProxyUrl
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 _getProxyPayload
76.92% covered (warning)
76.92%
10 / 13
0.00% covered (danger)
0.00%
0 / 1
2.05
 _extractShortUrl
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php declare(strict_types=1);
2/**
3 * PrivateBin
4 *
5 * a zero-knowledge paste bin
6 *
7 * @link      https://github.com/PrivateBin/PrivateBin
8 * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
9 * @license   https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
10 */
11
12namespace PrivateBin\Proxy;
13
14use PrivateBin\Configuration;
15use PrivateBin\Exception\JsonException;
16use PrivateBin\Json;
17
18/**
19 * ShlinkProxy
20 *
21 * Forwards a URL for shortening to shlink and stores the result.
22 */
23class ShlinkProxy extends AbstractProxy
24{
25    /**
26     * Overrides the abstract parent function to get the proxy URL.
27     *
28     * @param Configuration $conf
29     * @return string
30     */
31    protected function _getProxyUrl(Configuration $conf): string
32    {
33        return $conf->getKey('apiurl', 'shlink');
34    }
35
36    /**
37     * Overrides the abstract parent function to get contents from Shlink API.
38     *
39     * @access protected
40     * @param Configuration $conf
41     * @param string $link
42     * @return array
43     */
44    protected function _getProxyPayload(Configuration $conf, string $link): array
45    {
46        $shlink_api_key = $conf->getKey('apikey', 'shlink');
47
48        $body = array(
49            'longUrl' => $link,
50        );
51
52        try {
53            return array(
54                'method'  => 'POST',
55                'header'  => "Content-Type: application/json\r\n" .
56                            'X-Api-Key: ' . $shlink_api_key . "\r\n",
57                'content' => Json::encode($body),
58            );
59        } catch (JsonException $e) {
60            error_log('[' . get_class($this) . '] Error encoding body: ' . $e->getMessage());
61            return array();
62        }
63    }
64
65    /**
66     * Extracts the short URL from the shlink API response.
67     *
68     * @access protected
69     * @param array $data
70     * @return ?string
71     */
72    protected function _extractShortUrl(array $data): ?string
73    {
74        return $data['shortUrl'] ?? null;
75    }
76}