summaryrefslogtreecommitdiffstats
path: root/core/lib/Drupal/Core/TypedData/Plugin/DataType/BinaryData.php
blob: e51e5055b9b5f2eb16864aeb33696e9d8ea9feaa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php

namespace Drupal\Core\TypedData\Plugin\DataType;

use Drupal\Core\TypedData\PrimitiveBase;
use Drupal\Core\TypedData\Type\BinaryInterface;

/**
 * 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
 * a PHP file resource or a (absolute) stream resource URI may be passed.
 *
 * @DataType(
 *   id = "binary",
 *   label = @Translation("Binary")
 * )
 */
class BinaryData extends PrimitiveBase implements BinaryInterface {

  /**
   * The file resource URI.
   *
   * @var string
   */
  protected $uri;

  /**
   * A generic file resource handle.
   *
   * @var resource
   */
  public $handle = NULL;

  /**
   * {@inheritdoc}
   */
  public function getValue() {
    // If the value has been set by (absolute) stream resource URI, access the
    // resource now.
    if (!isset($this->handle) && isset($this->uri)) {
      $this->handle = is_readable($this->uri) ? fopen($this->uri, 'rb') : FALSE;
    }
    return $this->handle;
  }

  /**
   * Overrides TypedData::setValue().
   *
   * Supports a PHP file resource or a (absolute) stream resource URI as value.
   */
  public function setValue($value, $notify = TRUE) {
    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()
      $this->uri = $value;
      $this->handle = NULL;
    }
    else {
      $this->handle = $value;
    }
    // Notify the parent of any changes.
    if ($notify && isset($this->parent)) {
      $this->parent->onChange($this->name);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getString() {
    // Return the file content.
    $contents = '';
    while (!feof($this->getValue())) {
      $contents .= fread($this->handle, 8192);
    }
    return $contents;
  }

  /**
   * {@inheritdoc}
   */
  public function getCastedValue() {
    return $this->getValue();
  }

}