AthenaeumAthenaeum
Packages
  • next
  • current
  • v9.x
  • v8.x
  • v7.x
  • v6.x
  • v5.x
  • v4.x
  • v3.x
  • v2.x
  • v1.x
Changelog
GitHub
Packages
  • next
  • current
  • v9.x
  • v8.x
  • v7.x
  • v6.x
  • v5.x
  • v4.x
  • v3.x
  • v2.x
  • v1.x
Changelog
GitHub
  • Version 7.x

    • Release Notes
    • Upgrade Guide
    • New to this...
    • Contribution Guide
    • Security Policy
    • Code of Conduct
    • Origin
  • ACL

    • Introduction
    • How to install
    • Setup
    • Permissions
    • Roles
    • Users
    • Cached Permissions
  • Antivirus

    • Introduction
    • How to install
    • Setup
    • How to use
    • Scanners

      • Introduction
      • ClamAV
      • Null
      • Custom
    • Events
    • PSR
  • Audit

    • Audit
    • How to install
    • Setup
    • Recording
    • Events
  • Auth

    • Introduction
    • How to install
    • Fortify

      • Prerequisites
      • Actions

        • Rehash Password
  • Circuits

    • Circuits
    • How to install
    • Setup
    • Usage
    • Events
  • Collections

    • Collections
    • How to install
    • Summation

      • Summation Collection
      • Items Processor
  • Config

    • Configuration Loader
    • How to install
    • Setup
    • Load Configuration Files
    • Custom File Parsers
  • Console

    • Command and Schedule Registration
    • How to install
    • Setup
    • Commands
    • Schedules
  • Container

    • IoC Service Container
    • How to install
    • Container
    • List Resolver
  • Core

    • Athenaeum Core Application
    • How to install
    • Setup
    • Usage

      • Configuration
      • Service Providers
      • Service Container
      • Events
      • Caching
      • Logging
      • Console
      • Task Scheduling
      • Exception Handling
      • Extending Core Application
      • Testing
  • Database

    • Introduction
    • How to install
    • Models

      • Instantiatable
      • Sluggable
    • Query

      • Criteria (Query Filter)
  • Dto

    • Data Transfer Object (DTO)
    • How to install
    • Create Interface
    • Implement DTO
    • How to use
    • Populate
    • Export
    • Json
    • Serialization
    • Nested DTOs
    • Array DTO
  • ETags

    • Introduction
    • How to install
    • Setup
    • ETags usage

      • How to use
      • Generators

        • Default Generator
        • Custom Generator
      • Eloquent Models
    • Http Request Preconditions

      • Introduction
      • Resource Context
      • Preconditions
      • Actions
      • RFC 9110

        • If-Match
        • If-Unmodified-Since
        • If-None-Match
        • If-Modified-Since
        • If-Range
      • Extensions

        • Introduction
        • Range
      • Range Validator
      • Download Stream
    • Macros
  • Events

    • Register Listeners and Subscribers
    • How to install
    • Setup
    • Listeners
    • Subscribers
  • Filters

    • Search Filter Utilities
    • Prerequisites
    • How to install
    • Setup
    • Processor
    • Filters Builder
    • Predefined Resources

      • Search Processor
      • Sorting Processor
      • Constraints Processor
      • Matching Processor
    • Tip: Create a base builder
  • Flysystem

    • Introduction
    • Database Adapter

      • Introduction
      • How to install
      • Setup
      • Data Deduplication
      • MIME-Type Detection
  • Http

    • Api

      • Http API
      • How to install
      • Setup
      • Resources

        • Introduction
        • Timestamps
        • Self-Link
        • Relations
        • Caching
        • Registrar
      • Requests

        • Introduction
        • List Resources
        • List Deleted
        • Show Resource
        • Create Resource
        • Update Resource
        • Delete Resource
        • List Related
        • Process Multiple Resources
        • Helpers
      • Middleware

        • Introduction
        • Request Must Be Json
        • Capture Fields To Select
        • Remove Response Payload
    • Clients

      • Http Clients
      • How to install
      • Setup
      • Basic Usage
      • Available Methods

        • Fluent Api
        • Protocol Version
        • Base Uri
        • Http Method and Uri
        • Headers
        • Accept & Content-Type
        • Authentication
        • Http Query
        • Payload Format
        • Payload
        • Attachments
        • Cookies
        • Response Expectations
        • Middleware
        • Conditions
        • Criteria
        • Redirects
        • Timeout
        • Debugging
        • Logging
        • Driver Options
        • Driver
      • Http Query Builder

        • Introduction
        • Select
        • Where
        • Dates
        • Include
        • Pagination
        • Sorting
        • Raw Expressions
        • Custom Grammar
    • Cookies

      • Http Cookies
      • How to install
      • Usage
    • Messages

      • Http Messages
      • How to install
      • Serializers
  • Maintenance

    • Modes

      • Maintenance Modes
      • How to install
      • Setup
      • Basic Usage
      • Available Drivers
  • Mime Types

    • MIME-Types
    • How to install
    • Setup
    • Usage
    • Drivers

      • Available Drivers
      • File Info
  • Properties

    • Properties Overload
    • How to install
    • Usage
    • Naming Convention
    • Properties Visibility
  • Redmine

    • Redmine Api Client
    • How to install
    • Setup
    • General Usage

      • Supported Operations
      • Fetch list of resources
      • Find
      • Fetch
      • Create new record
      • Update existing record
      • Delete existing record
      • Relations
    • Available Resources

      • Predefined Resources
      • Attachments
      • Enumerations
      • Issue Relations
      • Users
      • User Groups
      • Roles
      • Project Memberships
      • Versions (Milestones)
      • Issue Categories
      • Trackers
  • Service

    • Service Registrar
    • How to install
    • How to use
  • Streams

    • Streams
    • How to install
    • Setup
    • How to use

      • Introduction
      • Open and Close
      • Raw Resource
      • Seeking
      • Reading
      • Writing
      • Size
      • Truncate
      • Sync
      • Flush
      • Hash
      • MIME-Type
      • Filename
      • Output
      • Locking
      • Transactions
      • Meta
      • Misc
  • Support

    • Introduction
    • How to install
    • Laravel Aware-of Helpers

      • How to use
      • Enforce Via Interface
      • Custom Default
      • Pros and Cons
      • Available Helpers
    • Aware-of Properties

      • Generator
      • Available Aware-of Helpers
    • Live Templates
  • Testing

    • Introduction
    • How to install
    • Test Cases
    • Testing Aware-of Helpers
  • Translation

    • Introduction
    • How to install
    • Exporters

      • Introduction
      • Setup
      • How to use
      • Drivers

        • Introduction
        • Array
        • Lang.js (Array)
        • Lang.js (JSON)
        • Cache
  • Utils

    • Introduction
    • How to install
    • Array
    • Duration
    • Json
    • Math
    • Memory
    • Method Helper
    • Invoker
    • Populatable
    • String
    • Version
  • Validation

    • Introduction
    • How to install
    • Setup
    • Rules

      • Alpha-Dash-Dot
      • Date Format
      • Semantic Version
