Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
50.57% covered (warning)
50.57%
44 / 87
45.45% covered (danger)
45.45%
5 / 11
CRAP
0.00% covered (danger)
0.00%
0 / 1
BaseController
50.57% covered (warning)
50.57%
44 / 87
45.45% covered (danger)
45.45%
5 / 11
182.91
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 getLogList
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 clearLogList
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getSpendTime
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 sendMailer
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
6
 removeEntityOlderThanOneHour
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 deleteEntityFromQueue
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
3.02
 testEntity
39.13% covered (danger)
39.13%
9 / 23
0.00% covered (danger)
0.00%
0 / 1
22.43
 monitorProcesses
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
56
 log
84.62% covered (warning)
84.62%
11 / 13
0.00% covered (danger)
0.00%
0 / 1
3.03
 convertCollectionToArray
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2
3/**
4 *
5 * @package Zmsmessaging
6 *
7 */
8
9namespace BO\Zmsmessaging;
10
11use BO\Zmsentities\Mail;
12use BO\Zmsentities\Mimepart;
13use BO\Zmsentities\Schema\Entity;
14use BO\Mellon\Validator;
15
16class BaseController
17{
18    protected $verbose = false;
19    protected static $logList = [];
20    protected $workstation = null;
21    protected $startTime;
22    protected $maxRunTime = 50;
23
24    public function __construct($verbose = false, $maxRunTime = 50)
25    {
26        $this->verbose = $verbose;
27        $this->startTime = microtime(true);
28        $this->maxRunTime = $maxRunTime;
29    }
30
31    public static function getLogList()
32    {
33        return static::$logList;
34    }
35
36    public static function clearLogList(): void
37    {
38        static::$logList = [];
39    }
40
41    protected function getSpendTime(): float
42    {
43        $time = round(microtime(true) - $this->startTime, 3);
44        return $time;
45    }
46
47    protected function sendMailer(Entity $entity, $mailer = null, $action = false)
48    {
49        // @codeCoverageIgnoreStart
50        $hasSendSuccess = ($action) ? $mailer->Send() : $action;
51        if (false !== $action && null !== $mailer && ! $hasSendSuccess) {
52            $this->log("Exception: SendingFailed  - " . \App::$now->format('c'));
53            throw new Exception\SendingFailed();
54        }
55        // @codeCoverageIgnoreEnd
56        $log = new Mimepart(['mime' => 'text/plain']);
57        $log->content = ($entity instanceof Mail) ? $entity->subject : $entity->message;
58        \App::$http->readPostResult('/log/process/' . $entity->process['id'] . '/', $log);
59        return $mailer;
60    }
61
62    /**
63     * @return false|null
64     */
65    protected function removeEntityOlderThanOneHour(Mail $entity)
66    {
67        if (3600 < \App::$now->getTimestamp() - $entity->createTimestamp) {
68            $this->deleteEntityFromQueue($entity);
69            $log = new Mimepart(['mime' => 'text/plain']);
70            $log->content = 'Zmsmessaging Failure: Queue entry older than 1 hour has been removed';
71            \App::$http->readPostResult('/log/process/' . $entity->process['id'] . '/', $log, ['error' => 1]);
72            \App::$log->warning($log->content);
73            return false;
74        }
75    }
76
77    public function deleteEntityFromQueue(Mail $entity): bool
78    {
79        if (!($entity instanceof Mail)) {
80            return false;
81        }
82        try {
83            $entity = \App::$http
84                ->readDeleteResult('/mails/' . $entity->id . '/')
85                ->getEntity();
86        } catch (\BO\Zmsclient\Exception $exception) {
87            throw $exception;
88        }
89
90        return (bool) $entity;
91    }
92
93    /**
94     * @return void
95     */
96    public function testEntity(Mail $entity)
97    {
98        if (!isset($entity['department'])) {
99            throw new \Exception("Could not resolve department for message " . $entity['id']);
100        }
101        if (!isset($entity['department']['email'])) {
102            throw new \Exception(
103                "No mail address for department "
104                . $entity['department']['name']
105                . " (departmentID="
106                . $entity['department']['id']
107                . " Vorgang="
108                . $entity['process']['id']
109                . ") "
110                . $entity['id']
111            );
112        }
113        if (! $entity->hasContent()) {
114            throw new \BO\Zmsmessaging\Exception\MailWithoutContent();
115        }
116        if ($entity instanceof Mail) {
117            $isMail = Validator::value($entity->getRecipient())->isMail()->getValue();
118            if (!$isMail) {
119                throw new \BO\Zmsmessaging\Exception\InvalidMailAddress();
120            }
121            if (\App::$verify_dns_enabled) {
122                $hasDns = Validator::value($entity->getRecipient())->isMail()->hasDNS()->getValue();
123                if (!$hasDns) {
124                    throw new \BO\Zmsmessaging\Exception\InvalidMailAddress();
125                }
126            }
127        }
128    }
129
130    protected function monitorProcesses(array $processHandles): void
131    {
132        $running = true;
133        while ($running) {
134            $running = false;
135            foreach ($processHandles as &$handle) {
136                if (is_resource($handle['process'])) {
137                    $status = proc_get_status($handle['process']);
138                    if ($status['running']) {
139                        $running = true;
140                    } else {
141                        $output = stream_get_contents($handle['pipes'][1]);  // stdout
142                        $errorOutput = stream_get_contents($handle['pipes'][2]);  // stderr
143                        fclose($handle['pipes'][1]);
144                        fclose($handle['pipes'][2]);
145                        if (trim($output)) {
146                            $this->log("\nProcess stdout: " . trim($output) . "\n");
147                        }
148                        if (trim($errorOutput)) {
149                            $this->log("\nProcess stderr: " . trim($errorOutput) . "\n");
150                        }
151
152                        proc_close($handle['process']);
153                        $handle['process'] = null;
154                    }
155                }
156            }
157            usleep(500000);
158        }
159    }
160
161
162
163
164    public function log(string $message): void
165    {
166        if (is_array($message)) {
167            $message = print_r($message, true);
168        }
169
170        $time = $this->getSpendTime();
171        $memory = memory_get_usage() / (1024 * 1024);
172        static::$logList[] = $message;
173
174        $context = [
175            'component' => 'zmsmessaging',
176            'elapsed' => $time,
177            'memory_mb' => $memory,
178        ];
179        if ($this->verbose) {
180            \App::$log->debug($message, $context);
181        } else {
182            \App::$log->info($message, $context);
183        }
184    }
185
186    protected function convertCollectionToArray($collection): array
187    {
188        $this->log("Converting collection to array");
189        $array = [];
190        foreach ($collection as $item) {
191            $array[] = $item;
192        }
193        $this->log("Conversion complete, array size: " . count($array));
194        return $array;
195    }
196}