Completed
Push — master ( b2f402...60b6a2 )
by Sergi Tur
03:31
created

Serve::check_port()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 11
rs 9.4285
cc 2
eloc 7
nc 2
nop 3
1
<?php
2
3
namespace Acacha\Llum\Traits;
4
5
use Symfony\Component\Console\Output\OutputInterface;
6
7
/**
8
 * Class Serve.
9
 * @property OutputInterface $output
10
 */
11
trait Serve
12
{
13
    /**
14
     * Serve command.
15
     *
16
     * @param int $port
17
     */
18
    protected function serve($port = 8000)
19
    {
20
        $continue = true;
21
        do {
22
            if ($this->check_port($port)) {
23
                $this->output->writeln('<info>Running php artisan serve --port='.$port.'</info>');
24
                exec('php artisan serve --port='.$port.' > /dev/null 2>&1 &');
25
                sleep(1);
26
                if (file_exists('/usr/bin/sensible-browser')) {
27
                    $this->output->writeln('<info>Opening http://localhost:'.$port.' with default browser</info>');
28
                    passthru('/usr/bin/sensible-browser http://localhost:'.$port);
29
                }
30
                $continue = false;
31
            }
32
            ++$port;
33
        } while ($continue);
34
    }
35
36
    /**
37
     * Check if port is in use.
38
     *
39
     * @param int    $port
40
     * @param string $host
41
     * @param int    $timeout
42
     *
43
     * @return bool
44
     */
45
    protected function check_port($port = 8000, $host = '127.0.0.1', $timeout = 3)
46
    {
47
        $fp = @fsockopen($host, $port, $errno, $errstr, $timeout);
48
        if (! $fp) {
49
            return true;
50
        } else {
51
            fclose($fp);
52
53
            return false;
54
        }
55
    }
56
}
57