Преглед на файлове

some code cleanup

master
Evgeniy Ierusalimov преди 2 седмици
родител
ревизия
b9f713de5b
променени са 4 файла, в които са добавени 83 реда и са изтрити 51 реда
  1. 25
    7
      src/Command/ImportFromXmlCommand.php
  2. 3
    2
      src/Service/MailFetcher.php
  3. 46
    41
      src/Service/PortfolioManager.php
  4. 9
    1
      src/Service/TelegramNotifier.php

+ 25
- 7
src/Command/ImportFromXmlCommand.php Целия файл

@@ -7,7 +7,6 @@ use App\Service\TelegramNotifier;
7 7
 use App\Service\XmlParser;
8 8
 use Symfony\Component\Console\Attribute\AsCommand;
9 9
 use Symfony\Component\Console\Command\Command;
10
-use Symfony\Component\Console\Input\InputArgument;
11 10
 use Symfony\Component\Console\Input\InputInterface;
12 11
 use Symfony\Component\Console\Input\InputOption;
13 12
 use Symfony\Component\Console\Output\OutputInterface;
@@ -39,25 +38,44 @@ class ImportFromXmlCommand extends Command
39 38
     protected function execute(InputInterface $input, OutputInterface $output): int
40 39
     {
41 40
         $io = new SymfonyStyle($input, $output);
41
+
42 42
         $xmlFile = $input->getOption('xml-file');
43
+        if (null === $xmlFile) {
44
+            $io->error('The --xml-file option is required.');
45
+
46
+            return Command::INVALID;
47
+        }
43 48
 
44
-//        if ($xmlFile) {
45
-//            $io->note(sprintf('You passed an argument: %s', $xmlFile));
46
-//        }
49
+        if (!is_file($xmlFile)) {
50
+            $io->error(sprintf('File not found: %s', $xmlFile));
51
+
52
+            return Command::INVALID;
53
+        }
47 54
 
48 55
         $xmlString = file_get_contents($xmlFile);
56
+        if (false === $xmlString) {
57
+            $io->error(sprintf('Cannot read file: %s', $xmlFile));
58
+
59
+            return Command::FAILURE;
60
+        }
61
+
49 62
         $xml = simplexml_load_string($xmlString);
63
+        if (false === $xml) {
64
+            $io->error('Invalid XML content.');
65
+
66
+            return Command::FAILURE;
67
+        }
50 68
 
51 69
         $parsedPortfolio = $this->xmlParser->processXml($xml);
52
-        print $this->portfolioPresenter->toText($parsedPortfolio);
70
+
71
+        $output->writeln($this->portfolioPresenter->toText($parsedPortfolio));
72
+
53 73
         $this->portfolioPresenter->toImage($parsedPortfolio, 'portfolio.png');
54 74
 
55 75
         if ($input->getOption('notify')) {
56 76
             $this->telegramNotifier->notify('', 'portfolio.png');
57 77
         }
58 78
 
59
-        //$io->success('You have a new command! Now make it your own! Pass --help to see your options.');
60
-
61 79
         return Command::SUCCESS;
62 80
     }
63 81
 }

+ 3
- 2
src/Service/MailFetcher.php Целия файл

@@ -11,6 +11,7 @@ use Symfony\Component\Filesystem\Filesystem;
11 11
 use Symfony\Component\Filesystem\Path;
12 12
 use App\Presentation\PortfolioPresenter;
13 13
 use App\Service\TelegramNotifier;
14
+use PhpImap\Exceptions\ConnectionException;
14 15
 
15 16
 readonly class MailFetcher
16 17
 {
@@ -35,9 +36,9 @@ readonly class MailFetcher
35 36
             // Get all emails (messages)
36 37
             // PHP.net imap_search criteria: http://php.net/manual/en/function.imap-search.php
37 38
             $mailsIds = $mailbox->searchMailbox('ALL');
38
-        } catch (PhpImap\Exceptions\ConnectionException $ex) {
39
+        } catch (ConnectionException $ex) {
39 40
             $this->logger->error("IMAP connection failed: " . implode(",", $ex->getErrors('all')));
40
-            die();
41
+            throw new \RuntimeException('IMAP connection failed', 0, $ex);
41 42
         }
42 43
 
43 44
         if (!$mailsIds) {

+ 46
- 41
src/Service/PortfolioManager.php Целия файл

@@ -28,19 +28,22 @@ readonly class PortfolioManager
28 28
         if ($portfolio) {
29 29
             $this->logger->debug("Found existing portfolio with id: " . $portfolio->getId() . ', skipped..');
30 30
             return false;
31
-        } else {
32
-            $newPortfolio = $this->savePortfolio($parsedPortfolio, $xmlString);
33
-            $this->logger->debug("Saved new portfolio with id: " . $newPortfolio->getId());
34
-            return true;
35 31
         }
32
+
33
+        $newPortfolio = $this->savePortfolio($parsedPortfolio, $xmlString, $startDate, $endDate);
34
+        $this->logger->debug("Saved new portfolio with id: " . $newPortfolio->getId());
35
+
36
+        return true;
36 37
     }
37 38
 
