Completed
Push — master ( cb9cb0...a2a2e1 )
by
unknown
43:00 queued 13:11
created

HttpClient::_sendRequest()   C

Complexity

Conditions 7
Paths 25

Size

Total Lines 51
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 7.6892

Importance

Changes 3
Bugs 0 Features 2
Metric Value
dl 0
loc 51
ccs 22
cts 29
cp 0.7586
rs 6.9743
c 3
b 0
f 2
cc 7
eloc 32
nc 25
nop 1
crap 7.6892

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace net\authorize\util;
3
4
use net\authorize\util\LogFactory;
5
use net\authorize\util\Log;
6
7
/**
8
 * A class to send a request to the XML API.
9
 *
10
 * @package    AuthorizeNet
11
 * @subpackage net\authorize\util
12
 */
13
class HttpClient
14
{
15
    private $_Url = "";
16
17
    public $VERIFY_PEER = true; // attempt trust validation of SSL certificates when establishing secure connections.
18
    private $logger = NULL;
19
    /**
20
     * Constructor.
21
     *
22
     */
23
    public function __construct()
24 8
    {
25
        $this->logger = LogFactory::getLog(get_class($this));
26 8
    }
27 8
28 8
    /**
29 8
     * Set a log file.
30
     *
31
     * @param string $endPoint end point to hit from  \net\authorize\api\constants\ANetEnvironment
32
     */
33
    public function setPostUrl( $endPoint = \net\authorize\api\constants\ANetEnvironment::CUSTOM)
34
    {
35
        $this->_Url = sprintf( "%s/xml/v1/request.api", $endPoint);
36 8
    }
37
38 8
    /**
39 8
     * @return string
40
     */
41
    public function _getPostUrl()
42
    {
43
        //return (self::URL);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
44 8
        return ($this->_Url);
45
    }
46
47 8
    /**
48
     * Set a log file.
49
     *
50
     * @param string $filepath Path to log file.
51
     */
52
    public function setLogFile($filepath)
53
    {
54
        $this->logger->setLogFile($filepath);
55
    }
56
57
    /**
58
     * Posts the request to AuthorizeNet endpoint using Curl & returns response.
59
     *
60
     * @param string $xmlRequest
61
     * @return string $xmlResponse The response.
62
     */
63
    public function _sendRequest($xmlRequest)
64
    {
65
        $xmlResponse = "";
66 8
67
        $post_url = $this->_getPostUrl();
68 8
        $curl_request = curl_init($post_url);
69
        curl_setopt($curl_request, CURLOPT_POSTFIELDS, $xmlRequest);
70 8
        curl_setopt($curl_request, CURLOPT_HEADER, 0);
71 8
        curl_setopt($curl_request, CURLOPT_TIMEOUT, 45);
72 8
        curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, 1);
73 8
        curl_setopt($curl_request, CURLOPT_SSL_VERIFYHOST, 2);
74 8
75 8
        $this->logger->info(sprintf(" Url: %s", $post_url));
76 8
        // Do not log requests that could contain CC info.
77
        $this->logger->info(sprintf("Request to AnetApi: \n%s", $xmlRequest));
78 8
79
        if ($this->VERIFY_PEER) {
80 8
            curl_setopt($curl_request, CURLOPT_CAINFO, dirname(dirname(__FILE__)) . '/../../ssl/cert.pem');
81
        } else {
82 8
            $this->logger->error("Invalid SSL option for the request");
83 8
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by net\authorize\util\HttpClient::_sendRequest of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
84
        }
85
86
        if (preg_match('/xml/',$post_url)) {
87
            curl_setopt($curl_request, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
88
//            file_put_contents($this->_log_file, "\nSending 'XML' Request type", FILE_APPEND);
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
89 8
            $this->logger->info("Sending 'XML' Request type");
90 8
        }
91
92 8
        try
93
        {
94
            $this->logger->info("Sending http request via Curl");
95
            $xmlResponse = curl_exec($curl_request);
96
            $this->logger->info("Response from AnetApi: $xmlResponse");
97 8
98 8
        } catch (\Exception $ex)
99 8
        {
100
            $errorMessage = sprintf("\n%s:Error making http request via curl: Code:'%s', Message:'%s', Trace:'%s', File:'%s':'%s'",
101
                $this->now(), $ex->getCode(), $ex->getMessage(), $ex->getTraceAsString(), $ex->getFile(), $ex->getLine() );
102
            $this->logger->error($errorMessage);
103
        }
104
        if ($this->logger && $this->logger->getLogFile()) {
105
            if ($curl_error = curl_error($curl_request)) {
106
                $this->logger->error("CURL ERROR: $curl_error");
107 8
            }
108 8
109
        }
110
        curl_close($curl_request);
111
112
        return $xmlResponse;
113 8
    }
114
115 8
    private function now()
116
    {
117
        return date( DATE_RFC2822);
118
    }
119
}