<?php
namespace App\Controller;
use App\Kernel;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\Cache\ItemInterface;
class OnlineFileController extends AbstractController
{
#[Route('/onlineFile/{url}/{action?}', name: 'onlineFile')]
public function index(Kernel $kernel,$url,$action=null): Response
{
$url = urldecode($url);
$cache = new FilesystemAdapter(directory:$kernel->getProjectDir().DIRECTORY_SEPARATOR.'var'.DIRECTORY_SEPARATOR.'onlineFileCheck');
if(strtolower($action) == 'help' || strtolower($url) == 'help')
{
return new Response('/onlineFile/[url_encode(url_encode(url))]/{help|store|compare|show}');
}
elseif(strtolower($action) == 'store')
{
$content = file_get_contents($url);
$hash = hash('sha256',$content);
$cached = new \stdClass();
$cached->url = $url;
$cached->content = $content;
$cached->hash = $hash;
$cached->stored = new \DateTime();
$cacheItem = $cache->getItem($url);
$cacheItem->set($cached);
$cache->save($cacheItem);
return new JsonResponse($cached);
}
elseif(strtolower($action) == 'compare')
{
$cached = $cache->getItem($url)->get();
if($cached !== null)
{
$old = json_decode($cached->content,true);
$new = json_decode(file_get_contents($url),true);
$diffs = array_diff($old,$new);
if(count($diffs) > 0)
$response = '<pre>'.var_export($diffs,true).'</pre>';
else
$response = 'NO DIFF';
}
else
$response = 'NO CACHE FOUND';
return new Response($response);
}
elseif(strtolower($action) == 'show')
{
$cached = $cache->getItem($url)->get();
if($cached !== null)
{
$response = 'HASH : '.$cached->hash.'<br /><br /><pre>'.json_encode(json_decode($cached->content),JSON_PRETTY_PRINT).'</pre>';
}
else
$response = 'NO CACHE FOUND';
return new Response($response);
}
else
{
$response = 'OK';
$cached = $cache->getItem($url)->get();
if($cached !== null)
{
$content = file_get_contents($url);
$hash = hash('sha256',$content);
if($cached->hash !== $hash)
{
$response = 'CHANGED';
}
}
else
$response = 'EMPTY';
return new JsonResponse($response);
}
}
}