Class yii\mongodb\file\Download

Inheritanceyii\mongodb\file\Download » yii\base\BaseObject
Implementsyii\base\Configurable
Available since version2.1
Source Code https://github.com/yiisoft/yii2-mongodb/blob/master/file/Download.php

Download represents the GridFS download operation.

A Download object is usually created by calling yii\mongodb\file\Collection::get() or yii\mongodb\file\Collection::createDownload().

Usage example:

Yii::$app->mongodb->getFileCollection()->createDownload($document['_id'])->toFile('/path/to/file.dat');

You can use Download::substr() to read a specific part of the file:

$filePart = Yii::$app->mongodb->getFileCollection()->createDownload($document['_id'])->substr(256, 1024);

Public Properties

Hide inherited properties

Property Type Description Defined By
$bytes string File content. yii\mongodb\file\Download
$chunkCursor \MongoDB\Driver\Cursor Chuck list cursor. yii\mongodb\file\Download
$chunkIterator Iterator Chuck cursor iterator. yii\mongodb\file\Download
$collection yii\mongodb\file\Collection File collection to be used. yii\mongodb\file\Download
$document array Document to be downloaded. yii\mongodb\file\Download
$filename string|null File name. yii\mongodb\file\Download
$resource resource File stream resource. yii\mongodb\file\Download
$size integer File size. yii\mongodb\file\Download

Public Methods

Hide inherited methods

Method Description Defined By
__call() Calls the named method which is not a class method. yii\base\BaseObject
__construct() Constructor. yii\base\BaseObject
__get() Returns the value of an object property. yii\base\BaseObject
__isset() Checks if a property is set, i.e. defined and not null. yii\base\BaseObject
__set() Sets value of an object property. yii\base\BaseObject
__unset() Sets an object property to null. yii\base\BaseObject
canGetProperty() Returns a value indicating whether a property can be read. yii\base\BaseObject
canSetProperty() Returns a value indicating whether a property can be set. yii\base\BaseObject
className() Returns the fully qualified name of this class. yii\base\BaseObject
getBytes() Alias of toString() method. yii\mongodb\file\Download
getChunkCursor() Returns file chunks read cursor. yii\mongodb\file\Download
getChunkIterator() Returns iterator for the file chunks cursor. yii\mongodb\file\Download
getDocument() yii\mongodb\file\Download
getFilename() Returns associated file's filename. yii\mongodb\file\Download
getResource() Returns persistent stream resource, which can be used to read file. yii\mongodb\file\Download
getSize() Returns the size of the associated file. yii\mongodb\file\Download
hasMethod() Returns a value indicating whether a method is defined. yii\base\BaseObject
hasProperty() Returns a value indicating whether a property is defined. yii\base\BaseObject
init() Initializes the object. yii\base\BaseObject
setDocument() Sets data of the document to be downloaded. yii\mongodb\file\Download
substr() Return part of a file. yii\mongodb\file\Download
toFile() Saves download to the physical file. yii\mongodb\file\Download
toResource() Returns an opened stream resource, which can be used to read file. yii\mongodb\file\Download
toStream() Saves file into the given stream. yii\mongodb\file\Download
toString() Returns a string of the bytes in the associated file. yii\mongodb\file\Download
write() Alias of toFile() method. yii\mongodb\file\Download

Property Details

Hide inherited properties

$bytes public property

File content.

public string $bytes null
$chunkCursor public property

Chuck list cursor.

public \MongoDB\Driver\Cursor $chunkCursor null
$chunkIterator public property

Chuck cursor iterator.

public Iterator $chunkIterator null
$collection public property

File collection to be used.

$document public property

Document to be downloaded. Note that the type of this property differs in getter and setter. See getDocument() and setDocument() for details.

public array $document null
$filename public property

File name.

public string|null $filename null
$resource public property

File stream resource.

public resource $resource null
$size public property

File size.

public integer $size null

Method Details

Hide inherited methods

__call() public method

Defined in: yii\base\BaseObject::__call()

