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

Utils::isInvokableObject()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
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
use ReflectionClass;
12
use ReflectionException;
13
use ReflectionFunction;
14
use ReflectionFunctionAbstract;
15
16
class Utils
17
{
18
    public static function getFullUrl(Route $route, array $urlParameters = []): string
19
    {
20
        $uri = $route->uri();
21
22
        return self::replaceUrlParameterPlaceholdersWithValues($uri, $urlParameters);
23
    }
24
25
    /**
26
     * @param array|Route $routeOrAction
27
     *
28
     * @return array|null
29
     */
30
    public static function getRouteClassAndMethodNames($routeOrAction)
31
    {
32
        $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...
33
            ? $routeOrAction->getAction()
34
            : $routeOrAction;
35
36
        $uses = $action['uses'];
37
38
        if ($uses !== null) {
39
            if (is_array($uses)) {
40
                return $uses;
41
            } elseif (is_string($uses)) {
42
                return explode('@', $uses);
43
            } elseif (static::isInvokableObject($uses)) {
44
                return [$uses, '__invoke'];
45
            }
46
        }
47
        if (array_key_exists(0, $action) && array_key_exists(1, $action)) {
48
            return [
49
                0 => $action[0],
50
                1 => $action[1],
51
            ];
52
        }
53
    }
54
55
    /**
56
     * Transform parameters in URLs into real values (/users/{user} -> /users/2).
57
     * Uses @urlParam values specified by caller, otherwise just uses '1'.
58
     *
59
     * @param string $uri
60
     * @param array $urlParameters Dictionary of url params and example values
61
     *
62
     * @return mixed
63
     */
64
    public static function replaceUrlParameterPlaceholdersWithValues(string $uri, array $urlParameters)
65
    {
66
        $matches = preg_match_all('/{.+?}/i', $uri, $parameterPaths);
67
        if (! $matches) {
68
            return $uri;
69
        }
70
71
        foreach ($parameterPaths[0] as $parameterPath) {
72
            $key = trim($parameterPath, '{?}');
73
            if (isset($urlParameters[$key])) {
74
                $example = $urlParameters[$key];
75
                $uri = str_replace($parameterPath, $example, $uri);
76
            }
77
        }
78
        // Remove unbound optional parameters with nothing
79
        $uri = preg_replace('#{([^/]+\?)}#', '', $uri);
80
        // Replace any unbound non-optional parameters with '1'
81
        $uri = preg_replace('#{([^/]+)}#', '1', $uri);
82
83
        return $uri;
84
    }
85
86
    public static function dumpException(\Exception $e)
87
    {
88
        if (class_exists(\NunoMaduro\Collision\Handler::class)) {
89
            $output = new ConsoleOutput(OutputInterface::VERBOSITY_VERBOSE);
90
            $handler = new \NunoMaduro\Collision\Handler(new \NunoMaduro\Collision\Writer($output));
91
            $handler->setInspector(new \Whoops\Exception\Inspector($e));
92
            $handler->setException($e);
93
            $handler->handle();
94
        } else {
95
            dump($e);
96
            echo "You can get better exception output by installing the library \nunomaduro/collision (PHP 7.1+ only).\n";
97
        }
98
    }
99
100
    public static function deleteDirectoryAndContents($dir)
101
    {
102
        $adapter = new Local(realpath(__DIR__.'/../../'));
103
        $fs = new Filesystem($adapter);
104
        $fs->deleteDir($dir);
105
    }
106
107
    /**
108
     * @param mixed $value
109
     * @param int $indentationLevel
110
     *
111
     * @throws \Symfony\Component\VarExporter\Exception\ExceptionInterface
112
     *
113
     * @return string
114
     */
115
    public static function printPhpValue($value, $indentationLevel = 0)
116
    {
117
        $output = VarExporter::export($value);
118
        // Padding with x spaces so they align
119
        $split = explode("\n", $output);
120
        $result = '';
121
        $padWith = str_repeat(' ', $indentationLevel);
122
        foreach ($split as $index => $line) {
123
            $result .= ($index == 0 ? '' : "\n$padWith").$line;
124
        }
125
126
        return $result;
127
    }
128
129
    /**
130
     * @param mixed $value
131
     *
132
     * @return bool
133
     */
134
    public static function isInvokableObject($value): bool
135
    {
136
        return is_object($value) && method_exists($value, '__invoke');
137
    }
138
139
    /**
140
     * @param array $routeControllerAndMethod
141
     *
142
     * @throws ReflectionException
143
     *
144
     * @return ReflectionFunctionAbstract
145
     */
146
    public static function reflectRouteMethod(array $routeControllerAndMethod): ReflectionFunctionAbstract
147
    {
148
        [$class, $method] = $routeControllerAndMethod;
0 ignored issues
show
Bug introduced by
The variable $class does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $method does not exist. Did you mean $routeControllerAndMethod?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
149
150
        if ($class instanceof \Closure) {
151
            return new ReflectionFunction($class);
152
        }
153
154
        return (new ReflectionClass($class))->getMethod($method);
0 ignored issues
show
Bug introduced by
The variable $method does not exist. Did you mean $routeControllerAndMethod?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
155
    }
156
}
157