You are viewing documentation for an outdated version. It is no longer supported!

Writing

  • Determine if Writable
  • Write
    • Write Formatted
  • Put
    • Put Formatted
  • Append
    • Append Resource
    • Append Stream
  • Copy
    • Copy To Target
    • Copy From

Determine if Writable

The isWritable() determines if a stream is writable or not.

$a = FileStream::open('people.txt', 'r+b');
$b = FileStream::open('contacts.txt', 'rb');

echo $a->isWritable(); // true
echo $b->isWritable(); // false

Write

Use the write() method to write data to the stream.

The method returns amount of bytes written to the stream.

$stream = FileStream::openTemporary();
$bytes = $stream->write('abc');

echo $bytes; // 3

Behind the scene, PHP's fwrite() is used for writing data to the stream.

Write Formatted

If you want to write data using a specific format, then you can use the writeFormatted() method.

The method accepts a $format argument, as specified by PHP's fprintf(), and an arbitrary amount of values.

Similar to write(), this method also returns the amount of bytes written to the stream.

$stream = FileStream::openTemporary();

$greetings = 'Hi there';
$name = 'John';

$bytes = $stream->writeFormatted('%s <<%s>>', $greetings, $name);

echo $bytes; // 16
echo (string) $stream; // Hi there <<John>>

Put

Alternatively, you can use the put() method to write data to a stream. This method is a "fluent" version of write().