Calls the named method which is not a class method.

Do not call this method directly as it is a PHP magic method that will be implicitly called when an unknown method is being invoked.

public mixed __call ( $name, $params )
$name string

The method name

$params array

Method parameters

return mixed

The method return value

throws yii\base\UnknownMethodException

when calling unknown method

                public function __call($name, $params)
{
    throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}

            
__construct() public method

Defined in: yii\base\BaseObject::__construct()

Constructor.

The default implementation does two things:

  • Initializes the object with the given configuration $config.
  • Call init().

If this method is overridden in a child class, it is recommended that

  • the last parameter of the constructor is a configuration array, like $config here.
  • call the parent implementation at the end of the constructor.
public void __construct ( $config = [] )
$config array

Name-value pairs that will be used to initialize the object properties

                public function __construct($config = [])
{
    if (!empty($config)) {
        Yii::configure($this, $config);
    }
    $this->init();
}

            
__get() public method

Defined in: yii\base\BaseObject::__get()

Returns the value of an object property.

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $value = $object->property;.

See also __set().

public mixed __get ( $name )
$name string

The property name

return mixed

The property value

throws yii\base\UnknownPropertyException

if the property is not defined

throws yii\base\InvalidCallException

if the property is write-only

                public function __get($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        return $this->$getter();
    } elseif (method_exists($this, 'set' . $name)) {
        throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
    }
    throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}

            
__isset() public method

Defined in: yii\base\BaseObject::__isset()

Checks if a property is set, i.e. defined and not null.

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing isset($object->property).

Note that if the property is not defined, false will be returned.

See also https://www.php.net/manual/en/function.isset.php.

public boolean __isset ( $name )
$name string

The property name or the event name

return boolean

Whether the named property is set (not null).

                public function __isset($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        return $this->$getter() !== null;
    }
    return false;
}

            
__set() public method

Defined in: yii\base\BaseObject::__set()

Sets value of an object property.

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $object->property = $value;.

See also __get().

public void __set ( $name, $value )
$name string

The property name or the event name

$value mixed

The property value

throws yii\base\UnknownPropertyException

if the property is not defined

throws yii\base\InvalidCallException

if the property is read-only

                public function __set($name, $value)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        $this->$setter($value);
    } elseif (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
    } else {
        throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
    }
}

            
__unset() public method

Defined in: yii\base\BaseObject::__unset()

Sets an object property to null.

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing unset($object->property).

Note that if the property is not defined, this method will do nothing. If the property is read-only, it will throw an exception.

See also https://www.php.net/manual/en/function.unset.php.

public void __unset ( $name )
$name string

The property name

throws yii\base\InvalidCallException

if the property is read only.

                public function __unset($name)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        $this->$setter(null);
    } elseif (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Unsetting read-only property: ' . get_class($this) . '::' . $name);
    }
}

            
canGetProperty() public method

Defined in: yii\base\BaseObject::canGetProperty()

Returns a value indicating whether a property can be read.

A property is readable if:

  • the class has a getter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);

See also canSetProperty().

public boolean canGetProperty ( $name, $checkVars true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

return boolean

Whether the property can be read

                public function canGetProperty($name, $checkVars = true)
{
    return method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name);
}

            
canSetProperty() public method

Defined in: yii\base\BaseObject::canSetProperty()

Returns a value indicating whether a property can be set.

A property is writable if:

  • the class has a setter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);

See also canGetProperty().

public boolean canSetProperty ( $name, $checkVars true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

return boolean

Whether the property can be written

                public function canSetProperty($name, $checkVars = true)
{
    return method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name);
}

            
className() public static method
Deprecated since 2.0.14. On PHP >=5.5, use ::class instead.

Defined in: yii\base\BaseObject::className()

Returns the fully qualified name of this class.

public static string className ( )
return string

The fully qualified name of this class.

                public static function className()
{
    return get_called_class();
}

            
getBytes() public method

Alias of toString() method.

