Newer
Older
Dries Buytaert
committed
<?php
/**
* @file
* Contains \Drupal\Core\TypedData\Plugin\DataType\BinaryData.
Dries Buytaert
committed
*/
Alex Pott
committed
namespace Drupal\Core\TypedData\Plugin\DataType;
Dries Buytaert
committed
Alex Pott
committed
use Drupal\Core\TypedData\PrimitiveBase;
use Drupal\Core\TypedData\Type\BinaryInterface;
Dries Buytaert
committed
/**
* The binary data type.
*
* The plain value of binary data is a PHP file resource, see
* http://php.net/manual/language.types.resource.php. For setting the value
Dries Buytaert
committed
* a PHP file resource or a (absolute) stream resource URI may be passed.
Alex Pott
committed
*
* @DataType(
* id = "binary",
Alex Pott
committed
* label = @Translation("Binary")
Alex Pott
committed
* )
Dries Buytaert
committed
*/
class BinaryData extends PrimitiveBase implements BinaryInterface {
Dries Buytaert
committed
/**
* The file resource URI.
*
* @var string
*/
protected $uri;
/**
* A generic file resource handle.
*
* @var resource
*/
public $handle = NULL;
/**
* {@inheritdoc}
Dries Buytaert
committed
*/
public function getValue() {
// If the value has been set by (absolute) stream resource URI, access the
// resource now.
Dries Buytaert
committed
if (!isset($this->handle) && isset($this->uri)) {
Dries Buytaert
committed
$this->handle = is_readable($this->uri) ? fopen($this->uri, 'rb') : FALSE;
Dries Buytaert
committed
}
return $this->handle;
}
/**
* Overrides TypedData::setValue().
*
* Supports a PHP file resource or a (absolute) stream resource URI as value.
Dries Buytaert
committed
*/
catch
committed
public function setValue($value, $notify = TRUE) {
Dries Buytaert
committed
if (!isset($value)) {
$this->handle = NULL;
$this->uri = NULL;
}
elseif (is_string($value)) {
// Note: For performance reasons we store the given URI and access the
// resource upon request. See BinaryData::getValue()
Dries Buytaert
committed
$this->uri = $value;
Dries Buytaert
committed
$this->handle = NULL;
Dries Buytaert
committed
}
else {
Dries Buytaert
committed
$this->handle = $value;
Dries Buytaert
committed
}
// Notify the parent of any changes.
if ($notify && isset($this->parent)) {
$this->parent->onChange($this->name);
}
Dries Buytaert
committed
}
/**
* {@inheritdoc}
Dries Buytaert
committed
*/
public function getString() {
// Return the file content.
Dries Buytaert
committed
$contents = '';
while (!feof($this->getValue())) {
$contents .= fread($this->handle, 8192);
}
return $contents;
}
Dries Buytaert
committed
/**
* {@inheritdoc}
Dries Buytaert
committed
*/
public function getCastedValue() {
return $this->getValue();
}