-
Notifications
You must be signed in to change notification settings - Fork 299
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #32 from aonic/master
Added a CSV handler in the core handlers
- Loading branch information
Showing
4 changed files
with
83 additions
and
2 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
<?php | ||
/** | ||
* Mime Type: text/csv | ||
* @author Raja Kapur <[email protected]> | ||
*/ | ||
|
||
namespace Httpful\Handlers; | ||
|
||
class CsvHandler extends MimeHandlerAdapter | ||
{ | ||
/** | ||
* @param string $body | ||
* @return mixed | ||
*/ | ||
public function parse($body) | ||
{ | ||
if (empty($body)) | ||
return null; | ||
|
||
$parsed = array(); | ||
$fp = fopen('data://text/plain;base64,' . base64_encode($body), 'r'); | ||
while (($r = fgetcsv($fp)) !== FALSE) { | ||
$parsed[] = $r; | ||
} | ||
|
||
if (empty($parsed)) | ||
throw new \Exception("Unable to parse response as CSV"); | ||
return $parsed; | ||
} | ||
|
||
/** | ||
* @param mixed $payload | ||
* @return string | ||
*/ | ||
public function serialize($payload) | ||
{ | ||
$fp = fopen('php://temp/maxmemory:'. (6*1024*1024), 'r+'); | ||
$i = 0; | ||
foreach ($payload as $fields) { | ||
if($i++ == 0) { | ||
fputcsv($fp, array_keys($fields)); | ||
} | ||
fputcsv($fp, $fields); | ||
} | ||
rewind($fp); | ||
$data = stream_get_contents($fp); | ||
fclose($fp); | ||
return $data; | ||
} | ||
} |
This file contains 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
This file contains 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