public string getBytes ( )
return string

File content.

                public function getBytes()
{
    return $this->toString();
}

            
getChunkCursor() public method

Returns file chunks read cursor.

public \MongoDB\Driver\Cursor getChunkCursor ( $refresh false )
$refresh boolean

Whether to recreate cursor, if it is already exist.

return \MongoDB\Driver\Cursor

Chuck list cursor.

throws yii\base\InvalidConfigException

                public function getChunkCursor($refresh = false)
{
    if ($refresh || $this->_chunkCursor === null) {
        $file = $this->getDocument();
        $this->_chunkCursor = $this->collection->getChunkCollection()->find(
            ['files_id' => $file['_id']],
            [],
            ['sort' => ['n' => 1]]
        );
    }
    return $this->_chunkCursor;
}

            
getChunkIterator() public method

Returns iterator for the file chunks cursor.

public Iterator getChunkIterator ( $refresh false )
$refresh boolean

Whether to recreate iterator, if it is already exist.

return Iterator

Chuck cursor iterator.

                public function getChunkIterator($refresh = false)
{
    if ($refresh || $this->_chunkIterator === null) {
        $this->_chunkIterator = new \IteratorIterator($this->getChunkCursor($refresh));
        $this->_chunkIterator->rewind();
    }
    return $this->_chunkIterator;
}

            
getDocument() public method

public array getDocument ( )
return array

Document to be downloaded.

throws yii\base\InvalidConfigException

on invalid document configuration.

                public function getDocument()
{
    if (!is_array($this->_document)) {
        if (is_scalar($this->_document) || $this->_document instanceof ObjectID) {
            $document = $this->collection->findOne(['_id' => $this->_document]);
            if (empty($document)) {
                throw new InvalidConfigException('Document id=' . $this->_document . ' does not exist at collection "' . $this->collection->getFullName() . '"');
            }
            $this->_document = $document;
        } else {
            $this->_document = (array)$this->_document;
        }
    }
    return $this->_document;
}

            
getFilename() public method

Returns associated file's filename.

public string|null getFilename ( )
return string|null

File name.

                public function getFilename()
{
    $document = $this->getDocument();
    return isset($document['filename']) ? $document['filename'] : null;
}

            
getResource() public method

Returns persistent stream resource, which can be used to read file.

public resource getResource ( )
return resource

File stream resource.

                public function getResource()
{
    if ($this->_resource === null) {
        $this->_resource = $this->toResource();
    }
    return $this->_resource;
}

            
getSize() public method

Returns the size of the associated file.

public integer getSize ( )
return integer

File size.

                public function getSize()
{
    $document = $this->getDocument();
    return isset($document['length']) ? $document['length'] : 0;
}

            
hasMethod() public method

Defined in: yii\base\BaseObject::hasMethod()

Returns a value indicating whether a method is defined.

The default implementation is a call to php function method_exists(). You may override this method when you implemented the php magic method __call().

public boolean hasMethod ( $name )
$name string

The method name

return boolean

Whether the method is defined

                public function hasMethod($name)
{
    return method_exists($this, $name);
}

            
hasProperty() public method

Defined in: yii\base\BaseObject::hasProperty()

Returns a value indicating whether a property is defined.

A property is defined if:

  • the class has a getter or setter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);

See also:

