Passed
Pull Request — master (#16)
by
unknown
03:49
created

LogV2   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 141
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 20
eloc 66
dl 0
loc 141
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 18 5
A createCsrfValidationException() 0 3 1
A validateForCsrf() 0 3 1
D execute() 0 47 11
A checkDbLogTable() 0 25 2
1
<?php
2
namespace DigitalOrigin\Pmt\Controller\Payment;
3
4
use Magento\Framework\App\Action\Action;
5
use Magento\Framework\App\ResourceConnection;
6
use Magento\Framework\DB\Ddl\Table;
7
use Magento\Framework\App\CsrfAwareActionInterface;
8
use Magento\Framework\App\RequestInterface;
9
use Magento\Framework\App\Request\InvalidRequestException;
10
11
class LogV2 extends Action implements CsrfAwareActionInterface
12
{
13
    /** Concurrency tablename */
14
    const LOGS_TABLE = 'pmt_logs';
15
16
    /** @var mixed $config */
17
    protected $config;
18
19
    /** @var ResourceConnection $dbObject */
20
    protected $dbObject;
21
22
    /**
23
     * Log constructor.
24
     *
25
     * @param \Magento\Framework\App\Action\Context $context
26
     * @param \DigitalOrigin\Pmt\Helper\Config      $pmtConfig
27
     * @param ResourceConnection                    $dbObject
28
     */
29
    public function __construct(
30
        \Magento\Framework\App\Action\Context $context,
31
        \DigitalOrigin\Pmt\Helper\Config $pmtConfig,
32
        ResourceConnection $dbObject
33
    ) {
34
        $this->config = $pmtConfig->getConfig();
35
        $this->dbObject = $dbObject;
36
37
        // CsrfAwareAction Magento2.3 compatibility
38
        if (interface_exists("\Magento\Framework\App\CsrfAwareActionInterface")) {
39
            $request = $this->getRequest();
40
            if ($request instanceof HttpRequest && $request->isPost() && empty($request->getParam('form_key'))) {
0 ignored issues
show
Bug introduced by
The type DigitalOrigin\Pmt\Controller\Payment\HttpRequest was not found. Did you mean HttpRequest? If so, make sure to prefix the type with \.
Loading history...
Bug introduced by
The method isPost() does not exist on Magento\Framework\App\RequestInterface. It seems like you code against a sub-type of Magento\Framework\App\RequestInterface such as Magento\Framework\Webapi\Request or Magento\Framework\App\Request\Http. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

40
            if ($request instanceof HttpRequest && $request->/** @scrutinizer ignore-call */ isPost() && empty($request->getParam('form_key'))) {
Loading history...
41
                $formKey = $this->_objectManager->get(\Magento\Framework\Data\Form\FormKey::class);
42
                $request->setParam('form_key', $formKey->getFormKey());
0 ignored issues
show
Bug introduced by
The method setParam() does not exist on Magento\Framework\App\RequestInterface. Did you maybe mean setParams()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

42
                $request->/** @scrutinizer ignore-call */ 
43
                          setParam('form_key', $formKey->getFormKey());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
43
            }
44
        }
45
46
        return parent::__construct($context);
0 ignored issues
show
Bug introduced by
Are you sure the usage of parent::__construct($context) targeting Magento\Framework\App\Action\Action::__construct() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
47
    }
48
49
    /**
50
     * Main function
51
     * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface|void
52
     */
53
    public function execute()
54
    {
55
        try {
56
            $response = array();
57
            $secretKey = $this->getRequest()->getParam('secret');
58
            $privateKey = isset($this->config['pmt_private_key']) ? $this->config['pmt_private_key'] : null;
59
60
            if ($secretKey!='' && $privateKey!='') {
61
                $this->checkDbLogTable();
62
                /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
63
                $dbConnection = $this->dbObject->getConnection();
64
                $tableName    = $this->dbObject->getTableName(self::LOGS_TABLE);
65
                $sql          = $dbConnection
66
                    ->select()
67
                    ->from($tableName, array('log', 'createdAt'));
0 ignored issues
show
Unused Code introduced by
The call to Magento\Framework\DB\Select::from() has too many arguments starting with $tableName. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

67
                    ->/** @scrutinizer ignore-call */ from($tableName, array('log', 'createdAt'));

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
68
69
                if ($dateFrom = $this->getRequest()->getParam('from')) {
70
                    $sql->where('createdAt > ?', $dateFrom);
71
                }
72
73
                if ($dateTo = $this->getRequest()->getParam('to')) {
74
                    $sql->where('createdAt < ?', $dateTo);
75
                }
76
77
                $limit = ($this->getRequest()->getParam('limit')) ? $this->getRequest()->getParam('limit') : 50;
78
                $sql->limit($limit);
79
                $sql->order('createdAt', 'desc');
0 ignored issues
show
Unused Code introduced by
The call to Magento\Framework\DB\Select::order() has too many arguments starting with 'desc'. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

79
                $sql->/** @scrutinizer ignore-call */ 
80
                      order('createdAt', 'desc');

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
80
81
                $results = $dbConnection->fetchAll($sql);
82
                if (isset($results) && $privateKey == $secretKey) {
83
                    foreach ($results as $key => $result) {
84
                        $response[$key]['timestamp'] = $result['createdAt'];
85
                        $response[$key]['log']       = json_decode($result['log']);
86
                    }
87
                } else {
88
                    $response['result'] = 'Error';
89
                }
90
91
                $response = json_encode($response);
92
                header("HTTP/1.1 200", true, 200);
93
                header('Content-Type: application/json', true);
94
                header('Content-Length: '.strlen($response));
95
                echo($response);
96
                exit();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
97
            }
98
        } catch (\Exception $e) {
99
            die($e->getMessage());
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
100
        }
101
    }
102
103
    /**
104
     * @return void|\Zend_Db_Statement_Interface
105
     * @throws \Zend_Db_Exception
106
     */
107
    private function checkDbLogTable()
108
    {
109
        /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
110
        $dbConnection = $this->dbObject->getConnection();
111
        $tableName = $this->dbObject->getTableName(self::LOGS_TABLE);
112
        if (!$dbConnection->isTableExists($tableName)) {
113
            $table = $dbConnection
114
                ->newTable($tableName)
115
                ->addColumn(
116
                    'id',
117
                    Table::TYPE_SMALLINT,
118
                    null,
119
                    array('nullable'=>false, 'auto_increment'=>true, 'primary'=>true)
120
                )
121
                ->addColumn('log', Table::TYPE_TEXT, null, array('nullable'=>false))
122
                ->addColumn(
123
                    'createdAt',
124
                    Table::TYPE_TIMESTAMP,
125
                    null,
126
                    array('nullable'=>false,
127
                          'default'=>Table::TIMESTAMP_INIT)
128
                );
129
            return $dbConnection->createTable($table);
130
        }
131
        return;
132
    }
133
134
    /**
135
     * @param RequestInterface $request
136
     *
137
     * @return InvalidRequestException|null
138
     */
139
    public function createCsrfValidationException(RequestInterface $request): ?InvalidRequestException
140
    {
141
        return null;
142
    }
143
144
    /**
145
     * @param RequestInterface $request
146
     *
147
     * @return bool|null
148
     */
149
    public function validateForCsrf(RequestInterface $request): ?bool
150
    {
151
        return true;
152
    }
153
}
154