Completed
Pull Request — master (#690)
by
unknown
01:35
created

Utils::printPhpValue()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
cc 3
nc 3
nop 2
1
<?php
2
3
namespace Mpociot\ApiDoc\Tools;
4
5
use Illuminate\Routing\Route;
6
use League\Flysystem\Adapter\Local;
7
use League\Flysystem\Filesystem;
8
use Symfony\Component\Console\Output\ConsoleOutput;
9
use Symfony\Component\Console\Output\OutputInterface;
10
use Symfony\Component\VarExporter\VarExporter;
11
12
class Utils
13
{
14
    public static function getFullUrl(Route $route, array $urlParameters = []): string
15
    {
16
        $uri = $route->uri();
17
18
        return self::replaceUrlParameterPlaceholdersWithValues($uri, $urlParameters);
19
    }
20
21
    /**
22
     * @param array|Route $routeOrAction
23
     *
24
     * @return array|null
25
     */
26
    public static function getRouteClassAndMethodNames($routeOrAction)
27
    {
28
        $action = $routeOrAction instanceof Route
0 ignored issues
show
Bug introduced by
The class Illuminate\Routing\Route does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
29
            ? $routeOrAction->getAction()
30
            : $routeOrAction;
31
32
        $uses = $action['uses'];
33
34
        if ($uses !== null) {
35
            if (is_array($uses)) {
36
                return $uses;
37
            } elseif (is_string($uses)) {
38
                return explode('@', $uses);
39
            } elseif (static::isInvokableObject($uses)) {
40
                return [$uses, '__invoke'];
41
            }
42
        }
43
        if (array_key_exists(0, $action) && array_key_exists(1, $action)) {
44
            return [
45
                0 => $action[0],
46
                1 => $action[1],
47
            ];
48
        }
49
    }
50
51
    /**
52
     * Transform parameters in URLs into real values (/users/{user} -> /users/2).
53
     * Uses @urlParam values specified by caller, otherwise just uses '1'.
54
     *
55
     * @param string $uri
56
     * @param array $urlParameters Dictionary of url params and example values
57
     *
58
     * @return mixed
59
     */
60
    public static function replaceUrlParameterPlaceholdersWithValues(string $uri, array $urlParameters)
61
    {
62
        $matches = preg_match_all('/{.+?}/i', $uri, $parameterPaths);
63
        if (! $matches) {
64
            return $uri;
65
        }
66
67
        foreach ($parameterPaths[0] as $parameterPath) {
68
            $key = trim($parameterPath, '{?}');
69
            if (isset($urlParameters[$key])) {
70
                $example = $urlParameters[$key];
71
                $uri = str_replace($parameterPath, $example, $uri);
72
            }
73
        }
74
        // Remove unbound optional parameters with nothing
75
        $uri = preg_replace('#{([^/]+\?)}#', '', $uri);
76
        // Replace any unbound non-optional parameters with '1'
77
        $uri = preg_replace('#{([^/]+)}#', '1', $uri);
78
79
        return $uri;
80
    }
81
82
    public static function dumpException(\Exception $e)
83
    {
84
        if (class_exists(\NunoMaduro\Collision\Handler::class)) {
85
            $output = new ConsoleOutput(OutputInterface::VERBOSITY_VERBOSE);
86
            $handler = new \NunoMaduro\Collision\Handler(new \NunoMaduro\Collision\Writer($output));
87
            $handler->setInspector(new \Whoops\Exception\Inspector($e));
88
            $handler->setException($e);
89
            $handler->handle();
90
        } else {
91
            dump($e);
92
            echo "You can get better exception output by installing the library \nunomaduro/collision (PHP 7.1+ only).\n";
93
        }
94
    }
95
96
    public static function deleteDirectoryAndContents($dir)
97
    {
98
        $adapter = new Local(realpath(__DIR__.'/../../'));
99
        $fs = new Filesystem($adapter);
100
        $fs->deleteDir($dir);
101
    }
102
103
    /**
104
     * @param mixed $value
105
     * @param int $indentationLevel
106
     *
107
     * @throws \Symfony\Component\VarExporter\Exception\ExceptionInterface
108
     *
109
     * @return string
110
     */
111
    public static function printPhpValue($value, $indentationLevel = 0)
112
    {
113
        $output = VarExporter::export($value);
114
        // Padding with x spaces so they align
115
        $split = explode("\n", $output);
116
        $result = '';
117
        $padWith = str_repeat(' ', $indentationLevel);
118
        foreach ($split as $index => $line) {
119
            $result .= ($index == 0 ? '' : "\n$padWith").$line;
120
        }
121
122
        return $result;
123
    }
124
125
    /**
126
     * @param mixed $value
127
     *
128
     * @return bool
129
     */
130
    public static function isInvokableObject($value): bool
131
    {
132
        return is_object($value) && method_exists($value, '__invoke');
133
    }
134
}
135