PHP code example of xorgxx / neox-geolocator-bundle

1. Go to this page and download the library: Download xorgxx/neox-geolocator-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

xorgxx / neox-geolocator-bundle example snippets


Bundles.php


return [
    .....
    NeoxGeolocator\NeoxGeolocatorBundle\NeoxGeolocatorBundle::class => ['all' => true],
    .....
];

    /**
     * @Route("/unauthorized", name="Seo_unauthorized")
     * @param Request $request
     * @return Response
     */
     
    #[NeoxGeoBag( forcer: true, filterLocal: ["RU", "GB"], filterContinents: ["Asia"])]   
    public function unauthorized(Request $request, CacheItemPoolInterface  $adapter): Response
    {
        $session    = $request->getSession();
        $Geolocator = $adapter->getItem(geolocatorAbstract::NAME . $session->getId());
        $metadata   = $Geolocator->getMetadata();
        
        if ( $Geolocator && $Geolocator->isHit() && array_key_exists('expiry', $metadata)) {
            $expirationTimestamp    = $metadata['expiry'];
            $expirationDateTime     = $date = new DateTime("@$expirationTimestamp");
        };
        
        $i = $Geolocator->get("value");
        return $this->render('unauthorized.html.twig', [
            "Geolocator"        => $Geolocator->get("value"),
            "timer"             => $expirationDateTime ?? null,
        ]);
    }

    .....
    
    {% block javascripts  %}
        <script>
         // Wait 0.5 seconds (500 milliseconds) then redirect
            setTimeout(function() {
                window.location.href = "/";
            }, 500);
        </script>
   
    {% endblock %}


    namespace App\Services;
    
    use NeoxGeolocator\NeoxGeolocatorBundle\Entity\Geolocation;
    use NeoxGeolocator\NeoxGeolocatorBundle\Pattern\geolocatorAbstract;
    use NeoxGeolocator\NeoxGeolocatorBundle\Pattern\GeolocatorInterface;
    use Psr\Cache\InvalidArgumentException;
    use Symfony\Component\Cache\Adapter\FilesystemAdapter;
    use Symfony\Component\Cache\CacheItem;
    use Symfony\Contracts\Cache\ItemInterface;
    use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
    use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
    use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
    use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
    
    class ipApiService extends geolocatorAbstract implements GeolocatorInterface
    {
        public function Geolocator(): Geolocation
        {
            
            // get geolocation
            $this->Geolocation = $this->getInfoCdn();
            
            // set filter Local
            $this->setFilterLocal();
            
            // set filter contement
            $this->setFilterContinents();
            
            // set filter Connection
            $this->setFilterConnection();
            
            // set crawler
            $this->setFilterCrawler();
            
//            $this->requestStack->getSession()->set('geolocator', $this->Geolocation);
            
            return $this->Geolocation;
            
            // TODO: Implement Geolocator() method.
        }
        
        public function getInfoCdn(): Geolocation{
            
            // check ip
            // $currentIp = $ipCheck ?: $this->httpClient->request('GET', $this->CDN["ip"] )->getContent();
            // $currentIp      = $this->requestStack->getCurrentRequest()->getClientIp();
            $data   = "";
            if ( $this->getLimiter('ipapi') ) {
                $currentIp      = $this->getRealIp();
                $api            = "http://" . $this->neoxBag->getCdn()["api_use"] . "/json/$currentIp?fields=status,message,continent,continentCode,country,countryCode,regionName,city,zip,lat,lon,reverse,mobile,proxy,hosting,query";
                // todo: check if this expires !!!
                $response_      = $this->httpClient->request('GET', $api );
                $data           = $response_->getContent();
                
                # for adaptation data 2 options
                # FIRST OPTION
                return Geolocation::fromJson($data); 
                
                # SECOND OPTION
                $geolocation   = new Geolocation();
                    $geolocationModel->setstatus('success')               // = ;
                    ->setcontinent($o["continent"]["names"]["fr"])          // = 'Europe';
                    ->setcontinentCode($o["continent"]["code"])             // = 'EU';
                    ->setcountry($o["country"]["names"]["en"])              // = 'France';
                    ->setcountryCode($o["country"]["iso_code"])             // = 'FR';
                    ->setregionName($o["subdivisions"][0]["names"]["en"])   // = 'Paris';
                    ->setcity($o["city"]["names"]["en"])                    // = 'Paris';
                    ->setzip($o["postal"]["code"])                          // = '75000';
                    ->setlat($o["location"]["latitude"])                    // = 40.6951;
                    ->setlon($o["location"]["longitude"])                   // = 20.325;
                    ->setreverse($o["traits"]["isp"])                       // = 'unn-156-146-55-226.cdn';
                    ->setmobile('nc')                                 // = false;
                    ->setproxy(($o["traits"]["connection_type"] == 'Corporate' ? true : false))     // = false;
                    ->sethosting(($o["traits"]["user_type"] == 'hosting' ? true : false))           // = false;
                    ->setquery($currentIp)           // = '156.146.55.226';
                    ->setvalid(true)            // = true;
                ;
            
              return $geolocation;
            }else{
                /** @var geolocatorAbstract $class */
                $class = $this->buildClass("findIpService");
                return  $class->Geolocator();
            }
        }
    }



    
    namespace App\EventSubscriber;
    
    use NeoxGeolocator\NeoxGeolocatorBundle\Event\NeoxGeolocatorEvents;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class NeoxGeolocatorSubscriber implements EventSubscriberInterface
    {
        
        /**
         * @inheritDoc
         */
        public static function getSubscribedEvents(): array
        {
            return [
                NeoxGeolocatorEvents::NEOX_GEOLOCATOR_EVENT => 'onCustomEvent',
                NeoxGeolocatorEvents::NEOX_GEOLOCATOR_PASS  => 'onCustomEvent',
                NeoxGeolocatorEvents::NEOX_GEOLOCATOR_FAIL  => 'onCustomEvent',
            ];
        }
        
        public function onCustomEvent(NeoxGeolocatorEvents $event): void
        {
            // Faire quelque chose avec l'événement
            $neoxGeolocation = $event->getGeolocation();
            ......
        }
    }