-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDatafordelerCVR.php
More file actions
202 lines (176 loc) · 6.25 KB
/
Copy pathDatafordelerCVR.php
File metadata and controls
202 lines (176 loc) · 6.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
<?php
namespace Drupal\os2web_datalookup\Plugin\os2web\DataLookup;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Render\Markup;
use Drupal\os2web_datalookup\LookupResult\CompanyLookupResult;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Psr\Http\Message\ResponseInterface;
/**
* Defines a plugin for DatafordelerCVR.
*
* @DataLookup(
* id = "datafordeler_cvr",
* label = @Translation("Datafordeler CVR"),
* group = "cvr_lookup"
* )
*/
class DatafordelerCVR extends DataLookupBase implements DataLookupCompanyInterface {
/**
* Http client.
*
* @var \GuzzleHttp\Client
*/
protected Client $httpClient;
/**
* {@inheritdoc}
*/
public function defaultConfiguration(): array {
return [
'webserviceurl_live' => 'https://graphql.datafordeler.dk/flexibleCurrent/v1',
'api_key' => '',
] + parent::defaultConfiguration();
}
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state): array {
$form['webserviceurl_live'] = [
'#type' => 'textfield',
'#title' => $this->t('Webservice URL (LIVE)'),
'#description' => $this->t('Live URL against which to make the request, e.g. https://graphql.datafordeler.dk/flexibleCurrent/v1'),
'#default_value' => $this->configuration['webserviceurl_live'],
];
$form['api_key'] = [
'#type' => 'textfield',
'#title' => $this->t('API Key'),
'#default_value' => $this->configuration['api_key'],
];
$form['test_cvr'] = [
'#type' => 'textfield',
'#title' => $this->t('Test CVR nr.'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state): void {
$keys = array_keys($this->defaultConfiguration());
$configuration = $this->getConfiguration();
foreach ($keys as $key) {
$configuration[$key] = $form_state->getValue($key);
}
$this->setConfiguration($configuration);
if (!empty($form_state->getValue('test_cvr'))) {
$lookupResult = $this->lookup($form_state->getValue('test_cvr'));
$response = (array) $lookupResult;
\Drupal::messenger()->addMessage(
Markup::create('<pre>' . print_r($response, 1) . '</pre>'),
$lookupResult->isSuccessful() ? MessengerInterface::TYPE_STATUS : MessengerInterface::TYPE_WARNING
);
}
}
/**
* {@inheritdoc}
*/
public function lookup(string $param): CompanyLookupResult {
try {
if (!preg_match('/^\d{8}$/', $param)) {
throw new \InvalidArgumentException('CVR must be exactly 8 digits.');
}
$msg = sprintf('Hent virksomhed med CVRNummer: %s', $param);
$this->auditLogger->info('DataLookup', $msg);
$response = $this->executeQuery($param);
$result = json_decode((string) $response->getBody());
}
catch (GuzzleException | \InvalidArgumentException $e) {
$msg = sprintf('Hent virksomhed med CVRNummer (%s): %s', $param, $e->getMessage());
$this->auditLogger->error('DataLookup', $msg);
$result = $e->getMessage();
}
$cvrResult = new CompanyLookupResult();
if ($result && isset($result->data->CVR_Virksomhed->nodes) && !empty($result->data->CVR_Virksomhed->nodes)) {
$companyGraph = $result->data->CVR_Virksomhed->nodes[0]->id_CVR_CVREnhed_id_ref->nodes[0];
$cvrResult->setSuccessful();
$cvrResult->setCvr($param);
if ($companyGraph->id_CVR_Navn_CVREnhedsId_ref) {
$cvrResult->setName($companyGraph->id_CVR_Navn_CVREnhedsId_ref->vaerdi);
}
if ($companyGraph->id_CVR_Adressering_CVREnhedsId_ref) {
$address = $companyGraph->id_CVR_Adressering_CVREnhedsId_ref->nodes[0];
$cvrResult->setStreet($address->CVRAdresse_vejnavn ?? '');
$cvrResult->setHouseNr($address->CVRAdresse_husnummerFra ?? '');
$cvrResult->setFloor($address->CVRAdresse_etagebetegnelse ?? '');
$cvrResult->setApartmentNr($address->CVRAdresse_doerbetegnelse ?? '');
$cvrResult->setPostalCode($address->CVRAdresse_postnummer ?? '');
$city = $address->CVRAdresse_postdistrikt ?? $cvrResult->getPostalCode();
$cvrResult->setCity($city);
$cvrResult->setMunicipalityCode($address->CVRAdresse_kommunekode ?? '');
}
}
else {
$cvrResult->setSuccessful(FALSE);
if (is_string($result)) {
$cvrResult->setErrorMessage($result);
}
}
return $cvrResult;
}
/**
* Executes the GraphQL lookup request for a specific CVR number.
*
* Builds the GraphQL payload and sends it to the configured Datafordeler
* endpoint using the shared HTTP request flow from the parent class.
*
* @param string $cvr
* The CVR number to look up.
*
* @return \Psr\Http\Message\ResponseInterface
* The raw HTTP response from the GraphQL endpoint.
*
* @throws \GuzzleHttp\Exception\GuzzleException
*/
private function executeQuery($cvr): ResponseInterface {
$this->httpClient = new Client();
// Setting date to TODAY 00:00:00, so that we are always getting up-to-date
// information.
$virkningstid = (new \DateTimeImmutable('today', new \DateTimeZone('UTC')))
->format('Y-m-d\T00:00:00\Z');
$query = <<<GRAPHQL
{ CVR_Virksomhed(first: 1, virkningstid: "{$virkningstid}", where: { CVRNummer: { eq: {$cvr} } }) {
nodes {
CVRNummer
id_CVR_CVREnhed_id_ref(first: 1) {
nodes {
id_CVR_Navn_CVREnhedsId_ref { vaerdi }
id_CVR_Adressering_CVREnhedsId_ref(first: 1, where: { AdresseringAnvendelse: { in: ["beliggenhedsadresse", "postadresse"] } }) {
nodes {
AdresseringAnvendelse
CVRAdresse_vejnavn
CVRAdresse_husnummerFra
CVRAdresse_etagebetegnelse
CVRAdresse_doerbetegnelse
CVRAdresse_postnummer
CVRAdresse_postdistrikt
CVRAdresse_kommunekode
}
}
}
}
}
}
}
GRAPHQL;
$webserviceUrl = $this->configuration['webserviceurl_live'];
return $this->httpClient->post($webserviceUrl, [
'query' => [
'apiKey' => $this->configuration['api_key'],
],
'json' => [
'query' => $query,
],
]);
}
}