Completed
Pull Request — 1.5 (#761)
by Paweł
17:05
created

ProcessPackagesCommand   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 102
Duplicated Lines 5.88 %

Coupling/Cohesion

Components 2
Dependencies 14

Importance

Changes 0
Metric Value
wmc 7
lcom 2
cbo 14
dl 6
loc 102
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 17 1
A configure() 0 21 1
B execute() 6 45 5

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Superdesk Web Publisher Core Bundle.
7
 *
8
 * Copyright 2019 Sourcefabric z.ú. and contributors.
9
 *
10
 * For the full copyright and license information, please see the
11
 * AUTHORS and LICENSE files distributed with this source code.
12
 *
13
 * @copyright 2019 Sourcefabric z.ú
14
 * @license http://www.superdesk.org/license
15
 */
16
17
namespace SWP\Bundle\CoreBundle\Command;
18
19
use Knp\Component\Pager\Pagination\SlidingPagination;
20
use Knp\Component\Pager\PaginatorInterface;
21
use OldSound\RabbitMqBundle\RabbitMq\ProducerInterface;
22
use SWP\Bundle\CoreBundle\Repository\PackageRepositoryInterface;
23
use SWP\Bundle\MultiTenancyBundle\MultiTenancyEvents;
24
use SWP\Component\Bridge\Model\PackageInterface;
25
use SWP\Component\Common\Criteria\Criteria;
26
use SWP\Component\MultiTenancy\Context\TenantContextInterface;
27
use Symfony\Component\Console\Command\Command;
28
use Symfony\Component\Console\Input\InputArgument;
29
use Symfony\Component\Console\Input\InputInterface;
30
use Symfony\Component\Console\Output\OutputInterface;
31
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
32
use Symfony\Component\HttpFoundation\Request;
33
use Symfony\Component\HttpFoundation\RequestStack;
34
35
class ProcessPackagesCommand extends Command
36
{
37
    protected static $defaultName = 'swp:package:process';
38
39
    private $eventDispatcher;
40
41
    private $tenantContext;
42
43
    private $packageRepository;
44
45
    private $paginator;
46
47
    private $requestStack;
48
49
    private $contentPushProducer;
50
51
    public function __construct(
52
        EventDispatcherInterface $eventDispatcher,
53
        TenantContextInterface $tenantContext,
54
        PackageRepositoryInterface $packageRepository,
55
        PaginatorInterface $paginator,
56
        RequestStack $requestStack,
57
        ProducerInterface $contentPushProducer
58
    ) {
59
        parent::__construct();
60
61
        $this->eventDispatcher = $eventDispatcher;
62
        $this->tenantContext = $tenantContext;
63
        $this->packageRepository = $packageRepository;
64
        $this->paginator = $paginator;
65
        $this->requestStack = $requestStack;
66
        $this->contentPushProducer = $contentPushProducer;
67
    }
68
69
    protected function configure(): void
70
    {
71
        $this
72
            ->setName(self::$defaultName)
73
            ->setDescription('Finds packages by term and process them.')
74
            ->addOption('limit', null, InputArgument::OPTIONAL, 'Pagination limit', 10)
75
            ->addOption('page', null, InputArgument::OPTIONAL, 'Pagination page', 1)
76
            ->addOption('order', null, InputArgument::OPTIONAL, 'Packages order. Example: updatedAt=desc', 'updatedAt=desc')
77
            ->addOption('authors', null, InputArgument::OPTIONAL, 'Filter by authors. Example: "author1,author2"', null)
78
            ->addOption('statuses', null, InputArgument::OPTIONAL, 'Filter by package statuses. Example: "new,published,unpublished"', null)
79
            ->addOption('dry-run', null, InputArgument::OPTIONAL, 'Do not execute anything, just show what was found', false)
80
            ->setHelp(<<<'EOT'
81
The <info>swp:package:packages</info> finds packages by given term and process them.
82
83
  <info>php %command.full_name%</info>
84
85
  <info>term</info> argument is the value of the string by which to find the packages.
86
87
EOT
88
            );
89
    }
90
91
    protected function execute(InputInterface $input, OutputInterface $output): void
92
    {
93
        $this->eventDispatcher->dispatch(MultiTenancyEvents::TENANTABLE_DISABLE);
94
        $currentTenant = $this->tenantContext->getTenant();
95
        $this->requestStack->push(new Request());
96
97
        $order = [];
98
        parse_str($input->getOption('order'), $order);
99
100
        $filters = [
101
            'organization' => $currentTenant->getOrganization()->getId(),
102
        ];
103 View Code Duplication
        if (null !== $input->getOption('authors')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
104
            $filters['authors'] = \explode(',', $input->getOption('authors'));
105
        }
106 View Code Duplication
        if (null !== $input->getOption('statuses')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
107
            $filters['statuses'] = \explode(',', $input->getOption('statuses'));
108
        }
109
110
        $criteria = new Criteria($filters);
111
112
        /** @var SlidingPagination $pagination */
113
        $pagination = $this->paginator->paginate(
114
            $this->packageRepository->getQueryByCriteria($criteria, $order, 'p'),
0 ignored issues
show
Bug introduced by
It seems like $order can also be of type null; however, SWP\Component\Storage\Re...e::getQueryByCriteria() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
115
            $input->getOption('page'),
116
            $input->getOption('limit')
117
        );
118
119
        $output->writeln(sprintf('Packages found: %s', $pagination->getTotalItemCount()));
120
121
        /** @var PackageInterface $package */
122
        foreach ($pagination->getItems() as $package) {
123
            $output->writeln(sprintf('Processing package with guid: %s', $package->getGuid()));
124
            if (true === (bool) $input->getOption('dry-run')) {
125
                continue;
126
            }
127
128
            //send package to content push
129
            $payload = \serialize([
130
                'package' => $package,
131
                'tenant' => $currentTenant,
132
            ]);
133
            $this->contentPushProducer->publish($payload);
134
        }
135
    }
136
}
137