38
-    private function savePortfolio(ParsedPortfolio $parsedPortfolio, string $xmlString): Portfolio
39
-    {
39
+    private function savePortfolio(
40
+        ParsedPortfolio $parsedPortfolio,
41
+        string $xmlString,
42
+        \DateTime $startDate,
43
+        \DateTime $endDate,
44
+    ): Portfolio {
40 45
         $this->logger->debug(print_r($parsedPortfolio, true));
41 46
 
42
-        list($startDate, $endDate) = $parsedPortfolio->extractPeriod();
43
-
44 47
         $portfolio = new Portfolio();
45 48
 
46 49
         $portfolio->setClientAgreement($parsedPortfolio->getHeader()['Клиент']);
@@ -48,39 +51,41 @@ readonly class PortfolioManager
48 51
         $portfolio->setEndDate(new \DateTimeImmutable($endDate->format('Y-m-d')));
49 52
         $portfolio->setXmlData($xmlString);
50 53
 
51
-        $this->entityManager->persist($portfolio);
52
-
53
-        foreach ($parsedPortfolio->getDetails() as $parsedDetail) {
54
-            $detail = new PortfolioDetail();
55
-
56
-            $detail->setPortfolio($portfolio);
57
-            $detail->setIssuer($parsedDetail['Эмитент']);
58
-            $detail->setSecurity($parsedDetail['ЦБ']);
59
-            $detail->setPriceStart($parsedDetail['НОЦена']);
60
-            $detail->setPriceEnd($parsedDetail['КОЦена']);
61
-            $detail->setQuantityStart($parsedDetail['КоличествоНО']);
62
-            $detail->setQuantityEnd($parsedDetail['КоличествоКО']);
63
-            $detail->setSumStart($parsedDetail['СуммаНКДНО']);
64
-            $detail->setSumEnd($parsedDetail['СуммаНКДКО']);
65
-
66
-            $this->entityManager->persist($detail);
67
-        }
68
-
69
-        foreach ($parsedPortfolio->getMovements() as $parsedMovement) {
70
-            $movement = new PortfolioMovement();
71
-
72
-            $movement->setPortfolio($portfolio);
73
-            $movement->setSecurity($parsedMovement['ЦБ']);
74
-            $movement->setPeriod(new \DateTimeImmutable($parsedMovement['Период']));
75
-            $movement->setQuantityStart($parsedMovement['НО']);
76
-            $movement->setQuantityEnd($parsedMovement['КО']);
77
-            $movement->setQuantityIncome($parsedMovement['Приход']);
78
-            $movement->setQuantityOutcome($parsedMovement['Расход']);
79
-
80
-            $this->entityManager->persist($movement);
81
-        }
82
-
83
-        $this->entityManager->flush();
54
+        $this->entityManager->wrapInTransaction(function () use ($parsedPortfolio, $portfolio): void {
55
+            $this->entityManager->persist($portfolio);
56
+
57
+            foreach ($parsedPortfolio->getDetails() as $parsedDetail) {
58
+                $detail = new PortfolioDetail();
59
+
60
+                $detail->setPortfolio($portfolio);
61
+                $detail->setIssuer($parsedDetail['Эмитент']);
62
+                $detail->setSecurity($parsedDetail['ЦБ']);
63
+                $detail->setPriceStart($parsedDetail['НОЦена']);
64
+                $detail->setPriceEnd($parsedDetail['КОЦена']);
65
+                $detail->setQuantityStart($parsedDetail['КоличествоНО']);
66
+                $detail->setQuantityEnd($parsedDetail['КоличествоКО']);
67
+                $detail->setSumStart($parsedDetail['СуммаНКДНО']);
68
+                $detail->setSumEnd($parsedDetail['СуммаНКДКО']);
69
+
70
+                $this->entityManager->persist($detail);
71
+            }
72
+
73
+            foreach ($parsedPortfolio->getMovements() as $parsedMovement) {
74
+                $movement = new PortfolioMovement();
75
+
76
+                $movement->setPortfolio($portfolio);
77
+                $movement->setSecurity($parsedMovement['ЦБ']);
78
+                $movement->setPeriod(new \DateTimeImmutable($parsedMovement['Период']));
79
+                $movement->setQuantityStart($parsedMovement['НО']);
80
+                $movement->setQuantityEnd($parsedMovement['КО']);
81
+                $movement->setQuantityIncome($parsedMovement['Приход']);
82
+                $movement->setQuantityOutcome($parsedMovement['Расход']);
83
+
84
+                $this->entityManager->persist($movement);
85
+            }
86
+
87
+            $this->entityManager->flush();
88
+        });
84 89
 
85 90
         return $portfolio;
86 91
     }

+ 9
- 1
src/Service/TelegramNotifier.php Целия файл

@@ -2,6 +2,7 @@
2 2
 
3 3
 namespace App\Service;
4 4
 
5
+use Psr\Log\LoggerInterface;
5 6
 use Symfony\Component\Notifier\Bridge\Telegram\TelegramTransport;
6 7
 use Symfony\Component\Notifier\Chatter;
7 8
 use Symfony\Component\Notifier\Bridge\Telegram\TelegramOptions;
@@ -14,6 +15,7 @@ readonly class TelegramNotifier
14 15
         private string $telegramBotToken,
15 16
         private string $telegramChatId,
16 17
         private HttpClientInterface $httpClient,
18
+        private LoggerInterface $logger,
17 19
     ) {
18 20
     }
19 21
 
@@ -36,6 +38,12 @@ readonly class TelegramNotifier
36 38
 
37 39
         $chatMessage->options($telegramOptions);
38 40
 
39
-        $chatter->send($chatMessage);
41
+        try {
42
+            $chatter->send($chatMessage);
43
+        } catch (\Throwable $e) {
44
+            $this->logger->error('Telegram notification failed: ' . $e->getMessage(), [
45
+                'exception' => $e,
46
+            ]);
47
+        }
40 48
     }
41 49
 }

Loading…
Отказ
Запис