<?php
namespace App\Twig\Extension;
use Pimcore\Model\Document;
use Pimcore\Twig\Extension\Templating\Navigation;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
use GeoIp2\Database\Reader;
class NavigationExtension extends AbstractExtension
{
/**
* @var Navigation
*/
protected $navigationHelper;
/**
* @param Navigation $navigationHelper
*/
public function __construct(Navigation $navigationHelper)
{
$this->navigationHelper = $navigationHelper;
}
/**
* @return array|TwigFunction[]
*/
public function getFunctions()
{
return [
new TwigFunction('app_navigation_data_links', [$this, 'getDataLinks']),
new TwigFunction('country_ip', [$this, 'getCountryIp'])
];
}
/**
* @param Document $document
* @param Document $startNode
*
* @return \Pimcore\Navigation\Container
* @throws \Exception
*/
public function getDataLinks(Document $document, Document $startNode)
{
$navigation = $this->navigationHelper->build([
'active' => $document,
'root' => $startNode,
'pageCallback' => function($page, $document) {
/** @var \Pimcore\Model\Document $document */
/** @var \Pimcore\Navigation\Page\Document $page */
if($document->getProperty("data_object")) {
$children=$document->getProperty("data_object")->getChildren();
//sorting the objects
usort($children,function ($a, $b) {
$orderA = $a->get("order");
$orderB = $b->get("order");
if ($orderA === $orderB) {
return 0;
}
return ($orderA < $orderB) ? -1 : 1;
});
foreach($children as $object) {
$uri = new \Pimcore\Navigation\Page\Document([
"label" => $object->getName(),
"id" => "object-" . $object->getId(),
"uri" =>'/'.$document->getKey().'/'.$object->getUrl(),
]);
$page->addPage($uri);
}
}
}
]);
return $navigation;
}
/**
* @param array $values
* @return array
*/
public function getCountryIp()
{
try {
$ipaddress = '';
$ip = '';
if (isset($_SERVER['HTTP_CLIENT_IP'])){
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
}else if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
}else if(isset($_SERVER['HTTP_X_FORWARDED'])){
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
}else if(isset($_SERVER['HTTP_FORWARDED_FOR'])){
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
}else if(isset($_SERVER['HTTP_FORWARDED'])){
$ipaddress = $_SERVER['HTTP_FORWARDED'];
}else if(isset($_SERVER['REMOTE_ADDR'])){
$ipaddress = $_SERVER['REMOTE_ADDR'];
}else{
$ipaddress = 'UNKNOWN';
}
if($ipaddress != 'UNKNOWN' && $ipaddress != '127.0.0.1') {
$ip_info = new Reader(__DIR__.'/GeoLite2-Country.mmdb');
$record = $ip_info->country($ipaddress);
if($record) {
$ip = $record->country->isoCode;
}
}else{
$ip = "AE";
}
} catch (Exception $e) {
$ip = '';
}
return $ip;
}
}
?>