Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
68.75% covered (warning)
68.75%
11 / 16
50.00% covered (danger)
50.00%
1 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
PdfSignatureDetectionService
68.75% covered (warning)
68.75%
11 / 16
50.00% covered (danger)
50.00%
1 / 2
5.76
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 hasSignatures
66.67% covered (warning)
66.67%
10 / 15
0.00% covered (danger)
0.00%
0 / 1
4.59
1<?php
2
3declare(strict_types=1);
4/**
5 * SPDX-FileCopyrightText: 2020-2024 LibreCode coop and contributors
6 * SPDX-License-Identifier: AGPL-3.0-or-later
7 */
8
9namespace OCA\Libresign\Service;
10
11use OCA\Libresign\Exception\LibresignException;
12use OCA\Libresign\Handler\SignEngine\SignEngineFactory;
13use Psr\Log\LoggerInterface;
14
15class PdfSignatureDetectionService {
16    public function __construct(
17        private SignEngineFactory $signEngineFactory,
18        private LoggerInterface $logger,
19    ) {
20    }
21
22    /**
23     * Check if a PDF has existing signatures
24     *
25     * @param string $pdfContent The PDF file content
26     * @return bool True if the file has signatures, false otherwise
27     */
28    public function hasSignatures(string $pdfContent): bool {
29        $resource = fopen('php://memory', 'r+');
30        if ($resource === false) {
31            $this->logger->warning('Failed to create resource for signature detection');
32            return false;
33        }
34
35        fwrite($resource, $pdfContent);
36        rewind($resource);
37
38        try {
39            $engine = $this->signEngineFactory->resolve('pdf');
40            $certificates = $engine->getCertificateChain($resource);
41            return !empty($certificates);
42        } catch (LibresignException) {
43            return false;
44        } catch (\Throwable $e) {
45            $this->logger->debug('Failed to detect signatures: ' . $e->getMessage());
46            return false;
47        } finally {
48            fclose($resource);
49        }
50    }
51}