Issues (35)

src/Components/Dispatcher.php (1 issue)

Labels
Severity
1
<?php
2
/**
3
 * Service dispatcher init
4
 * User: moyo
5
 * Date: 13/12/2017
6
 * Time: 10:48 AM
7
 */
8
9
namespace Carno\HRPC\Components;
10
11
use Carno\Console\App;
12
use Carno\Console\Component;
13
use Carno\Console\Contracts\Application;
14
use Carno\Console\Contracts\Bootable;
15
use Carno\Container\DI;
16
use Carno\Promise\Promise;
17
use Carno\RPC\Service\Dispatcher as RDispatcher;
18
use Carno\RPC\Service\Scanner;
0 ignored issues
show
This use statement conflicts with another class in this namespace, Carno\HRPC\Components\Scanner. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
19
use Throwable;
20
21
class Dispatcher extends Component implements Bootable
22
{
23
    /**
24
     * @var array
25
     */
26
    protected $dependencies = [Scanner::class];
27
28
    /**
29
     * @param Application|App $app
30
     */
31
    public function starting(Application $app) : void
32
    {
33
        /**
34
         * @var RDispatcher $dispatcher
35
         */
36
37
        $dispatcher = DI::set(RDispatcher::class, DI::object(RDispatcher::class));
38
39
        $started = $app->starting()->done();
40
        $shutdown = Promise::deferred();
41
42
        $app->starting()->add(static function () use ($dispatcher, $started, $shutdown) {
43
            $dispatcher->preparing($started, $shutdown)->catch(function (Throwable $e) {
44
                logger('hrpc')->error(
45
                    'Service startup failed when initialize',
46
                    ['ec' => get_class($e), 'em' => $e->getMessage()]
47
                );
48
            });
49
        });
50
51
        $app->stopping()->add(static function () use ($shutdown) {
52
            $shutdown->resolve();
53
        });
54
    }
55
}
56