HEX
Server: Microsoft-IIS/8.5
System: Windows NT YDAWBH120 6.3 build 9600 (Windows Server 2012 R2 Standard Edition) AMD64
User: tentjecom_web (0)
PHP: 7.4.14
Disabled: NONE
Upload Files
File: D:/HostingSpaces/ASmits/kemi.nl/app/Http/Middleware/SitesResolver.php
<?php


namespace App\Http\Middleware;


use App\KommaApp\Sites\Models\Site;
use Illuminate\Support\Facades\URL;

class SitesResolver
{

    /**
     * Set site on Application
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, \Closure $next)
    {

        //Skip this when it is an Kms route
        if($request->segment(1) == 'kms') return $next($request);

        if(!\Config::get('app.multipleSites')){

            \App::setSite(Site::find(1));
            // If there is only one site, the redirect should be handled by the web.config
        }
        else{

            $root = $request->root();
            $path = $request->path();

            //TODO make redirect rules for https/http and with/without wwww
            // This statement is set to redirect to https://example.com
//            if((starts_with($root, 'http:://') || starts_with($root, 'https://www.')) && \App::environment() == 'production' ){
//
//            }

//                $root = str_replace($root, 'http://www.');

            $siteDomains = \Config::get('site.domains');
            $activeSiteSlug = '';

            foreach ($siteDomains as $siteKey => $domains){
                foreach ($domains as $domain){
                    if(str_contains($root, $domain)){
                        if($activeSiteSlug == '') $activeSiteSlug = $siteKey;
                        else throw new \InvalidArgumentException("Domain isn't specific enough because active site key is overruled by other site, best practice is to define domains with there top-level domain in the site config");
                    }
                }
            }

            // Find the site by the active site slug
            $site = Site::where('slug', $activeSiteSlug)->first();
            \App::setSite( $site );

            // Check if defined language is one of the languages of this site
            // if not throw error, because it shouldn't happen...
            if(!$site->languages->contains(\App::getLanguage())){
                throw new \InvalidArgumentException("Defined app language doesn't exist in this site, so check how this could happen.");
            }
        }

        //Return the Request, and check the other routes
        return $next($request);

    }

}