Passed
Push — master ( 3b2234...ff0cff )
by Tim
13:15
created

MetaLoader   F

Complexity

Total Complexity 117

Size/Duplication

Total Lines 677
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 273
dl 0
loc 677
rs 2
c 3
b 0
f 0
wmc 117

21 Methods

Rating   Name   Duplication   Size   Complexity  
A getTypes() 0 3 1
A setTypes() 0 6 2
A __construct() 0 15 4
B saveState() 0 18 7
B writeMetadataFiles() 0 37 10
A dumpMetadataStdOut() 0 17 3
A loadXML() 0 8 2
A writeARPfile() 0 26 3
B addMetadata() 0 30 7
A writeState() 0 11 3
A processWhitelist() 0 9 4
A processBlacklist() 0 9 4
A processCertificates() 0 12 4
A writeMetadataPdo() 0 10 3
A getTime() 0 4 1
B processAttributeWhitelist() 0 29 7
A addCachedMetadata() 0 12 6
A writeMetadataSerialize() 0 15 3
C containsArray() 0 57 13
A createContext() 0 23 6
F loadSource() 0 108 24

How to fix   Complexity   

Complex Class

Complex classes like MetaLoader often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use MetaLoader, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\Module\metarefresh;
6
7
use Exception;
8
use SimpleSAML\Configuration;
9
use SimpleSAML\Logger;
10
use SimpleSAML\Metadata;
11
use SimpleSAML\Utils;
12
use SimpleSAML\XML\DOMDocumentFactory;
13
14
/**
15
 * @package SimpleSAMLphp
16
 */
17
class MetaLoader
18
{
19
    /** @var int|null */
20
    private ?int $expire;
21
22
    /** @var array */
23
    private array $metadata = [];
24
25
    /** @var object|null */
26
    private ?object $oldMetadataSrc;
27
28
    /** @var string|null */
29
    private ?string $stateFile = null;
30
31
    /** @var bool */
32
    private bool $changed = false;
33
34
    /** @var array */
35
    private array $state = [];
36
37
    /** @var array */
38
    private array $types = [
39
        'saml20-idp-remote',
40
        'saml20-sp-remote',
41
        'attributeauthority-remote'
42
    ];
43
44
45
    /**
46
     * Constructor
47
     *
48
     * @param int|null $expire
49
     * @param string|null  $stateFile
50
     * @param object|null  $oldMetadataSrc
51
     */
52
    public function __construct(int $expire = null, string $stateFile = null, object $oldMetadataSrc = null)
53
    {
54
        $this->expire = $expire;
55
        $this->oldMetadataSrc = $oldMetadataSrc;
56
        $this->stateFile = $stateFile;
57
58
        // Read file containing $state from disk
59
        /** @psalm-var array|null */
60
        $state = null;
61
        if (!is_null($stateFile) && is_readable($stateFile)) {
62
            include($stateFile);
63
        }
64
65
        if (!empty($state)) {
0 ignored issues
show
introduced by
The condition empty($state) is always false.
Loading history...
66
            $this->state = $state;
67
        }
68
    }
69
70
71
    /**
72
     * Get the types of entities that will be loaded.
73
     *
74
     * @return array The entity types allowed.
75
     */
76
    public function getTypes(): array
77
    {
78
        return $this->types;
79
    }
80
81
82
    /**
83
     * Set the types of entities that will be loaded.
84
     *
85
     * @param string|array $types Either a string with the name of one single type allowed, or an array with a list of
86
     * types. Pass an empty array to reset to all types of entities.
87
     */
88
    public function setTypes($types): void
89
    {
90
        if (!is_array($types)) {
91
            $types = [$types];
92
        }
93
        $this->types = $types;
94
    }
95
96
97
    /**
98
     * This function processes a SAML metadata file.
99
     *
100
     * @param array $source
101
     */
102
    public function loadSource(array $source): void
103
    {
104
        if (preg_match('@^https?://@i', $source['src'])) {
105
            // Build new HTTP context
106
            $context = $this->createContext($source);
107
108
            $httpUtils = new Utils\HTTP();
109
            // GET!
110
            try {
111
                /** @var array $response  We know this because we set the third parameter to `true` */
112
                $response = $httpUtils->fetch($source['src'], $context, true);
113
                list($data, $responseHeaders) = $response;
114
            } catch (Exception $e) {
115
                Logger::warning('metarefresh: ' . $e->getMessage());
116
            }
117
118
            // We have response headers, so the request succeeded
119
            if (!isset($responseHeaders)) {
120
                // No response headers, this means the request failed in some way, so re-use old data
121
                Logger::info('No response from ' . $source['src'] . ' - attempting to re-use cached metadata');
122
                $this->addCachedMetadata($source);
123
                return;
124
            } elseif (preg_match('@^HTTP/1\.[01]\s304\s@', $responseHeaders[0])) {
125
                // 304 response
126
                Logger::debug('Received HTTP 304 (Not Modified) - attempting to re-use cached metadata');
127
                $this->addCachedMetadata($source);
128
                return;
129
            } elseif (!preg_match('@^HTTP/1\.[01]\s200\s@', $responseHeaders[0])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $responseHeaders does not seem to be defined for all execution paths leading up to this point.
Loading history...
130
                // Other error
131
                Logger::info('Error from ' . $source['src'] . ' - attempting to re-use cached metadata');
132
                $this->addCachedMetadata($source);
133
                return;
134
            }
135
        } else {
136
            // Local file.
137
            $data = file_get_contents($source['src']);
138
            $responseHeaders = null;
139
        }
140
141
        // Everything OK. Proceed.
142
        if (isset($source['conditionalGET']) && $source['conditionalGET']) {
143
            // Stale or no metadata, so a fresh copy
144
            Logger::debug('Downloaded fresh copy');
145
        }
146
147
        try {
148
            $entities = $this->loadXML($data, $source);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $data does not seem to be defined for all execution paths leading up to this point.
Loading history...
149
        } catch (Exception $e) {
150
            Logger::notice(
151
                'XML parser error when parsing ' . $source['src'] . ' - attempting to re-use cached metadata'
152
            );
153
            Logger::debug('XML parser returned: ' . $e->getMessage());
154
            $this->addCachedMetadata($source);
155
            return;
156
        }
157
158
        foreach ($entities as $entity) {
159
            if (!$this->processBlacklist($entity, $source)) {
160
                continue;
161
            }
162
            if (!$this->processWhitelist($entity, $source)) {
163
                continue;
164
            }
165
            if (!$this->processAttributeWhitelist($entity, $source)) {
166
                continue;
167
            }
168
            if (!$this->processCertificates($entity, $source)) {
169
                continue;
170
            }
171
172
            $template = null;
173
            if (array_key_exists('template', $source)) {
174
                $template = $source['template'];
175
            }
176
177
            if (array_key_exists('regex-template', $source)) {
178
                foreach ($source['regex-template'] as $e => $t) {
179
                    if (preg_match($e, $entity->getEntityID())) {
180
                        if (is_array($template)) {
181
                            $template = array_merge($template, $t);
182
                        } else {
183
                            $template = $t;
184
                        }
185
                    }
186
                }
187
            }
188
189
            if (in_array('saml20-sp-remote', $this->types, true)) {
190
                $this->addMetadata($source['src'], $entity->getMetadata20SP(), 'saml20-sp-remote', $template);
191
            }
192
            if (in_array('saml20-idp-remote', $this->types, true)) {
193
                $this->addMetadata($source['src'], $entity->getMetadata20IdP(), 'saml20-idp-remote', $template);
194
            }
195
            if (in_array('attributeauthority-remote', $this->types, true)) {
196
                $attributeAuthorities = $entity->getAttributeAuthorities();
197
                if (count($attributeAuthorities) && !empty($attributeAuthorities[0])) {
198
                    $this->addMetadata(
199
                        $source['src'],
200
                        $attributeAuthorities[0],
201
                        'attributeauthority-remote',
202
                        $template
203
                    );
204
                }
205
            }
206
        }
207
208
        Logger::debug(sprintf('Found %d entities', count($entities)));
209
        $this->saveState($source, $responseHeaders);
210
    }
211
212
213
    /**
214
     * @param \SimpleSAML\Metadata\SAMLParser $entity
215
     * @param array $source
216
     * @bool
217
     */
218
    private function processCertificates(Metadata\SAMLParser $entity, array $source): bool
219
    {
220
        if (array_key_exists('certificates', $source) && ($source['certificates'] !== null)) {
221
            if (!$entity->validateSignature($source['certificates'])) {
222
                $entityId = $entity->getEntityId();
223
                Logger::notice(
224
                    'Skipping "' . $entityId . '" - could not verify signature using certificate.' . "\n"
225
                );
226
                return false;
227
            }
228
        }
229
        return true;
230
    }
231
232
233
    /**
234
     * @param \SimpleSAML\Metadata\SAMLParser $entity
235
     * @param array $source
236
     * @bool
237
     */
238
    private function processBlacklist(Metadata\SAMLParser $entity, array $source): bool
239
    {
240
        if (isset($source['blacklist'])) {
241
            if (!empty($source['blacklist']) && in_array($entity->getEntityId(), $source['blacklist'], true)) {
242
                Logger::info('Skipping "' . $entity->getEntityId() . '" - blacklisted.' . "\n");
243
                return false;
244
            }
245
        }
246
        return true;
247
    }
248
249
250
    /**
251
     * @param \SimpleSAML\Metadata\SAMLParser $entity
252
     * @param array $source
253
     * @bool
254
     */
255
    private function processWhitelist(Metadata\SAMLParser $entity, array $source): bool
256
    {
257
        if (isset($source['whitelist'])) {
258
            if (!empty($source['whitelist']) && !in_array($entity->getEntityId(), $source['whitelist'], true)) {
259
                Logger::info('Skipping "' . $entity->getEntityId() . '" - not in the whitelist.' . "\n");
260
                return false;
261
            }
262
        }
263
        return true;
264
    }
265
266
267
    /**
268
     * @param \SimpleSAML\Metadata\SAMLParser $entity
269
     * @param array $source
270
     * @bool
271
     */
272
    private function processAttributeWhitelist(Metadata\SAMLParser $entity, array $source): bool
273
    {
274
        /* Do we have an attribute whitelist? */
275
        if (isset($source['attributewhitelist']) && !empty($source['attributewhitelist'])) {
276
            $idpMetadata = $entity->getMetadata20IdP();
277
            if (!isset($idpMetadata)) {
278
                /* Skip non-IdPs */
279
                return false;
280
            }
281
282
            /**
283
             * Do a recursive comparison for each whitelist of the attributewhitelist with the idpMetadata for this
284
             * IdP. At least one of these whitelists should match
285
             */
286
            $match = false;
287
            foreach ($source['attributewhitelist'] as $whitelist) {
288
                if ($this->containsArray($whitelist, $idpMetadata)) {
289
                    $match = true;
290
                    break;
291
                }
292
            }
293
294
            if (!$match) {
295
                /* No match found -> next IdP */
296
                return false;
297
            }
298
            Logger::debug('Whitelisted entityID: ' . $entity->getEntityID());
299
        }
300
        return true;
301
    }
302
303
304
    /**
305
     * @param array|string $src
306
     * @param array|string $dst
307
     * @return bool
308
     *
309
     * Recursively checks whether array $dst contains array $src. If $src
310
     * is not an array, a literal comparison is being performed.
311
     */
312
    private function containsArray($src, $dst): bool
313
    {
314
        if (is_array($src)) {
315
            if (!is_array($dst)) {
316
                return false;
317
            }
318
            $dstKeys = array_keys($dst);
319
320
            /* Loop over all src keys */
321
            foreach ($src as $srcKey => $srcval) {
322
                if (is_int($srcKey)) {
323
                    /* key is number, check that the key appears as one
324
                     * of the destination keys: if not, then src has
325
                     * more keys than dst */
326
                    if (!array_key_exists($srcKey, $dst)) {
327
                        return false;
328
                    }
329
330
                    /* loop over dest keys, to find value: we don't know
331
                     * whether they are in the same order */
332
                    $submatch = false;
333
                    foreach ($dstKeys as $dstKey) {
334
                        if ($this->containsArray($srcval, $dst[$dstKey])) {
335
                            $submatch = true;
336
                            break;
337
                        }
338
                    }
339
                    if (!$submatch) {
340
                        return false;
341
                    }
342
                } else {
343
                    /* key is regexp: find matching keys */
344
                    /** @var array|false $matchingDstKeys */
345
                    $matchingDstKeys = preg_grep($srcKey, $dstKeys);
346
                    if (!is_array($matchingDstKeys)) {
347
                        return false;
348
                    }
349
350
                    $match = false;
351
                    foreach ($matchingDstKeys as $dstKey) {
352
                        if ($this->containsArray($srcval, $dst[$dstKey])) {
353
                            /* Found a match */
354
                            $match = true;
355
                            break;
356
                        }
357
                    }
358
                    if (!$match) {
359
                        /* none of the keys has a matching value */
360
                        return false;
361
                    }
362
                }
363
            }
364
            /* each src key/value matches */
365
            return true;
366
        } else {
367
            /* src is not an array, do a regexp match against dst */
368
            return (preg_match($src, strval($dst)) === 1);
369
        }
370
    }
371
372
    /**
373
     * Create HTTP context, with any available caches taken into account
374
     *
375
     * @param array $source
376
     * @return array
377
     */
378
    private function createContext(array $source): array
379
    {
380
        $config = Configuration::getInstance();
381
        $name = $config->getOptionalString('technicalcontact_name', null);
382
        $mail = $config->getOptionalString('technicalcontact_email', null);
383
384
        $rawheader = "User-Agent: SimpleSAMLphp metarefresh, run by $name <$mail>\r\n";
385
386
        if (isset($source['conditionalGET']) && $source['conditionalGET']) {
387
            if (array_key_exists($source['src'], $this->state)) {
388
                $sourceState = $this->state[$source['src']];
389
390
                if (isset($sourceState['last-modified'])) {
391
                    $rawheader .= 'If-Modified-Since: ' . $sourceState['last-modified'] . "\r\n";
392
                }
393
394
                if (isset($sourceState['etag'])) {
395
                    $rawheader .= 'If-None-Match: ' . $sourceState['etag'] . "\r\n";
396
                }
397
            }
398
        }
399
400
        return ['http' => ['header' => $rawheader]];
401
    }
402
403
    private function addCachedMetadata(array $source): void
404
    {
405
        if (!isset($this->oldMetadataSrc)) {
406
            Logger::info('No oldMetadataSrc, cannot re-use cached metadata');
407
            return;
408
        }
409
410
        foreach ($this->types as $type) {
411
            foreach ($this->oldMetadataSrc->getMetadataSet($type) as $entity) {
0 ignored issues
show
Bug introduced by
The method getMetadataSet() does not exist on null. ( Ignorable by Annotation )

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

411
            foreach ($this->oldMetadataSrc->/** @scrutinizer ignore-call */ getMetadataSet($type) as $entity) {

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...
412
                if (array_key_exists('metarefresh:src', $entity)) {
413
                    if ($entity['metarefresh:src'] == $source['src']) {
414
                        $this->addMetadata($source['src'], $entity, $type);
415
                    }
416
                }
417
            }
418
        }
419
    }
420
421
422
    /**
423
     * Store caching state data for a source
424
     *
425
     * @param array $source
426
     * @param array|null $responseHeaders
427
     */
428
    private function saveState(array $source, ?array $responseHeaders): void
429
    {
430
        if (isset($source['conditionalGET']) && $source['conditionalGET']) {
431
            // Headers section
432
            if ($responseHeaders !== null) {
0 ignored issues
show
introduced by
The condition $responseHeaders !== null is always true.
Loading history...
433
                $candidates = ['last-modified', 'etag'];
434
435
                foreach ($candidates as $candidate) {
436
                    if (array_key_exists($candidate, $responseHeaders)) {
437
                        $this->state[$source['src']][$candidate] = $responseHeaders[$candidate];
438
                    }
439
                }
440
            }
441
442
            if (!empty($this->state[$source['src']])) {
443
                // Timestamp when this src was requested.
444
                $this->state[$source['src']]['requested_at'] = $this->getTime();
445
                $this->changed = true;
446
            }
447
        }
448
    }
449
450
451
    /**
452
     * Parse XML metadata and return entities
453
     *
454
     * @param string $data
455
     * @param array $source
456
     * @return \SimpleSAML\Metadata\SAMLParser[]
457
     * @throws \Exception
458
     */
459
    private function loadXML(string $data, array $source): array
460
    {
461
        try {
462
            $doc = DOMDocumentFactory::fromString($data);
463
        } catch (Exception $e) {
464
            throw new Exception('Failed to read XML from ' . $source['src']);
465
        }
466
        return Metadata\SAMLParser::parseDescriptorsElement($doc->documentElement);
467
    }
468
469
470
    /**
471
     * This function writes the state array back to disk
472
     *
473
     */
474
    public function writeState(): void
475
    {
476
        if ($this->changed && !is_null($this->stateFile)) {
477
            Logger::debug('Writing: ' . $this->stateFile);
478
            $sysUtils = new Utils\System();
479
            $sysUtils->writeFile(
480
                $this->stateFile,
481
                "<?php\n/* This file was generated by the metarefresh module at " . $this->getTime() . ".\n" .
482
                " Do not update it manually as it will get overwritten. */\n" .
483
                '$state = ' . var_export($this->state, true) . ";\n",
484
                0644
485
            );
486
        }
487
    }
488
489
490
    /**
491
     * This function writes the metadata to stdout.
492
     *
493
     */
494
    public function dumpMetadataStdOut(): void
495
    {
496
        foreach ($this->metadata as $category => $elements) {
497
            echo '/* The following data should be added to metadata/' . $category . '.php. */' . "\n";
498
499
            foreach ($elements as $m) {
500
                $filename = $m['filename'];
501
                $entityID = $m['metadata']['entityid'];
502
                $time = $this->getTime();
503
                echo "\n";
504
                echo '/* The following metadata was generated from ' . $filename . ' on ' . $time . '. */' . "\n";
505
                echo '$metadata[\'' . addslashes($entityID) . '\'] = ' . var_export($m['metadata'], true) . ';' . "\n";
506
            }
507
508
            echo "\n";
509
            echo '/* End of data which should be added to metadata/' . $category . '.php. */' . "\n";
510
            echo "\n";
511
        }
512
    }
513
514
515
    /**
516
     * This function adds metadata from the specified file to the list of metadata.
517
     * This function will return without making any changes if $metadata is NULL.
518
     *
519
     * @param string $filename The filename the metadata comes from.
520
     * @param \SAML2\XML\md\AttributeAuthorityDescriptor[]|null $metadata The metadata.
521
     * @param string $type The metadata type.
522
     * @param array|null $template The template.
523
     */
524
    private function addMetadata(string $filename, ?array $metadata, string $type, array $template = null): void
525
    {
526
        if ($metadata === null) {
0 ignored issues
show
introduced by
The condition $metadata === null is always false.
Loading history...
527
            return;
528
        }
529
530
        if (isset($template)) {
531
            $metadata = array_merge($metadata, $template);
532
        }
533
534
        $metadata['metarefresh:src'] = $filename;
535
        if (!array_key_exists($type, $this->metadata)) {
536
            $this->metadata[$type] = [];
537
        }
538
539
        // If expire is defined in constructor...
540
        if (!empty($this->expire)) {
541
            // If expire is already in metadata
542
            if (array_key_exists('expire', $metadata)) {
543
                // Override metadata expire with more restrictive global config
544
                if ($this->expire < $metadata['expire']) {
545
                    $metadata['expire'] = $this->expire;
546
                }
547
548
                // If expire is not already in metadata use global config
549
            } else {
550
                $metadata['expire'] = $this->expire;
551
            }
552
        }
553
        $this->metadata[$type][] = ['filename' => $filename, 'metadata' => $metadata];
554
    }
555
556
557
    /**
558
     * This function writes the metadata to an ARP file
559
     *
560
     * @param \SimpleSAML\Configuration $config
561
     */
562
    public function writeARPfile(Configuration $config): void
563
    {
564
        $arpfile = $config->getString('arpfile');
565
        $types = ['saml20-sp-remote'];
566
567
        $md = [];
568
        foreach ($this->metadata as $category => $elements) {
569
            if (!in_array($category, $types, true)) {
570
                continue;
571
            }
572
            $md = array_merge($md, $elements);
573
        }
574
575
        // $metadata, $attributemap, $prefix, $suffix
576
        $arp = new ARP(
577
            $md,
578
            $config->getOptionalString('attributemap', ''),
0 ignored issues
show
Bug introduced by
It seems like $config->getOptionalString('attributemap', '') can also be of type null; however, parameter $attributemap_filename of SimpleSAML\Module\metarefresh\ARP::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

578
            /** @scrutinizer ignore-type */ $config->getOptionalString('attributemap', ''),
Loading history...
579
            $config->getOptionalString('prefix', ''),
0 ignored issues
show
Bug introduced by
It seems like $config->getOptionalString('prefix', '') can also be of type null; however, parameter $prefix of SimpleSAML\Module\metarefresh\ARP::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

579
            /** @scrutinizer ignore-type */ $config->getOptionalString('prefix', ''),
Loading history...
580
            $config->getOptionalString('suffix', '')
0 ignored issues
show
Bug introduced by
It seems like $config->getOptionalString('suffix', '') can also be of type null; however, parameter $suffix of SimpleSAML\Module\metarefresh\ARP::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

580
            /** @scrutinizer ignore-type */ $config->getOptionalString('suffix', '')
Loading history...
581
        );
582
583
584
        $arpxml = $arp->getXML();
585
586
        Logger::info('Writing ARP file: ' . $arpfile . "\n");
587
        file_put_contents($arpfile, $arpxml);
588
    }
589
590
591
    /**
592
     * This function writes the metadata to to separate files in the output directory.
593
     *
594
     * @param string $outputDir
595
     */
596
    public function writeMetadataFiles(string $outputDir): void
597
    {
598
        while (strlen($outputDir) > 0 && $outputDir[strlen($outputDir) - 1] === '/') {
599
            $outputDir = substr($outputDir, 0, strlen($outputDir) - 1);
600
        }
601
602
        if (!file_exists($outputDir)) {
603
            Logger::info('Creating directory: ' . $outputDir . "\n");
604
            $res = @mkdir($outputDir, 0777, true);
605
            if ($res === false) {
606
                throw new Exception('Error creating directory: ' . $outputDir);
607
            }
608
        }
609
610
        foreach ($this->types as $type) {
611
            $filename = $outputDir . '/' . $type . '.php';
612
613
            if (array_key_exists($type, $this->metadata)) {
614
                $elements = $this->metadata[$type];
615
                Logger::debug('Writing: ' . $filename);
616
617
                $content  = '<?php' . "\n" . '/* This file was generated by the metarefresh module at ';
618
                $content .= $this->getTime() . "\nDo not update it manually as it will get overwritten\n" . '*/' . "\n";
619
620
                foreach ($elements as $m) {
621
                    $entityID = $m['metadata']['entityid'];
622
                    $content .= "\n" . '$metadata[\'';
623
                    $content .= addslashes($entityID) . '\'] = ' . var_export($m['metadata'], true) . ';' . "\n";
624
                }
625
626
                $sysUtils = new Utils\System();
627
                $sysUtils->writeFile($filename, $content, 0644);
628
            } elseif (is_file($filename)) {
629
                if (unlink($filename)) {
630
                    Logger::debug('Deleting stale metadata file: ' . $filename);
631
                } else {
632
                    Logger::warning('Could not delete stale metadata file: ' . $filename);
633
                }
634
            }
635
        }
636
    }
637
638
639
    /**
640
     * Save metadata for loading with the 'serialize' metadata loader.
641
     *
642
     * @param string $outputDir  The directory we should save the metadata to.
643
     */
644
    public function writeMetadataSerialize(string $outputDir): void
645
    {
646
        $metaHandler = new Metadata\MetaDataStorageHandlerSerialize(['directory' => $outputDir]);
647
648
        // First we add all the metadata entries to the metadata handler
649
        foreach ($this->metadata as $set => $elements) {
650
            foreach ($elements as $m) {
651
                $entityId = $m['metadata']['entityid'];
652
653
                Logger::debug(sprintf(
654
                    'metarefresh: Add metadata entry %s in set %s.',
655
                    var_export($entityId, true),
656
                    var_export($set, true),
657
                ));
658
                $metaHandler->saveMetadata($entityId, $set, $m['metadata']);
659
            }
660
        }
661
    }
662
663
664
    /**
665
     * This function uses the `PDO` metadata handler to upsert metadata in database.
666
     *
667
     * @param \SimpleSAML\Configuration $globalConfig
668
     * @param array $config An associative array with the configuration for `PDO` handler.
669
     *
670
     * @return void
671
     */
672
    public function writeMetadataPdo(Configuration $globalConfig, array $config = []): void
673
    {
674
        $metaHandler = new Metadata\MetaDataStorageHandlerPdo($globalConfig, $config);
0 ignored issues
show
Unused Code introduced by
The call to SimpleSAML\Metadata\Meta...ndlerPdo::__construct() has too many arguments starting with $config. ( Ignorable by Annotation )

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

674
        $metaHandler = /** @scrutinizer ignore-call */ new Metadata\MetaDataStorageHandlerPdo($globalConfig, $config);

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...
Bug introduced by
$globalConfig of type SimpleSAML\Configuration is incompatible with the type array expected by parameter $config of SimpleSAML\Metadata\Meta...ndlerPdo::__construct(). ( Ignorable by Annotation )

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

674
        $metaHandler = new Metadata\MetaDataStorageHandlerPdo(/** @scrutinizer ignore-type */ $globalConfig, $config);
Loading history...
675
676
        foreach ($this->metadata as $set => $elements) {
677
            foreach ($elements as $m) {
678
                $entityId = $m['metadata']['entityid'];
679
680
                Logger::debug("PDO Metarefresh: Upsert metadata entry `{$entityId}` in set `{$set}`.");
681
                $metaHandler->addEntry($entityId, $set, $m['metadata']);
682
            }
683
        }
684
    }
685
686
687
    /**
688
     * @return string
689
     */
690
    private function getTime(): string
691
    {
692
        // The current date, as a string
693
        return gmdate('Y-m-d\\TH:i:s\\Z');
694
    }
695
}
696