Last active
December 23, 2016 16:23
-
-
Save alexander-schranz/c02a8ad30f74681cfd8903b83eaf2d45 to your computer and use it in GitHub Desktop.
Cross CacheController.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace AppBundle\Controller; | |
| use Guzzle\Http\Client; | |
| use Sulu\Bundle\WebsiteBundle\Controller\CacheController as SuluCacheController; | |
| use Symfony\Component\HttpFoundation\JsonResponse; | |
| use Symfony\Component\HttpFoundation\Request; | |
| use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; | |
| class CacheController extends SuluCacheController | |
| { | |
| /** | |
| * {@inheritdoc} | |
| */ | |
| public function clearAction(Request $request = null) | |
| { | |
| $response = parent::clearAction(); | |
| $otherIp = $this->getOtherServer(); | |
| if ($request && $otherIp && $request->getClientIp() != $otherIp) { | |
| $this->callOtherServer($request); | |
| } | |
| return $response; | |
| } | |
| /** | |
| * {@inheritdoc} | |
| */ | |
| public function clearWebsiteAction(Request $request) | |
| { | |
| if (in_array( | |
| $request->getClientIp(), | |
| [ | |
| $this->getOtherServer(), | |
| '127.0.0.1' | |
| ] | |
| )) { | |
| $response = parent::clearAction(); | |
| return $response; | |
| } else { | |
| throw new AccessDeniedHttpException(sprintf('Cache clear is not allowed with IP: %s', $request->getClientIp())); | |
| } | |
| } | |
| /** | |
| * @param Request $request | |
| * | |
| * @return bool | |
| */ | |
| protected function callOtherServer(Request $request) | |
| { | |
| $domain = $this->getOtherServer('domain'); | |
| if (!$domain) { | |
| return null; | |
| } | |
| $url = $request->getScheme() . '://' . $domain . '/_cache/clear'; | |
| $client = new Client($url); | |
| $request = $client->createRequest(); | |
| $request->send(); | |
| return true; | |
| } | |
| /** | |
| * @return mixed|null | |
| */ | |
| protected function getOtherServer($key = 'ip') | |
| { | |
| if (!$this->container->hasParameter('other_server_' . $key)) { | |
| return null; | |
| } | |
| $otherServerIp = $this->container->getParameter('other_server_' . $key); | |
| if (!$otherServerIp) { | |
| return null; | |
| } | |
| return $otherServerIp; | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment