Passed
Push — developer ( 5caef9...3bfca3 )
by Mariusz
17:23
created

WooCommerce::testConnection()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 13
rs 9.9666
c 0
b 0
f 0
cc 3
nc 3
nop 0
1
<?php
2
/**
3
 * Main file to integration with WooCommerce.
4
 *
5
 * The file is part of the paid functionality. Using the file is allowed only after purchasing a subscription.
6
 * File modification allowed only with the consent of the system producer.
7
 *
8
 * @package Integration
9
 *
10
 * @copyright YetiForce S.A.
11
 * @license   YetiForce Public License 5.0 (licenses/LicenseEN.txt or yetiforce.com)
12
 * @author    Mariusz Krzaczkowski <[email protected]>
13
 */
14
15
namespace App\Integrations;
16
17
use App\Exceptions\AppException;
18
19
/**
20
 * Main class to integration with WooCommerce.
21
 */
22
class WooCommerce
23
{
24
	/** @var string Servers table name */
25
	public const TABLE_NAME = 'i_#__woocommerce_servers';
26
	/** @var string Basic table name */
27
	public const LOG_TABLE_NAME = 'l_#__woocommerce';
28
	/** @var string Config table name */
29
	public const CONFIG_TABLE_NAME = 'i_#__woocommerce_config';
30
	/** @var string Map class table name */
31
	public const MAP_TABLE_NAME = 'i_#__woocommerce_map_class';
32
33
	/** @var callable|null Bath iteration callback */
34
	public $bathCallback;
35
	/** @var \App\Integrations\WooCommerce\Config Config. */
36
	public $config;
37
	/** @var \App\Integrations\WooCommerce\Connector\Base Connector with WooCommerce. */
38
	public $connector;
39
	/** @var \App\Integrations\WooCommerce\Synchronizer\Base[] Synchronizers instance */
40
	public $synchronizer = [];
41
42
	/**
43
	 * Constructor. Connect with WooCommerce and authorize.
44
	 *
45
	 * @param int           $serverId
46
	 * @param callable|null $bathCallback
47
	 */
48
	public function __construct(int $serverId, ?callable $bathCallback = null)
49
	{
50
		$this->bathCallback = $bathCallback;
51
		$this->config = WooCommerce\Config::getInstance($serverId);
52
	}
53
54
	/**
55
	 * Get connector.
56
	 *
57
	 * @return \App\Integrations\WooCommerce\Connector\Base
58
	 */
59
	public function getConnector(): WooCommerce\Connector\Base
60
	{
61
		if (null === $this->connector) {
62
			$className = '\\App\\Integrations\\WooCommerce\\Connector\\' . $this->config->get('connector') ?? 'HttpAuth';
63
			if (!class_exists($className)) {
64
				throw new AppException('ERR_CLASS_NOT_FOUND');
65
			}
66
			$this->connector = new $className($this->config);
67
			if (!$this->connector instanceof WooCommerce\Connector\Base) {
68
				throw new AppException('ERR_CLASS_MUST_BE||\App\Integrations\WooCommerce\Connector\Base');
69
			}
70
		}
71
		return $this->connector;
72
	}
73
74
	/**
75
	 * Get synchronizer object instance.
76
	 *
77
	 * @param string $name
78
	 *
79
	 * @return \App\Integrations\WooCommerce\Synchronizer\Base
80
	 */
81
	public function getSync(string $name): WooCommerce\Synchronizer\Base
82
	{
83
		if (isset($this->synchronizer[$name])) {
84
			return $this->synchronizer[$name];
85
		}
86
		$className = "App\\Integrations\\WooCommerce\\Synchronizer\\{$name}";
87
		return $this->synchronizer[$name] = new $className($this);
88
	}
89
90
	/**
91
	 * Get information about Comarch ERP XL.
92
	 *
93
	 * @return array
94
	 */
95
	public function getInfo(): array
96
	{
97
		$connector = $this->getConnector();
98
		$response = $connector->request('GET', 'system_status');
99
		$response = \App\Json::decode($response);
100
		$info = '';
101
		$info .= "[environment][home_url]: {$response['environment']['home_url']}\n";
102
		$info .= "[environment][site_url]: {$response['environment']['site_url']}\n";
103
		$info .= "[environment][version]: {$response['environment']['version']}\n";
104
		$info .= "[environment][wp_version]: {$response['environment']['wp_version']}\n";
105
		$info .= "[environment][language]: {$response['environment']['language']}\n";
106
		$info .= "[environment][server_info]: {$response['environment']['server_info']}\n";
107
		$info .= "[environment][php_version]: {$response['environment']['php_version']}\n";
108
		$info .= "[environment][mysql_version_string]: {$response['environment']['mysql_version_string']}\n";
109
		$info .= "[environment][default_timezone]: {$response['environment']['default_timezone']}\n";
110
		$info .= "[database][wc_database_version]: {$response['database']['wc_database_version']}\n";
111
		$info .= "[settings][currency]: {$response['settings']['currency']}\n";
112
		$info .= "[settings][currency_symbol]: {$response['settings']['currency_symbol']}\n\n";
113
114
		$count = [];
115
		foreach ($response['post_type_counts'] as $value) {
116
			$count[$value['type']] = $value['count'];
117
		}
118
		return [
119
			'info' => trim($info),
120
			'count' => $count
121
		];
122
	}
123
124
	/**
125
	 * Test connection.
126
	 *
127
	 * @return string
128
	 */
129
	public function testConnection(): string
130
	{
131
		$status = '';
132
		try {
133
			$response = $this->getConnector()->request('GET', 'system_status');
134
			if (!empty($response)) {
135
				throw new AppException('Empty body');
136
			}
137
		} catch (\Throwable $th) {
138
			self::log('Test connection error', null, $th);
139
			$status = $th->getMessage();
140
		}
141
		return $status;
142
	}
143
144
	/**
145
	 * Add log to YetiForce system.
146
	 *
147
	 * @param string      $category
148
	 * @param array       $params
149
	 * @param ?\Throwable $ex
150
	 * @param bool        $error
151
	 *
152
	 * @return void
153
	 */
154
	public static function log(string $category, ?array $params, ?\Throwable $ex = null, bool $error = false): void
155
	{
156
		$message = $ex ? $ex->getMessage() : $category;
157
		$params = print_r($params, true);
158
		if ($ex && ($raw = \App\RequestHttp::getRawException($ex))) {
159
			$params .= PHP_EOL . $raw;
160
		}
161
		\App\DB::getInstance('log')->createCommand()
162
			->insert(self::LOG_TABLE_NAME, [
163
				'time' => date('Y-m-d H:i:s'),
164
				'error' => $ex ? 1 : ((int) $error),
165
				'message' => \App\TextUtils::textTruncate($message, 255),
166
				'params' => $params ? \App\TextUtils::textTruncate($params, 65535) : null,
167
				'trace' => $ex ? \App\TextUtils::textTruncate(
168
					rtrim(str_replace(ROOT_DIRECTORY . \DIRECTORY_SEPARATOR, '', $ex->__toString()), PHP_EOL), 65535
169
				) : null,
170
			])->execute();
171
	}
172
}
173