Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow set target root CDN directory #103 #109

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,13 @@ Set the CDN URL:
'url' => 'https://s3.amazonaws.com',
```

##### CDN Base Directory
Set CDN base dir path, if null, upload assets into bucket root.
```php
'cdn_base_dir' => null,
```
Example: 'myapp1/assets', then you can access assets by url like https://my-bucket.name/myapp1/assets/file.jpg

##### HTTP

Set the HTTP parameters:
Expand Down
4 changes: 3 additions & 1 deletion src/Vinelab/Cdn/CdnFacade.php
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,9 @@ private function generateUrl($path, $prepend = '')

// remove slashes from begging and ending of the path
// and append directories if needed
$clean_path = $prepend.$this->helper->cleanPath($path);
$clean_path = $this->helper->getCdnFilePath(
$prepend.$this->helper->cleanPath($path)
);

// call the provider specific url generator
return $this->provider->urlGenerator($clean_path);
Expand Down
31 changes: 31 additions & 0 deletions src/Vinelab/Cdn/CdnHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,4 +112,35 @@ public function cleanPath($path)
{
return rtrim(ltrim($path, '/'), '/');
}

/**
* Make path to local file copy on CDN, using cdn_base_dir
* @param string $localPath
* @return string
*/
public function getCdnFilePath($localPath)
{
$baseDir = null;
$cfg = $this->getConfigurations();
$localPath = $this->normalizePath($localPath);

if (isset($cfg['cdn_base_dir'])) {
$baseDir = $cfg['cdn_base_dir'];
}

if (null === $baseDir) {
return $localPath;
}

return $this->cleanPath($baseDir).'/'.$this->cleanPath($localPath);
}

/**
* @param string $path
* @return string
*/
private function normalizePath($path)
{
return str_replace('\\', '/', $path);
}
}
2 changes: 2 additions & 0 deletions src/Vinelab/Cdn/Contracts/CdnHelperInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,6 @@ public function parseUrl($url);
public function startsWith($haystack, $needle);

public function cleanPath($path);

public function getCdnFilePath($localPath);
}
6 changes: 2 additions & 4 deletions src/Vinelab/Cdn/Providers/AwsS3Provider.php
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ public function upload($assets)
// the bucket name
'Bucket' => $this->getBucket(),
// the path of the file on the server (CDN)
'Key' => str_replace('\\', '/', $file->getPathName()),
'Key' => $this->cdn_helper->getCdnFilePath($file->getPathName()),
// the path of the path locally
'Body' => fopen($file->getRealPath(), 'r'),
// the permission of the file
Expand All @@ -214,8 +214,6 @@ public function upload($assets)
'Metadata' => $this->default['providers']['aws']['s3']['metadata'],
'Expires' => $this->default['providers']['aws']['s3']['expires'],
]);
// var_dump(get_class($command));exit();


$this->s3_client->execute($command);
} catch (S3Exception $e) {
Expand Down Expand Up @@ -395,7 +393,7 @@ private function getFilesAlreadyOnBucket($assets)
}

$assets->transform(function($item, $key) use(&$filesOnAWS) {
$fileOnAWS = $filesOnAWS->get(str_replace('\\', '/', $item->getPathName()));
$fileOnAWS = $filesOnAWS->get($this->cdn_helper->getCdnFilePath($item->getPathName()));

//select to upload files that are different in size AND last modified time.
if(!($item->getMTime() === $fileOnAWS['LastModified']) && !($item->getSize() === $fileOnAWS['Size'])) {
Expand Down
12 changes: 12 additions & 0 deletions src/config/cdn.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,18 @@
*/
'url' => 'https://s3.amazonaws.com',

/*
|--------------------------------------------------------------------------
| CDN BASE DIRECTORY
|--------------------------------------------------------------------------
|
| Set CDN base dir path, if null, upload into bucket root
| Example: 'myapp1/assets', then you can access assets
| by url like https://my-bucket.name/myapp1/assets/file.jpg
|
*/
'cdn_base_dir' => null,

/*
|--------------------------------------------------------------------------
| Threshold
Expand Down
4 changes: 4 additions & 0 deletions tests/Vinelab/Cdn/CdnFacadeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
*/
class CdnFacadeTest extends TestCase
{
const CDN_BASE_DIR = 'base';

public function setUp()
{
parent::setUp();
Expand All @@ -21,6 +23,7 @@ public function setUp()
'bypass' => false,
'default' => 'AwsS3',
'url' => 'https://s3.amazonaws.com',
'cdn_base_dir' => self::CDN_BASE_DIR,
'threshold' => 10,
'providers' => [
'aws' => [
Expand Down Expand Up @@ -66,6 +69,7 @@ public function setUp()
$this->helper->shouldReceive('getConfigurations')->once()->andReturn($configuration_file);
$this->helper->shouldReceive('cleanPath')->andReturn($this->asset_path);
$this->helper->shouldReceive('startsWith')->andReturn(true);
$this->helper->shouldReceive('getCdnFilePath')->andReturn(self::CDN_BASE_DIR.'/'.$this->asset_path);

$this->validator = new \Vinelab\Cdn\Validators\CdnFacadeValidator();

Expand Down
105 changes: 105 additions & 0 deletions tests/Vinelab/Cdn/CdnHelperTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
<?php

namespace Vinelab\Cdn\Tests;

use Illuminate\Config\Repository;
use Mockery as M;
use Vinelab\Cdn\CdnHelper;

/**
* Class CdnHelperTest.
* @category Test
* @author Maksim Khodyrev <maximkou@gmail.com>
*/
class CdnHelperTest extends \PHPUnit_Framework_TestCase
{
const CDN_BASE_DIR = 'base';

/**
* @dataProvider dpGetCdnFilePath
* @param string $localPath
* @param string $cdnPath
*/
public function testGetCdnFilePath($localPath, $cdnPath)
{
$helper = new CdnHelper(
new Repository([
'cdn' => $this->getCdnConfig()
])
);

$this->assertEquals(
$cdnPath,
$helper->getCdnFilePath($localPath)
);
}

/**
* @return array
*/
public function dpGetCdnFilePath()
{
return [
[
'public/image.png',
self::CDN_BASE_DIR.'/public/image.png',
],
[
'/public/image.png',
self::CDN_BASE_DIR.'/public/image.png',
],
[
'image.png',
self::CDN_BASE_DIR.'/image.png',
]
];
}

/**
* @return array
*/
private function getCdnConfig()
{
return [
'bypass' => false,
'default' => 'AwsS3',
'url' => 'https://s3.amazonaws.com',
'cdn_base_dir' => self::CDN_BASE_DIR,
'threshold' => 10,
'providers' => [
'aws' => [
's3' => [
'region' => 'us-standard',
'version' => 'latest',
'http' => null,
'buckets' => [
'my-bucket-name' => '*',
],
'acl' => 'public-read',
'cloudfront' => [
'use' => false,
'cdn_url' => '',
],
'metadata' => [],

'expires' => gmdate('D, d M Y H:i:s T', strtotime('+5 years')),

'cache-control' => 'max-age=2628000',
],
],
],
'include' => [
'directories' => [__DIR__],
'extensions' => [],
'patterns' => [],
],
'exclude' => [
'directories' => [],
'files' => [],
'extensions' => [],
'patterns' => [],
'hidden' => true,
],
];
}
}
4 changes: 4 additions & 0 deletions tests/Vinelab/Cdn/CdnTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
*/
class CdnTest extends TestCase
{
const CDN_BASE_DIR = 'base';

public function setUp()
{
parent::setUp();
Expand Down Expand Up @@ -81,6 +83,7 @@ public function testPushCommand()
'bypass' => false,
'default' => 'AwsS3',
'url' => 'https://s3.amazonaws.com',
'cdn_base_dir' => self::CDN_BASE_DIR,
'threshold' => 10,
'providers' => [
'aws' => [
Expand Down Expand Up @@ -144,6 +147,7 @@ public function testPushCommand()
$m_validator->shouldReceive('validate');

$m_helper = M::mock('Vinelab\Cdn\CdnHelper');
$m_helper->shouldReceive('getCdnFilePath');

$m_spl_file = M::mock('Symfony\Component\Finder\SplFileInfo');
$m_spl_file->shouldReceive('getPathname')
Expand Down
4 changes: 4 additions & 0 deletions tests/Vinelab/Cdn/Providers/AwsS3ProviderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
*/
class AwsS3ProviderTest extends TestCase
{
const CDN_BASE_DIR = 'base';

public function setUp()
{
parent::setUp();
Expand All @@ -33,6 +35,7 @@ public function setUp()
$this->m_helper = M::mock('Vinelab\Cdn\CdnHelper');
$this->m_helper->shouldReceive('parseUrl')
->andReturn($this->pased_url);
$this->m_helper->shouldReceive('getCdnFilePath');

$this->m_spl_file = M::mock('Symfony\Component\Finder\SplFileInfo');
$this->m_spl_file->shouldReceive('getPathname')->andReturn('vinelab/cdn/tests/Vinelab/Cdn/AwsS3ProviderTest.php');
Expand Down Expand Up @@ -103,6 +106,7 @@ public function testUploadingAssets()
$configurations = [
'default' => 'AwsS3',
'url' => 'https://s3.amazonaws.com',
'cdn_base_dir' => self::CDN_BASE_DIR,
'threshold' => 10,
'providers' => [
'aws' => [
Expand Down