Completed
Push — master ( 143878...f45699 )
by Taosikai
14:33
created

NonBlockStreamHandler   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
dl 0
loc 29
rs 10
c 0
b 0
f 0
wmc 3
lcom 1
cbo 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A streamWrite() 0 12 2
1
<?php
2
3
/*
4
 * This file is part of the slince/spike package.
5
 *
6
 * (c) Slince <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Spike\Common\Logger;
13
14
use Monolog\Handler\StreamHandler;
15
use Monolog\Logger;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Spike\Common\Logger\Logger.

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...
16
use React\EventLoop\LoopInterface;
17
18
class NonBlockStreamHandler extends StreamHandler
19
{
20
    /**
21
     * @var LoopInterface
22
     */
23
    protected $eventLoop;
24
25
    public function __construct(LoopInterface $eventLoop, $stream, $level = Logger::DEBUG, $bubble = true, $filePermission = null, $useLocking = false)
26
    {
27
        $this->eventLoop = $eventLoop;
28
        parent::__construct($stream, $level, $bubble, $filePermission, $useLocking);
29
    }
30
31
    /**
32
     * {@inheritdoc}
33
     */
34
    protected function streamWrite($stream, array $record)
35
    {
36
        $data = (string) $record['formatted'];
37
        $this->eventLoop->addWriteStream($stream, function ($stream) use(&$data){
38
            $written = fwrite($stream, $data);
39
            if ($written === strlen($data)) {
40
                $this->eventLoop->removeWriteStream($stream);
41
            } else {
42
                $data = substr($data, $written);
43
            }
44
        });
45
    }
46
}