zend-blog-3-backend
133 строки · 3.6 Кб
1<?php
2/**
3* Created by PhpStorm.
4* User: morontt
5* Date: 04.05.16
6* Time: 23:01
7*/
8
9namespace App\Command;10
11use App\Entity\Post;12use App\Model\Image;13use App\Service\PictureTagBuilder;14use App\Service\TextProcessor;15use Doctrine\ORM\EntityManager;16use Doctrine\ORM\EntityManagerInterface;17use Symfony\Component\Console\Command\Command;18use Symfony\Component\Console\Input\InputArgument;19use Symfony\Component\Console\Input\InputInterface;20use Symfony\Component\Console\Output\OutputInterface;21
22class PostsBatchUpdateCommand extends Command23{
24/**25* @var EntityManager
26*/
27private $em;28
29private TextProcessor $textProcessor;30
31private PictureTagBuilder $ptb;32
33/**34* @param EntityManagerInterface $em
35* @param TextProcessor $textProcessor
36* @param PictureTagBuilder $ptb
37*/
38public function __construct(EntityManagerInterface $em, TextProcessor $textProcessor, PictureTagBuilder $ptb)39{40parent::__construct();41
42$this->em = $em;43$this->ptb = $ptb;44$this->textProcessor = $textProcessor;45
46$em->getConfiguration()->setSQLLogger(null);47}48
49protected function configure(): void50{51$this52->setName('mtt:posts:update')53->setDescription('Batch update all posts')54->addArgument('articleId', InputArgument::OPTIONAL, 'article ID')55;56}57
58/**59* @param InputInterface $input
60* @param OutputInterface $output
61*
62* @throws \Doctrine\ORM\ORMException
63* @throws \JsonException
64*
65* @return int
66*/
67protected function execute(InputInterface $input, OutputInterface $output): int68{69$startTime = microtime(true);70
71$postId = $input->getArgument('articleId');72$repo = $this->em->getRepository(Post::class);73if ($postId) {74$postGenerator = function () use ($repo, $postId) {75$post = $repo->find((int)$postId);76if (!$post) {77return;78}79
80yield [$post];81};82} else {83$postGenerator = function () use ($repo) {84$i = 0;85while (true) {86$posts = $repo->getPostsForIteration($i);87
88$i++;89if (!count($posts)) {90return;91}92
93yield $posts;94}95};96}97
98$cnt = 0;99foreach ($postGenerator() as $posts) {100/* @var Post $post */101foreach ($posts as $post) {102$cnt++;103$this->textProcessor->processing($post);104$this->em->flush();105
106$media = $post->getDefaultImage();107if ($media && $media->isImage()) {108$picture = $this->ptb->featuredPictureTag($media);109$media->setPictureTag($picture);110
111$srcSet = (new Image($media))->getSrcSet();112$srcSetData = $srcSet->toArray();113if (!empty($srcSetData)) {114$media->setSrcSet(json_encode($srcSetData, JSON_THROW_ON_ERROR));115}116
117$this->em->flush();118}119}120}121
122$output->writeln('');123$output->writeln(sprintf('<info>Update <comment>%d</comment> topics</info>', $cnt));124
125$endTime = microtime(true);126
127$output->writeln(128sprintf('<info>Total time: <comment>%s</comment> sec</info>', round($endTime - $startTime, 3))129);130
131return 0;132}133}
134