Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions src/CustomMimetypeHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

namespace Http\Message\MultipartStream;

/**
* Let you add your own mimetypes. The mimetype lookup will fallback on the ApacheMimeTypeHelper.
*
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class CustomMimetypeHelper extends ApacheMimetypeHelper
{
/**
* @var array
*/
private $mimetypes = [];

/**
* @param array $mimetypes should be of type extension => mimetype
*/
public function __construct(array $mimetypes = [])
{
$this->mimetypes = $mimetypes;
}

/**
* @param string $extension
* @param string $mimetype
*
* @return $this
*/
public function addMimetype($extension, $mimetype)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i am not sure we need an adder for this. the constructor should be enough, its not like we discover mime types at runtime - or is there a use case for that?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Im not sure this would ever be used, no. But I thought "why not?" This class should only be used in the 1% edge case. And if you are such end case you are probably doing something special and could probably be in a scenario when you want to edit this at runtime.

{
$this->mimetypes[$extension] = $mimetype;

return $this;
}

/**
* {@inheritdoc}
*
* Check if we have any defined mimetypes and of not fallback to ApacheMimetypeHelper
*/
public function getMimetypeFromExtension($extension)
{
$extension = strtolower($extension);

return isset($this->mimetypes[$extension])
? $this->mimetypes[$extension]
: parent::getMimetypeFromExtension($extension);
}
}
18 changes: 18 additions & 0 deletions tests/CustomMimetypeHelperTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace tests\Http\Message\MultipartStream;

use Http\Message\MultipartStream\CustomMimetypeHelper;

class CustomMimetypeHelperTest extends \PHPUnit_Framework_TestCase
{
public function testGetMimetypeFromExtension()
{
$helper = new CustomMimetypeHelper(['foo'=>'foo/bar']);
$this->assertEquals('foo/bar', $helper->getMimetypeFromExtension('foo'));

$this->assertEquals('application/x-rar-compressed', $helper->getMimetypeFromExtension('rar'));
$helper->addMimetype('rar', 'test/test');
$this->assertEquals('test/test', $helper->getMimetypeFromExtension('rar'));
}
}