vendredi 17 mai 2019

How do you override a class from the Laravel source code?

I need to make a change to the retrieveUser() function within Illuminate/Broadcasting/Broadcasters/Broadcaster.php.

The change works if I edit the class directly, but I have heard that you are not supposed to do that because it is difficult to track changes to the source code and because it will get overwritten when upgrading Laravel or when pushing to production.

So if I wanted to write my own modified retrieveUser() function for the Broadcaster class (it happens to be an abstract class which implements BroadcasterContract), then where and how would I do that?

Original function:

    /**
     * Retrieve the authenticated user using the configured guard (if any).
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  string  $channel
     * @return mixed
     */
    protected function retrieveUser($request, $channel)
    {
        $options = $this->retrieveChannelOptions($channel);

        $guards = $options['guards'] ?? null;

        if (is_null($guards)) {
            return $request->user();
        }

        foreach (Arr::wrap($guards) as $guard) {
            if ($user = $request->user($guard)) {
                return $user;
            }
        }
    }

New function:

protected function retrieveUser($request, $channel)
    {
        $options = $this->retrieveChannelOptions($channel);

        $guards = $options['guards'] ?? null;

        if (is_null($guards)) {
            $token = $request->header('Token');
            $id = Crypt::decrypt($token);
            $user = User::find($id);
            return $user;
        }

        foreach (Arr::wrap($guards) as $guard) {
            if ($user = $request->user($guard)) {
                return $user;
            }
        }
    }



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire