Completed
Pull Request — newinternal (#542)
by Simon
11:55 queued 02:00
created

JsonApiPageBase::runApiPage()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 13
c 2
b 0
f 0
dl 0
loc 23
rs 9.8333
cc 4
nc 4
nop 0
1
<?php
2
/******************************************************************************
3
 * Wikipedia Account Creation Assistance tool                                 *
4
 *                                                                            *
5
 * All code in this file is released into the public domain by the ACC        *
6
 * Development Team. Please see team.json for a list of contributors.         *
7
 ******************************************************************************/
8
9
namespace Waca\Tasks;
10
11
use Waca\API\ApiException;
12
use Waca\API\IJsonApiAction;
13
use Waca\WebRequest;
14
15
abstract class JsonApiPageBase extends ApiPageBase implements IJsonApiAction
16
{
17
    /**
18
     * Main function for this page, when no specific actions are called.
19
     *
20
     * @return void
21
     * @throws ApiException
22
     */
23
    final protected function main()
24
    {
25
        if (headers_sent()) {
26
            throw new ApiException('Headers have already been sent - this indicates a bug in the application!');
27
        }
28
29
        // javascript access control
30
        $httpOrigin = WebRequest::origin();
31
32
        if ($httpOrigin !== null) {
33
            $CORSallowed = $this->getSiteConfiguration()->getCrossOriginResourceSharingHosts();
34
35
            if (in_array($httpOrigin, $CORSallowed)) {
36
                header("Access-Control-Allow-Origin: " . $httpOrigin);
37
            }
38
        }
39
40
        $responseData = $this->runApiPage();
41
42
        ob_end_clean();
43
        print($responseData);
44
        ob_start();
45
    }
46
47
    /**
48
     * Method that runs API action
49
     *
50
     * @return object|array The modified API document
51
     */
52
    public abstract function executeApiAction();
53
54
    /**
55
     * @return string
56
     */
57
    final public function runApiPage()
58
    {
59
60
        try {
61
            $apiDocument = $this->executeApiAction();
62
        }
63
        catch (ApiException $ex) {
64
            $apiDocument = [
65
                'error' => $ex->getMessage(),
66
            ];
67
        }
68
69
        $data = json_encode($apiDocument, JSON_UNESCAPED_UNICODE);
70
71
        $targetVar = WebRequest::getString('targetVariable');
72
        if ($targetVar !== null && preg_match('/^[a-z]+$/', $targetVar)) {
73
            $data = $targetVar . ' = ' . $data . ';';
74
            header("Content-Type: text/javascript");
75
        } else {
76
            header("Content-Type: application/json");
77
        }
78
79
        return $data;
80
    }
81
}
82