Skip to content

Commit

Permalink
Add support for a DropboxFile from stream
Browse files Browse the repository at this point in the history
Sometimes we need to upload a file that isn't on the filesystem but is already a file stream.
This commit adds a new static function CreateByStream that allows us to create a new DropboxFile instance using a stream.
  • Loading branch information
jnstr authored and kunalvarma05 committed Apr 22, 2017
1 parent 8997759 commit 3f74cc8
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions src/Dropbox/DropboxFile.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,13 @@ class DropboxFile
*/
protected $mode;

/**
* Flag to see if we created an instance using a stream
*
* @var bool
*/
private $isStream = false;

/**
* Create a new DropboxFile instance
*
Expand All @@ -68,6 +75,48 @@ public function __destruct()
{
$this->close();
}


/**
* Create a new DropboxFile instance using a file stream
*
* @param $fileName
* @param $resource
* @param string $mode
* @return DropboxFile
* @throws DropboxClientException
*/
public static function createByStream($fileName, $resource, $mode = self::MODE_READ)
{
// initialize a new intance
$dropboxFile = new self($fileName, $mode);

// create a new stream and set it to the dropbox file
$stream = \GuzzleHttp\Psr7\stream_for($resource);
if (!$stream) {
throw new DropboxClientException('Failed to create DropboxFile instance. Unable to open the given resource.');
}
$dropboxFile->setStream($stream);

return $dropboxFile;
}

/**
* Create a new DropboxFile instance using a file path
*
* This behaves the same as the constructor but was added in order to
* match the syntax of the static createByStream function
*
* @see DropboxFile::createByStream()
*
* @param $filePath
* @param $mode
* @return DropboxFile
*/
public static function createByPath($filePath, $mode)
{
return new self($filePath, $mode);
}

/**
* Close the file stream
Expand Down Expand Up @@ -100,6 +149,17 @@ public function setMaxLength($maxLength)
{
$this->maxLength = $maxLength;
}

/**
* Manually set the stream for this DropboxFile instance
*
* @param $stream
*/
public function setStream($stream)
{
$this->isStream = true;
$this->stream = $stream;
}

/**
* Return the contents of the file
Expand Down Expand Up @@ -146,6 +206,11 @@ public function getStream()
*/
public function open()
{
// File was created from a stream so don't open it again
if ($this->stream && $this->isStream === true) {
return;
}

if (!$this->isRemoteFile($this->path)) {
if (self::MODE_READ === $this->mode && !is_readable($this->path)) {
throw new DropboxClientException('Failed to create DropboxFile instance. Unable to read resource: ' . $this->path . '.');
Expand Down

0 comments on commit 3f74cc8

Please sign in to comment.