Version 1
[yaffs-website] / web / core / lib / Drupal / Core / TypedData / Plugin / DataType / BinaryData.php
1 <?php
2
3 namespace Drupal\Core\TypedData\Plugin\DataType;
4
5 use Drupal\Core\TypedData\PrimitiveBase;
6 use Drupal\Core\TypedData\Type\BinaryInterface;
7
8 /**
9  * The binary data type.
10  *
11  * The plain value of binary data is a PHP file resource, see
12  * http://php.net/manual/language.types.resource.php. For setting the value
13  * a PHP file resource or a (absolute) stream resource URI may be passed.
14  *
15  * @DataType(
16  *   id = "binary",
17  *   label = @Translation("Binary")
18  * )
19  */
20 class BinaryData extends PrimitiveBase implements BinaryInterface {
21
22   /**
23    * The file resource URI.
24    *
25    * @var string
26    */
27   protected $uri;
28
29   /**
30    * A generic file resource handle.
31    *
32    * @var resource
33    */
34   public $handle = NULL;
35
36   /**
37    * {@inheritdoc}
38    */
39   public function getValue() {
40     // If the value has been set by (absolute) stream resource URI, access the
41     // resource now.
42     if (!isset($this->handle) && isset($this->uri)) {
43       $this->handle = is_readable($this->uri) ? fopen($this->uri, 'rb') : FALSE;
44     }
45     return $this->handle;
46   }
47
48   /**
49    * Overrides TypedData::setValue().
50    *
51    * Supports a PHP file resource or a (absolute) stream resource URI as value.
52    */
53   public function setValue($value, $notify = TRUE) {
54     if (!isset($value)) {
55       $this->handle = NULL;
56       $this->uri = NULL;
57     }
58     elseif (is_string($value)) {
59       // Note: For performance reasons we store the given URI and access the
60       // resource upon request. See BinaryData::getValue()
61       $this->uri = $value;
62       $this->handle = NULL;
63     }
64     else {
65       $this->handle = $value;
66     }
67     // Notify the parent of any changes.
68     if ($notify && isset($this->parent)) {
69       $this->parent->onChange($this->name);
70     }
71   }
72
73   /**
74    * {@inheritdoc}
75    */
76   public function getString() {
77     // Return the file content.
78     $contents = '';
79     while (!feof($this->getValue())) {
80       $contents .= fread($this->handle, 8192);
81     }
82     return $contents;
83   }
84
85   /**
86    * {@inheritdoc}
87    */
88   public function getCastedValue() {
89     return $this->getValue();
90   }
91
92 }