GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

CorsServiceProvider   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 11

Test Coverage

Coverage 91.67%

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 11
dl 0
loc 69
ccs 33
cts 36
cp 0.9167
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A boot() 0 9 3
A register() 0 46 3
1
<?php
2
3
namespace JDesrosiers\Silex\Provider;
4
5
use Pimple\Container;
6
use Pimple\ServiceProviderInterface;
7
use Silex\Api\BootableProviderInterface;
8
use Silex\Application;
9
use Silex\Controller;
10
use Symfony\Component\HttpFoundation\Response;
11
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
12
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
13
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
14
use Symfony\Component\HttpKernel\KernelEvents;
15
16
/**
17
 * The CORS service provider provides a `cors` service that a can be included in your project as application middleware.
18
 */
19
class CorsServiceProvider implements ServiceProviderInterface, BootableProviderInterface
20
{
21
    /**
22
     * Add OPTIONS method support for all routes
23
     *
24
     * @param Application $app
25
     */
26
    public function boot(Application $app)
27
    {
28 41
        $app->on(KernelEvents::EXCEPTION, function (GetResponseForExceptionEvent $event) {
29 5
            $e = $event->getException();
30 5
            if ($e instanceof MethodNotAllowedHttpException && $e->getHeaders()["Allow"] === "OPTIONS") {
31 1
                $event->setException(new NotFoundHttpException("No route found for \"{$event->getRequest()->getMethod()} {$event->getRequest()->getPathInfo()}\""));
32
            }
33 41
        });
34 41
    }
35
36
    /**
37
     * Register the cors function and set defaults
38
     *
39
     * @param Container $app
40
     */
41 41
    public function register(Container $app)
42
    {
43 41
        $app["cors.allowOrigin"] = "*"; // Defaults to all
44 41
        $app["cors.allowMethods"] = null; // Defaults to all
45 41
        $app["cors.allowHeaders"] = null; // Defaults to all
46 41
        $app["cors.maxAge"] = null;
47 41
        $app["cors.allowCredentials"] = null;
48 41
        $app["cors.exposeHeaders"] = null;
49
50 41
        $app["allow"] = $app->protect(new Allow());
51
52
        $app["options"] = $app->protect(function ($subject) use ($app) {
53 41
            $optionsController = function () {
54 23
                return Response::create("", 204);
55 41
            };
56
57 41
            if ($subject instanceof Controller) {
58 4
                $optionsRoute = $app->options($subject->getRoute()->getPath(), $optionsController)
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Pimple\Container as the method options() does only exist in the following sub-classes of Pimple\Container: Silex\Application, Silex\Tests\Application\FormApplication, Silex\Tests\Application\MonologApplication, Silex\Tests\Application\SecurityApplication, Silex\Tests\Application\SwiftmailerApplication, Silex\Tests\Application\TranslationApplication, Silex\Tests\Application\TwigApplication, Silex\Tests\Application\UrlGeneratorApplication, Silex\Tests\SpecialApplication. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
59 4
                    ->after($app["allow"]);
60
            } else {
61 37
                $optionsRoute = $subject->options("{path}", $optionsController)
62 37
                    ->after($app["allow"])
63 37
                    ->assert("path", ".*");
64
            }
65
66 41
            return $optionsRoute;
67 41
        });
68
69 41
        $app["cors-enabled"] = $app->protect(function ($subject, $config = []) use ($app) {
70 38
            $optionsController = $app["options"]($subject);
71 38
            $cors = new Cors($config);
72
73 38
            if ($subject instanceof Controller) {
74 4
                $optionsController->after($cors);
75
            }
76
77 38
            $subject->after($cors);
78
79 38
            return $subject;
80 41
        });
81
82
        $app["cors"] = function () use ($app) {
83
            $app["options"]($app);
84
            return new Cors();
85
        };
86
    }
87
}
88