/**
  * Gets a script url from sourcepoint and caches it for a day.
  *
  * @return array
  */
 protected function getAsScript()
 {
     $apiUrl = trim($this->getTemplateVariable('api_url'));
     $apiKey = trim($this->getTemplateVariable('api_key'));
     $failedValue = '<!--sourcepoint-failed-->';
     $cacheKey = 'wblib:sourcepoint:script';
     if (empty($apiUrl) || empty($apiKey)) {
         return ['data' => ['script' => $failedValue]];
     }
     $cachedScript = $this->cacheStore->get($cacheKey);
     if (false !== $cachedScript) {
         return ['data' => ['script' => $cachedScript]];
     }
     $scriptEndpoint = sprintf('%sscript?delivery=script', $apiUrl);
     $script = null;
     try {
         $curl = curl_init();
         curl_setopt($curl, CURLOPT_URL, $scriptEndpoint);
         curl_setopt($curl, CURLOPT_HTTPHEADER, [sprintf('Authorization: Token %s', $apiKey)]);
         curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 1);
         curl_setopt($curl, CURLOPT_TIMEOUT, 1);
         $script = trim(curl_exec($curl));
         curl_close($curl);
         // validate script tag
         // e.g.: "<script async="async" data-client-id="RXcVfPPwlbdGjwq" type="text/javascript" src="//d3ujids68p6xmq.cloudfront.net/abw.js"></script>"
         if (preg_match('/^<script/i', $script)) {
             $this->cacheStore->put($cacheKey, $script, $this->cacheTtl);
         } else {
             $this->Logger->error(sprintf('Expected a script tag but got: %s', $script));
             $script = $failedValue;
             $this->cacheStore->put($cacheKey, $failedValue, $this->failedCacheTtl);
         }
     } catch (\Exception $e) {
         $this->Logger->error(sprintf('CURL to [%s] failed with: %s', $scriptEndpoint, $e->getMessage()));
         $this->cacheStore->put($cacheKey, $failedValue, $this->failedCacheTtl);
     }
     return ['data' => ['script' => $script]];
 }
 /**
  * Creates lock for the given slug.  Lock will only last for 10 seconds.
  *
  * @param string $slug
  * @throws \Exception
  */
 protected function getLock($slug)
 {
     $i = 0;
     do {
         if ($existingLock = $this->cacheStore->get($this->getLockKey($slug))) {
             usleep(200000);
             // 200 milliseconds
             $i += 0.2;
         }
     } while ($existingLock && $i < 5);
     if ($existingLock) {
         throw new \Exception(sprintf('Failed to acquire lock for slug "%s", currently locked by "%s".', $slug, $existingLock));
     }
     $this->cacheStore->put($this->getLockKey($slug), $this->getUser()->Slug, 10);
 }