Skip to content

Commit b3b87ef

Browse files
author
Francesco Abeni
committed
Build DataUri from remote URL
* get file from a remote URL via CURL and build a DataUri from it * perform basic CURL response validation
1 parent 6b84ac5 commit b3b87ef

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

src/DataURI/Data.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,32 @@ public static function buildFromFile($file, $strict = false, $lengthMode = Data:
225225
return $dataURI;
226226
}
227227

228+
/**
229+
* Get a new instance of DataUri\Data from a remote file
230+
*
231+
* @param string $url Path to the remote file
232+
* @param boolean $strict Use strict mode
233+
* @param int $lengthMode The length mode
234+
* @return \DataURI\Data
235+
*/
236+
public static function buildFromUrl($url, $strict = false, $lengthMode = Data::TAGLEN)
237+
{
238+
$ch = curl_init($url);
239+
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
240+
$data = curl_exec($ch);
241+
242+
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) != 200) {
243+
throw new FileNotFoundException(sprintf('%s file does not exist or the remote server does not respond', $url));
244+
}
245+
246+
$mimeType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
247+
curl_close($ch);
248+
249+
$dataURI = new static($data, $mimeType, array(), $strict, $lengthMode);
250+
251+
return $dataURI;
252+
}
253+
228254
/**
229255
* Contructor initialization
230256

tests/DataTest.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,15 @@ public function testBuildFromFile()
119119
$this->assertEquals(file_get_contents($file), $dataURI->getData());
120120
}
121121

122+
public function testBuildFromUrl()
123+
{
124+
$url = 'http://www.alchemy.fr/images/header_03.png';
125+
$dataURI = DataURI\Data::buildFromUrl($url);
126+
$this->assertInstanceOf('DataURI\Data', $dataURI);
127+
$this->assertEquals('image/png', $dataURI->getMimeType());
128+
$this->assertEquals(file_get_contents($url), $dataURI->getData());
129+
}
130+
122131
/**
123132
* @expectedException \DataURI\Exception\FileNotFoundException
124133
*/

0 commit comments

Comments
 (0)