Skip to content

Commit

Permalink
added remoteimagecache and curl
Browse files Browse the repository at this point in the history
  • Loading branch information
koertho committed Feb 20, 2018
1 parent 96419aa commit 370ead4
Show file tree
Hide file tree
Showing 7 changed files with 374 additions and 80 deletions.
52 changes: 37 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,28 +17,50 @@ composer require heimrichhannot/contao-utils-bundle

## Utils

### Cache

#### Remote image cache `huh.utils.cache.remote_image_cache`

Method | Description
-----------|------------
get | Get a remote file from cache and cache file, if not already in cache.

### Curl `huh.utils.curl`

Method | Description
---------------------------|------------
recursivelyGetRequest |
request |
recursivelyPostRequest |
postRequest |
createCurlObject |
setHeaders |
splitResponseHeaderAndBody |
prepareHeaderArrayForPrint |


### DCA `huh.utils.dca`

Method | Description
----------------------|------------
Method | Description
-------------------------------------|------------
getConfigByArrayOrCallbackOrFunction |
setDateAdded |
setDateAddedOnCopy |
getFields |
addOverridableFields |
getOverridableProperty |
flattenPaletteForSubEntities |
generateAlias | Generate a unique alias or check if given alias is unique
setDateAdded |
setDateAddedOnCopy |
getFields |
addOverridableFields |
getOverridableProperty |
flattenPaletteForSubEntities |
generateAlias | Generate a unique alias or check if given alias is unique

### Models `huh.utils.model`

Method | Description
----------------------|------------
findModelInstanceByPk | Returns a model instance if for a given table and id or null if not exist.
findModelInstancesBy | Returns model instances by given table and search criteria.
findOneModelInstanceBy | Return a single model instance by table and search criteria.
Method | Description
--------------------------|------------
findModelInstanceByPk | Returns a model instance if for a given table and id or null if not exist.
findModelInstancesBy | Returns model instances by given table and search criteria.
findOneModelInstanceBy | Return a single model instance by table and search criteria.
findRootParentRecursively | Recursively finds the root parent.
findParentsRecursively |Returns an array of a model instance's parents in ascending order, i.e. the root parent comes first.
findParentsRecursively |Returns an array of a model instance's parents in ascending order, i.e. the root parent comes first.

### Routing `huh.utils.routing`

Expand Down
68 changes: 68 additions & 0 deletions src/Cache/RemoteImageCache.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php

/*
* Copyright (c) 2018 Heimrich & Hannot GmbH
*
* @license LGPL-3.0-or-later
*/

namespace HeimrichHannot\UtilsBundle\Cache;

use Contao\CoreBundle\Framework\ContaoFrameworkInterface;
use Contao\File;
use Contao\Validator;
use HeimrichHannot\Haste\Util\Curl;
use Symfony\Component\DependencyInjection\ContainerInterface;

class RemoteImageCache
{
/** @var ContaoFrameworkInterface */
protected $framework;
/**
* @var ContainerInterface
*/
private $container;

public function __construct(ContaoFrameworkInterface $framework, ContainerInterface $container)
{
$this->framework = $framework;
$this->container = $container;
}

/**
* Get a remote file from cache and cache file, if not already in cache.
*
* @param string $identifier Used as filename of the cached image. Should be unique within the folder scope
* @param string $folder Folder path or uuid of the file
* @param $remoteUrl The url of the cached (or to cache) file
* @param bool $returnUuid Return uuid instead of the path
*
* @return bool|string
*/
public function get(string $identifier, $folder, $remoteUrl, $returnUuid = false)
{
$strFilename = $identifier.'.jpg';

if (Validator::isUuid($folder)) {
$objFolder = $this->container->get('huh.utils.file')->getFolderFromUuid($folder);
$folder = $objFolder->value;
}

$objFile = new File(rtrim($folder, '/').'/'.$strFilename);

if ($objFile->exists() && $objFile->size > 0) {
return $returnUuid ? $objFile->getModel()->uuid : $objFile->path;
}

$strContent = $this->container->get('huh.utils.curl')->request($remoteUrl);

if (!$strContent || !is_string($strContent)) {
return false;
}

$objFile->write($strContent);
$objFile->close();

return $returnUuid ? $objFile->getModel()->uuid : $objFile->path;
}
}
167 changes: 167 additions & 0 deletions src/Curl/Curl.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
<?php

/*
* Copyright (c) 2018 Heimrich & Hannot GmbH
*
* @license LGPL-3.0-or-later
*/

namespace HeimrichHannot\UtilsBundle\Curl;

use Contao\Config;

class Curl
{
public static function recursivelyGetRequest($intMaxRecursionCount, $funcTerminationCondition, $strUrl, array $arrRequestHeaders = [], $blnReturnResponseHeaders = false)
{
$i = 0;
$blnTerminate = false;
$varResult = null;

while ($i++ < $intMaxRecursionCount && !$blnTerminate) {
$varResult = static::request($strUrl, $arrRequestHeaders, $blnReturnResponseHeaders);

$blnTerminate = $funcTerminationCondition($varResult, $strUrl, $arrRequestHeaders, $blnReturnResponseHeaders, $intMaxRecursionCount);
}

return $varResult;
}

public function request($strUrl, array $arrRequestHeaders = [], $blnReturnResponseHeaders = false)
{
$objCurl = static::createCurlObject($strUrl);

if (Config::get('hpProxy')) {
curl_setopt($objCurl, CURLOPT_PROXY, Config::get('hpProxy'));
}

if (!empty($arrRequestHeaders)) {
static::setHeaders($objCurl, $arrRequestHeaders);
}

if ($blnReturnResponseHeaders) {
curl_setopt($objCurl, CURLOPT_HEADER, true);
}

$strResponse = curl_exec($objCurl);
$intStatusCode = curl_getinfo($objCurl, CURLINFO_HTTP_CODE);
curl_close($objCurl);

if ($blnReturnResponseHeaders) {
return static::splitResponseHeaderAndBody($strResponse, $intStatusCode);
}

return $strResponse;
}

public static function recursivelyPostRequest($intMaxRecursionCount, $funcTerminationCondition, $strUrl, array $arrRequestHeaders = [], array $arrPost = [], $blnReturnResponseHeaders = false)
{
$i = 0;
$blnTerminate = false;
$varResult = null;

while ($i++ < $intMaxRecursionCount && !$blnTerminate) {
$varResult = static::postRequest($strUrl, $arrRequestHeaders, $arrPost, $blnReturnResponseHeaders);

$blnTerminate = $funcTerminationCondition($varResult, $strUrl, $arrRequestHeaders, $arrPost, $blnReturnResponseHeaders, $intMaxRecursionCount);
}

return $varResult;
}

public static function postRequest($strUrl, array $arrRequestHeaders = [], array $arrPost = [], $blnReturnResponseHeaders = false)
{
$objCurl = static::createCurlObject($strUrl);

if (Config::get('hpProxy')) {
curl_setopt($objCurl, CURLOPT_PROXY, Config::get('hpProxy'));
}

if ($blnReturnResponseHeaders) {
curl_setopt($objCurl, CURLOPT_HEADER, true);
}

if (!empty($arrRequestHeaders)) {
static::setHeaders($objCurl, $arrRequestHeaders);
}

if (!empty($arrPost)) {
curl_setopt($objCurl, CURLOPT_POST, true);
curl_setopt($objCurl, CURLOPT_POSTFIELDS, http_build_query($arrPost));
}

$strResponse = curl_exec($objCurl);
$intStatusCode = curl_getinfo($objCurl, CURLINFO_HTTP_CODE);
curl_close($objCurl);

if ($blnReturnResponseHeaders) {
return static::splitResponseHeaderAndBody($strResponse, $intStatusCode);
}

return $strResponse;
}

public static function createCurlObject($strUrl)
{
$objCurl = curl_init($strUrl);

curl_setopt($objCurl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($objCurl, CURLOPT_TIMEOUT, 10);

return $objCurl;
}

public static function setHeaders($objCurl, array $arrHeaders)
{
$arrPrepared = [];

foreach ($arrHeaders as $strName => $varValue) {
$arrPrepared[] = $strName.': '.$varValue;
}

curl_setopt($objCurl, CURLOPT_HTTPHEADER, $arrPrepared);
}

public static function splitResponseHeaderAndBody($strResponse, $intStatusCode)
{
$arrHeaders = [];

$intSplit = strpos($strResponse, "\r\n\r\n");
$strHeader = substr($strResponse, 0, $intSplit);
$strBody = str_replace($strHeader."\r\n\r\n", '', $strResponse);

foreach (explode("\r\n", $strHeader) as $i => $strLine) {
if (0 === $i) {
$arrHeaders['http_code'] = $intStatusCode;
} else {
list($strKey, $varValue) = explode(': ', $strLine);
$arrHeaders[$strKey] = $varValue;
}
}

return [$arrHeaders, trim($strBody)];
}

/**
* Creates a linebreak separated list of the headers in $arrHeaders -> see request() and postRequest().
*
* @param array $arrHeaders
*
* @return string
*/
public static function prepareHeaderArrayForPrint(array $arrHeaders)
{
$strResult = '';
$i = 0;

foreach ($arrHeaders as $strKey => $strValue) {
$strResult .= "$strKey: $strValue";

if ($i++ != count($arrHeaders) - 1) {
$strResult .= PHP_EOL;
}
}

return $strResult;
}
}
Loading

0 comments on commit 370ead4

Please sign in to comment.