$stream = FileStream::openTemporary()
    ->put('a')
    ->put('b')
    ->put('c');

echo (string) $stream; // abc

Put Formatted

putFormatted() is a "fluent" version of the writeFormatted() method.

$stream = FileStream::openTemporary();

$a = 'Hi there';
$b = 'John';
$c = 'Smith'

$stream
    ->putFormatted('%s ', $a)
    ->putFormatted('<<%s ', $b)
    ->putFormatted('%s>>', $c);

echo (string) $stream; // Hi there <<John Smith>>

Append

The append() method is able to add data, at the end of the stream, if the stream is seekable. If the stream is not seekable, then a StreamNotSeekable exception will be thrown.

The method accepts four arguments:

  • $data: Data to be appended.
  • int|null $length: (optional) Maximum bytes to append. By default, all bytes left in $data are appended.
  • int $offset: (optional) The offset where to start to copy data (offset on $data).
  • int|null $maximumMemory: (optional) Maximum amount of bytes, before writing to a temporary file. (Defaults to 2 MB if not specified).

The $maximumMemory argument is relevant when $data is a pure string, or numeric. If that is the case, then the append() method will wrap the $data into a "temporary" stream internally, before reading from it.

$stream = FileStream::open('people.txt', 'r+b')
    ->append("\nJohn");

Behind the scene, PHP's stream_copy_to_stream() is used to append.

Append Resource

To append data from a resource, pass in the resource as the $data argument.

$resource = fopen('contacts.txt', 'r');

$stream = FileStream::open('people.txt', 'r+b')
    ->append($resource);

Append Stream

You may also append directly from another stream.

$from = FileStream::open('contacts.txt', 'r');

$stream = FileStream::open('people.txt', 'r+b')
    ->append($from);

Caution

When pure PSR-7 StreamInterface is appended

If you choose to append from pure "PSR stream" (a stream that inherits from StreamInterface, but not from \Aedart\Contracts\Streams\Stream), then the given "data" stream is automatically detached.

$stream = FileStream::open('people.txt', 'r+b')
    ->append($psrStream);

// Attempt using "psr stream" after it was appended...
$psrStream->rewind(); // Invalid - Exception is thrown

The reason for this behavior is due to the limitation of PSR-7's defined StreamInterface. There is no safe way to obtain a reference to the underlying resource, without detaching it. PHP's native stream_copy_to_stream() can therefore not be applied.

Workaround

See copyFrom().

Copy

In situations when you wish to copy the stream, then you can use the copy() method.

This method will create a new "temporary" stream via openTemporary().

It accepts optional $length and $offset as arguments.

$stream = FileStream::open('my-file.txt', 'r+b')
    ->put('abc')
    ->positionToStart();

$copyA = $stream->copy();
$copyB = $stream
    ->positionToStart()
    ->copy(1, 1);

echo $copyA; // abc
echo $copyB; // b

Note

The initial stream's position is affected by the copy() method.

Behind the scene, PHP's stream_copy_to_stream() is used for the copy operation.

Copy To Target

If you wish to copy a stream into a specific target stream, then use the copyTo() method.

It accepts a $target stream, $length and $offset as optional arguments.

$stream = FileStream::open('my-file.txt', 'r+b')
    ->put('abc')
    ->positionToStart();

$target = FileStream::open('target.txt', 'r+b');
$copy = $stream->copyTo($target, 1, 1);

echo ($copy === $target); // true
echo (string) $copy; // b

Copy From

Available since v7.4.x

Alternatively, you may also copy data from an existing resource or stream.

$target = FileStream::openMemory()
    ->copyFrom($existing);

Similar to the copyTo() method, this method accepts a $source stream, a $length and an $offset argument.

The $source argument accepts the following types:

  • resource
  • \Aedart\Contracts\Streams\Stream
  • \Psr\Http\Message\StreamInterface

PSR-7 Stream

Unlike the copyTo() or append() methods, this method will not detach the underlying resource of the source PSR-7 stream.

$psrStream->rewind();
$target = FileStream::openMemory()
    ->copyFrom($psrStream);

$psrStream->rewind(); // valid - underlying resource is still attached
Edit page
Last Updated: 18/03/2024, 10:45
Contributors: Alin Eugen Deac, alin
Prev
Reading
Next
Size