StartWorkerCommand::configure()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 11
rs 9.4285
cc 1
eloc 9
nc 1
nop 0
1
<?php
2
3
namespace Mpclarkson\ResqueBundle\Command;
4
5
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
6
use Symfony\Component\Console\Input\InputArgument;
7
use Symfony\Component\Console\Input\InputInterface;
8
use Symfony\Component\Console\Input\InputOption;
9
use Symfony\Component\Console\Output\OutputInterface;
10
use Symfony\Component\Process\Process;
11
12
/**
13
 * Class StartWorkerCommand
14
 * @package Mpclarkson\ResqueBundle\Command
15
 */
16
class StartWorkerCommand extends ContainerAwareCommand
17
{
18
    /**
19
     *
20
     */
21
    protected function configure()
22
    {
23
        $this
24
            ->setName('resque:worker-start')
25
            ->setDescription('Start a resque worker')
26
            ->addArgument('queues', InputArgument::REQUIRED, 'Queue names (separate using comma)')
27
            ->addOption('count', 'c', InputOption::VALUE_REQUIRED, 'How many workers to fork', 1)
28
            ->addOption('interval', 'i', InputOption::VALUE_REQUIRED, 'How often to check for new jobs across the queues', 5)
29
            ->addOption('foreground', 'f', InputOption::VALUE_NONE, 'Should the worker run in foreground')
30
            ->addOption('memory-limit', 'm', InputOption::VALUE_REQUIRED, 'Force cli memory_limit (expressed in Mbytes)');
31
    }
32
33
    /**
34
     * @param InputInterface $input
35
     * @param OutputInterface $output
36
     * @return int|null|void
37
     */
38
    protected function execute(InputInterface $input, OutputInterface $output)
0 ignored issues
show
Coding Style introduced by
execute uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
39
    {
40
        $env = [];
41
42
        // here to work around issues with pcntl and cli_set_process_title in PHP > 5.5
43
        if (version_compare(PHP_VERSION, '5.5.0') >= 0) {
44
            $env = $_SERVER;
45
            unset(
46
                $env['_'],
47
                $env['PHP_SELF'],
48
                $env['SCRIPT_NAME'],
49
                $env['SCRIPT_FILENAME'],
50
                $env['PATH_TRANSLATED'],
51
                $env['argv']
52
            );
53
        }
54
55
        $env['APP_INCLUDE'] = $this->getContainer()->getParameter('resque.app_include');
56
        $env['COUNT'] = $input->getOption('count');
57
        $env['INTERVAL'] = $input->getOption('interval');
58
        $env['QUEUE'] = $input->getArgument('queues');
59
        $env['VERBOSE'] = 1;
60
61
        if (FALSE !== getenv('APP_INCLUDE')) {
62
            $env['APP_INCLUDE'] = getenv('APP_INCLUDE');
63
        }
64
65
        $prefix = $this->getContainer()->getParameter('resque.prefix');
66
        if (!empty($prefix)) {
67
            $env['PREFIX'] = $this->getContainer()->getParameter('resque.prefix');
68
        }
69
70
        if ($input->getOption('verbose')) {
71
            $env['VVERBOSE'] = 1;
72
        }
73
74
        if ($input->getOption('quiet')) {
75
            unset($env['VERBOSE']);
76
        }
77
78
        $redisHost = $this->getContainer()->getParameter('resque.redis.host');
79
        $redisPort = $this->getContainer()->getParameter('resque.redis.port');
80
        $redisDatabase = $this->getContainer()->getParameter('resque.redis.database');
81
82 View Code Duplication
        if ($redisHost != NULL && $redisPort != NULL) {
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...
83
            $env['REDIS_BACKEND'] = $redisHost . ':' . $redisPort;
84
        }
85
86
        if (isset($redisDatabase)) {
87
            $env['REDIS_BACKEND_DB'] = $redisDatabase;
88
        }
89
90
        $opt = '';
91
        if (0 !== $m = (int)$input->getOption('memory-limit')) {
92
            $opt = sprintf('-d memory_limit=%dM', $m);
93
        }
94
95 View Code Duplication
        if (version_compare(PHP_VERSION, '5.4.0') >= 0) {
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...
96
            $phpExecutable = PHP_BINARY;
97
        } else {
98
            $phpExecutable = PHP_BINDIR . '/php';
99
            if (defined('PHP_WINDOWS_VERSION_BUILD')) {
100
                $phpExecutable = 'php';
101
            }
102
        }
103
104
        $workerCommand = strtr('%php% %opt% %dir%/resque', [
105
            '%php%' => $phpExecutable,
106
            '%opt%' => $opt,
107
            '%dir%' => __DIR__ . '/../bin',
108
        ]);
109
110
        if (!$input->getOption('foreground')) {
111
            $workerCommand = strtr('nohup %cmd% > %logs_dir%/resque.log 2>&1 & echo $!', [
112
                '%cmd%'      => $workerCommand,
113
                '%logs_dir%' => $this->getContainer()->getParameter('kernel.logs_dir'),
114
            ]);
115
        }
116
117
        // In windows: When you pass an environment to CMD it replaces the old environment
118
        // That means we create a lot of problems with respect to user accounts and missing vars
119
        // this is a workaround where we add the vars to the existing environment.
120 View Code Duplication
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
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...
121
            foreach ($env as $key => $value) {
122
                putenv($key . "=" . $value);
123
            }
124
            $env = NULL;
125
        }
126
127
        $process = new Process($workerCommand, NULL, $env, NULL, NULL);
128
129
        if (!$input->getOption('quiet')) {
130
            $output->writeln(\sprintf('Starting worker <info>%s</info>', $process->getCommandLine()));
131
        }
132
133
        // if foreground, we redirect output
134
        if ($input->getOption('foreground')) {
135
            $process->run(function ($type, $buffer) use ($output) {
136
                $output->write($buffer);
137
            });
138
        } // else we recompose and display the worker id
139
        else {
140
            $process->run();
141
            $pid = \trim($process->getOutput());
142
143
            if (function_exists('gethostname')) {
144
                $hostname = gethostname();
145
            } else {
146
                $hostname = php_uname('n');
147
            }
148
149
            if (!$input->getOption('quiet')) {
150
                $output->writeln(\sprintf('<info>Worker started</info> %s:%s:%s', $hostname, $pid, $input->getArgument('queues')));
151
            }
152
        }
153
    }
154
}
155