public boolean hasProperty ( $name, $checkVars true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

return boolean

Whether the property is defined

                public function hasProperty($name, $checkVars = true)
{
    return $this->canGetProperty($name, $checkVars) || $this->canSetProperty($name, false);
}

            
init() public method

Defined in: yii\base\BaseObject::init()

Initializes the object.

This method is invoked at the end of the constructor after the object is initialized with the given configuration.

public void init ( )

                public function init()
{
}

            
setDocument() public method

Sets data of the document to be downloaded.

Document can be specified by its ID, in this case its data will be fetched automatically via extra query.

public void setDocument ( $document )
$document array|\MongoDB\BSON\ObjectID

Document raw data or document ID.

                public function setDocument($document)
{
    $this->_document = $document;
}

            
substr() public method

Return part of a file.

public string|false substr ( $start, $length )
$start integer

Reading start position. If non-negative, the returned string will start at the start'th position in file, counting from zero. If negative, the returned string will start at the start'th character from the end of file.

$length integer

Number of bytes to read. If given and is positive, the string returned will contain at most length characters beginning from start (depending on the length of file). If given and is negative, then that many characters will be omitted from the end of file (after the start position has been calculated when a start is negative).

return string|false

The extracted part of file or false on failure

                public function substr($start, $length)
{
    $document = $this->getDocument();
    if ($start < 0) {
        $start = max($document['length'] + $start, 0);
    }
    if ($start > $document['length']) {
        return false;
    }
    if ($length < 0) {
        $length = $document['length'] - $start + $length;
        if ($length < 0) {
            return false;
        }
    }
    $chunkSize = $document['chunkSize'];
    $startChunkNumber = floor($start / $chunkSize);
    $chunkIterator = $this->getChunkIterator();
    if (!$chunkIterator->valid()) {
        // invalid iterator state - recreate iterator
        // unable to use `rewind` due to error "Cursors cannot rewind after starting iteration"
        $chunkIterator = $this->getChunkIterator(true);
    }
    if ($chunkIterator->key() > $startChunkNumber) {
        // unable to go back by iterator
        // unable to use `rewind` due to error "Cursors cannot rewind after starting iteration"
        $chunkIterator = $this->getChunkIterator(true);
    }
    $result = '';
    $chunkDataOffset = $start - $startChunkNumber * $chunkSize;
    while ($chunkIterator->valid()) {
        if ($chunkIterator->key() >= $startChunkNumber) {
            $chunk = $chunkIterator->current();
            $data = $chunk['data']->getData();
            $readLength = min($chunkSize - $chunkDataOffset, $length);
            $result .= StringHelper::byteSubstr($data, $chunkDataOffset, $readLength);
            $length -= $readLength;
            if ($length <= 0) {
                break;
            }
            $chunkDataOffset = 0;
        }
        $chunkIterator->next();
    }
    return $result;
}

            
toFile() public method

Saves download to the physical file.

public integer toFile ( $filename )
$filename string

Name of the physical file.

return integer

Number of written bytes.

                public function toFile($filename)
{
    $filename = Yii::getAlias($filename);
    FileHelper::createDirectory(dirname($filename));
    return $this->toStream(fopen($filename, 'w+'));
}

            
toResource() public method

Returns an opened stream resource, which can be used to read file.

Note: each invocation of this method will create new file resource.

public resource toResource ( )
return resource

Stream resource.

                public function toResource()
{
    $protocol = $this->collection->database->connection->registerFileStreamWrapper();
    $context = stream_context_create([
        $protocol => [
            'download' => $this,
        ]
    ]);
    $document = $this->getDocument();
    $url = "{$protocol}://{$this->collection->database->name}.{$this->collection->prefix}?_id={$document['_id']}";
    return fopen($url, 'r', false, $context);
}

            
toStream() public method

Saves file into the given stream.

public integer toStream ( $stream )
$stream resource

Stream, which file should be saved to.

return integer

Number of written bytes.

                public function toStream($stream)
{
    $bytesWritten = 0;
    foreach ($this->getChunkCursor() as $chunk) {
        $bytesWritten += fwrite($stream, $chunk['data']->getData());
    }
    return $bytesWritten;
}

            
toString() public method

Returns a string of the bytes in the associated file.

public string toString ( )
return string

File content.

                public function toString()
{
    $result = '';
    foreach ($this->getChunkCursor() as $chunk) {
        $result .= $chunk['data']->getData();
    }
    return $result;
}

            
write() public method

Alias of toFile() method.

public integer write ( $filename )
$filename string

Name of the physical file.

return integer

Number of written bytes.

                public function write($filename)
{
    return $this->toFile($filename);
}