Completed
Push — master ( b97427...e235cc )
by Raffael
30:35 queued 26:08
created

Helper::streamContent()   D

Complexity

Conditions 18
Paths 4

Size

Total Lines 84

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 342

Importance

Changes 0
Metric Value
dl 0
loc 84
ccs 0
cts 67
cp 0
rs 4.8666
c 0
b 0
f 0
cc 18
nc 4
nop 3
crap 342

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * balloon
7
 *
8
 * @copyright   Copryright (c) 2012-2019 gyselroth GmbH (https://gyselroth.com)
9
 * @license     GPL-3.0 https://opensource.org/licenses/GPL-3.0
10
 */
11
12
namespace Balloon\App\Api;
13
14
use Balloon\Filesystem\Exception;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Balloon\App\Api\Exception.

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...
15
use Balloon\Filesystem\Node\File;
16
use Micro\Http\Response;
17
18
class Helper
19
{
20
    /**
21
     * Stream content.
22
     */
23
    public static function streamContent(Response $response, File $file, bool $download = false): ?Response
24
    {
25
        if (true === $download) {
26
            $response->setHeader('Content-Disposition', 'attachment; filename*=UTF-8\'\''.rawurlencode($file->getName()));
0 ignored issues
show
Bug introduced by
Consider using $file->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
27
            $response->setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
28
            $response->setHeader('Content-Type', 'application/octet-stream');
29
            $response->setHeader('Content-Length', (string) $file->getSize());
30
            $response->setHeader('Content-Transfer-Encoding', 'binary');
31
        } else {
32
            $response->setHeader('Content-Disposition', 'inline; filename*=UTF-8\'\''.rawurlencode($file->getName()));
0 ignored issues
show
Bug introduced by
Consider using $file->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
33
            $response->setHeader('Content-Type', $file->getContentType());
34
        }
35
36
        $response->setHeader('ETag', $file->getETag());
37
38
        if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && ($file->getETag() === $_SERVER['HTTP_IF_NONE_MATCH'] || $_SERVER['HTTP_IF_NONE_MATCH'] === '"*"')) {
39
            return $response->setCode(304);
40
        }
41
42
        return $response
43
          ->setOutputFormat(null)
44
          ->setBody(function () use ($file) {
45
              $stream = $file->get();
46
              $name = $file->getName();
0 ignored issues
show
Unused Code introduced by
$name is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
Bug introduced by
Consider using $file->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
47
48
              if (null === $stream) {
49
                  return;
50
              }
51
52
              $size = $file->getSize();
53
              $length = $size;
54
              $start = 0;
55
              $end = $size - 1;
56
57
              if (isset($_SERVER['HTTP_RANGE'])) {
58
                  header('Accept-Ranges: bytes');
59
                  $c_start = $start;
0 ignored issues
show
Unused Code introduced by
$c_start is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
60
                  $c_end = $end;
61
                  list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
62
63
                  if (strpos($range, ',') !== false) {
64
                      header("Content-Range: bytes $start-$end/$size");
65
66
                      throw new Exception\InvalidRange('invalid offset/limit requested');
67
                  }
68
69
                  if ($range == '-') {
70
                      $c_start = $size - substr($range, 1);
71
                  } else {
72
                      $range = explode('-', $range);
73
                      $c_start = $range[0];
74
                      $c_end = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
75
                  }
76
77
                  $c_end = ($c_end > $end) ? $end : $c_end;
78
                  if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
79
                      header("Content-Range: bytes $start-$end/$size");
80
81
                      throw new Exception\InvalidRange('invalid offset/limit requested');
82
                  }
83
84
                  $start = (int) $c_start;
85
                  $end = (int) $c_end;
86
                  $length = (int) $end - $start + 1;
87
                  fseek($stream, $start);
88
                  header('HTTP/1.1 206 Partial Content');
89
                  header("Content-Range: bytes $start-$end/$size");
90
              }
91
92
              header('Content-Length: '.$length);
93
              $buffer = 1024 * 8;
94
95
              while (!feof($stream) && ($p = ftell($stream)) <= $end) {
96
                  if ($p + $buffer > $end) {
97
                      $buffer = $end - $p + 1;
98
                  }
99
100
                  echo fread($stream, $buffer);
101
                  flush();
102
              }
103
104
              fclose($stream);
105
          });
106
    }
107
}
108