Completed
Push — master ( 066784...351105 )
by Joao Gilberto
02:29
created

ServiceHandler::setOutput()   B

Complexity

Conditions 5
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
rs 8.8571
cc 5
eloc 4
nc 2
nop 1
1
<?php
2
3
namespace ByJG\RestServer;
4
5
use ByJG\AnyDataset\Model\ObjectHandler;
6
use ByJG\Util\XmlUtil;
7
8
class ServiceHandler implements HandlerInterface
9
{
10
11
    protected $output = Output::JSON;
12
13
    public function getOutput()
14
    {
15
        return $this->output;
16
    }
17
18
    public function setOutput($output)
19
    {
20
        // Check if output is set
21
        if ($output != Output::JSON && $output != Output::XML && $output != Output::CSV && $output != Output::RDF) {
22
            throw new \Exception('Invalid output format. Valid are XML, JSON or CSV');
23
        }
24
25
        $this->output = $output;
26
    }
27
28
    public function setHeader()
29
    {
30
        switch ($this->getOutput()) {
31
            case Output::JSON:
32
                header('Content-Type: application/json');
33
                break;
34
35
            case Output::RDF:
36
                header('Content-Type: application/rdf+xml');
37
                break;
38
39
            case Output::XML:
40
                header('Content-Type: text/xml');
41
                break;
42
43
            default:
44
                header('Content-Type: text/plain');
45
                break;
46
        }
47
    }
48
49
    /**
50
     * CORS - Better do that in your http server, but you can enable calling this
51
     */
52
    public function setHeaderCors()
0 ignored issues
show
Coding Style introduced by João Gilberto Magalhães
setHeaderCors uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
53
    {
54
        header('Access-Control-Allow-Origin: *');
55
        header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
56
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
57
        $method = $_SERVER['REQUEST_METHOD'];
58
        if ($method == "OPTIONS") {
59
            return false;
60
        }
61
        return true;
62
    }
63
64
    public function execute(ServiceAbstract $instance)
65
    {
66
        $root = null;
67
        $annotationPrefix = 'object';
68
        if ($this->getOutput() == Output::RDF) {
69
            $xmlDoc = XmlUtil::CreateXmlDocument();
70
            $root = XmlUtil::CreateChild($xmlDoc, "rdf:RDF", "", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
71
            XmlUtil::AddNamespaceToDocument($root, "rdfs", "http://www.w3.org/2000/01/rdf-schema#");
0 ignored issues
show
Documentation introduced by Joao Gilberto Magalhaes
$root is of type object<DOMElement>, but the function expects a object<ByJG\Util\type>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
72
            $annotationPrefix = 'rdf';
73
        }
74
75
        $dom = $instance->getResponse()->getResponseBag()->process($root, $annotationPrefix);
76
77
        switch ($this->getOutput()) {
78
            case Output::JSON:
79
                return ObjectHandler::xml2json($dom);
0 ignored issues
show
Bug introduced by João Gilberto Magalhães
It seems like $dom defined by $instance->getResponse()...oot, $annotationPrefix) on line 75 can be null; however, ByJG\AnyDataset\Model\ObjectHandler::xml2json() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
80
81
            case Output::XML:
82
            case Output::RDF:
83
                return $dom->saveXML();
84
85
            case Output::CSV:
86
                $array = XmlUtil::xml2Array($dom);
87
88
                $return = "";
89
                foreach ((array) $array as $line) {
90
                    foreach ((array) $line as $field) {
91
                        $return .= "\"" . str_replace('"', '\\"', (is_array($field) ? json_encode($field) : $field)) . "\";";
92
                    }
93
                    $return .= "\n";
94
                }
95
                return $return;
96
        }
97
    }
98
}
99