Bz2 Chilkat2 PHP Reference Documentation
Bz2
Current Version: 11.7.0
Markdown version of this page for AI tools (v 11.7.0) · all AI docs
Chilkat.Bz2 provides BZip2 compression and decompression for files, memory buffers, and BinData. It can create standard .bz2 file images, decompress .bz2 content back to its original bytes, and support abortable long-running operations.
For an extended overview, see Bz2 Class Overview
Object Creation
use Chilkat2\Bz2;
try {
$bz2 = new Bz2();
// ... use $bz2 ...
} catch (\Chilkat2\Exception $e) {
echo $e->getClass(), '::', $e->getMethod(), " failed\n";
echo $e->getMessage(), "\n"; // the LastErrorText of the failed call
}Creates the object. The optional array sets properties in order, as if assigned one by one (new Bz2(['VerboseLogging' => true, 'RaiseError' => false])); an unknown or read-only name throws Error. The class is defined by the chilkat2 extension (extension=chilkat2 in php.ini): there is no PHP file to include.
There is no close(): PHP frees the object when its last reference goes (unset($bz2), $bz2 = null, or the end of the function or request). Objects returned by methods are independent and freed the same way. The class may be extended (class MyBz2 extends \Chilkat2\Bz2); objects cannot be cloned or serialized.
When true (the default), a method that fails throws Chilkat2\Exception. When false, it returns false (or null) instead, and the reason is in LastErrorText. Objects returned by a method inherit the value of the object that returned them.
Errors
Chilkat2\Exception extends RuntimeException: getMessage() is the failed call's full LastErrorText, getClass() its class ('Chilkat2\Bz2') and getMethod() the method name. The object remains usable. Methods that look something up and find nothing return null without throwing (each such method says so), methods that answer a question (HasMember, IsUnlocked, ...) return a plain bool, and property reads and writes do not throw for Chilkat reasons.
Misuse always throws, whatever RaiseError is: a wrong argument type is a TypeError (exact types under declare(strict_types=1)), a missing or extra argument an ArgumentCountError, a string containing a NUL byte or an out-of-range integer a ValueError, and an unknown property (properties are case-sensitive) or a write to a read-only one an Error. Named arguments work with the parameter names shown.
Strings are passed and returned as UTF-8; binary data is a PHP string of bytes. Unlocking: call (new \Chilkat2\GlobalSettings())->UnlockBundle('...') once at startup.
Properties
AbortCurrent
Set this property to to request cancellation of the compression or decompression operation currently executing on this object. Long-running operations check the request periodically; an operation that finishes quickly may complete before the request is observed.true
A synchronous call can be cancelled by setting this property from another thread. After cancellation is processed, Chilkat resets the property to . If no operation is running, a previously set value is cleared when the next method begins.false
LastErrorText to determine the final outcome.DebugLogFilePath
If set to a file path, this property logs the LastErrorText of each Chilkat method or property call to the specified file. This logging helps identify the context and history of Chilkat calls leading up to any crash or hang, aiding in debugging.
Enabling the VerboseLogging property provides more detailed information. This property is mainly used for debugging rare instances where a Chilkat method call causes a hang or crash, which should generally not happen.
Possible causes of hangs include:
- A timeout property set to 0, indicating an infinite timeout.
- A hang occurring within an event callback in the application code.
- An internal bug in the Chilkat code causing the hang.
HeartbeatMs
Specifies the interval, in milliseconds, between AbortCheck event callbacks during supported long-running compression and decompression operations. The default is 0, which disables AbortCheck callbacks.
Set a positive value, such as 200, when the application needs periodic opportunities to request cancellation. The interval is approximate; callbacks occur only while an operation is at a point where progress events can be delivered.
AbortCheck handler, set the callback's abort value to request termination. A synchronous method may also be cancelled from another thread by setting AbortCurrent to true.LastErrorHtml
Provides HTML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
topLastErrorText
Provides plain text information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
LastErrorXml
Provides XML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
topLastMethodSuccess
Indicates the success or failure of the most recent method call: true means success, false means failure. This property remains unchanged by property setters or getters. This method is present to address challenges in checking for null or Nothing returns in certain programming languages. Note: This property does not apply to methods that return integer values or to boolean-returning methods where the boolean does not indicate success or failure.
VerboseLogging
If set to true, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. The default value is false. Verbose logging should only be used for debugging. The potentially large quantity of logged information may adversely affect peformance.
Version
Methods
CompressBd
Compresses the current contents of $bd in place. On success, the BinData no longer contains the original bytes; it contains the complete standard BZip2 stream that may be saved with a .bz2 extension.
Returns true on success. On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns false). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.
CompressFile
Reads the file at $inFilename and writes its compressed bytes as a standard BZip2 stream to the file at $toPath. The output is conventionally given a .bz2 extension.
Both arguments must identify files, not directories. They may be absolute or relative paths, for example data/report.txt and data/report.txt.bz2.
.bz2 file represents one compressed byte stream. It does not store the original filename, directory path, timestamps, permissions, or multiple archive entries. Formats such as .tar.bz2 first combine files in a TAR archive and then compress that TAR stream with BZip2.Returns true on success. On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns false). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.
UncompressBd
Decompresses the BZip2 stream currently contained in $bd in place. On success, the BinData is replaced with the original uncompressed bytes.
$bd must contain a complete, valid BZip2 stream, such as the bytes of a .bz2 file or the output of CompressBd. This method operates on binary data and does not perform character-set conversion.Returns true on success. On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns false). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.
UncompressFile
Reads the BZip2 stream from the file at $inFilename, decompresses it, and writes the original uncompressed bytes to the file at $toPath.
Both arguments must identify files, not directories. Chilkat does not derive the destination name from the .bz2 filename because the BZip2 stream does not contain the original filename.
.bz2 file normally contains a single compressed byte stream rather than a collection of named files.Returns true on success. On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns false). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.
Events
All Chilkat methods are synchronous: the call returns when the work is done. During a long-running call, Bz2 reports progress to handlers installed with three methods, each taking any PHP callable (a closure, an arrow function, $this->method(...), an invokable object) and returning the object, so the calls chain:
$bz2->onPercentDone(function (int $pctDone): bool {
echo "$pctDone%\n";
return false; // return true to abort the method in progress
})
->onProgressInfo(function (string $name, string $value): void {
echo "$name: $value\n";
});
$bz2->HeartbeatMs = 250; // the AbortCheck handler is called 4 times per secondEach installs the handler for one event, replacing the one installed before; null removes it. A callable that does not exist is a TypeError right away.
The AbortCheck handler is called at the interval set by the HeartbeatMs property (0, the default, disables it); PercentDone is called when an operation's completion percentage is known; ProgressInfo delivers named progress values. A truthy return from the AbortCheck or PercentDone handler aborts the running method, which then fails in the usual way (Chilkat2\Exception, or false / null with RaiseError off). PHP's set_time_limit() does not interrupt a Chilkat call; an AbortCheck handler is how a script enforces its own limit.
Handlers run during the method call, in the same request. Inside a handler, the object's properties (such as $bz2->AbortCurrent = true) and other objects may be used, but calling a method of the same object throws Error. An exception thrown by a handler aborts the running method and propagates from it; the object remains usable. A closure that captures $bz2 itself makes a reference cycle, which PHP's cycle collector frees.
AbortCheck
public function onAbortCheck(?callable $callback): static
Enables a method call to be aborted by triggering the AbortCheck event at intervals defined by the HeartbeatMs property. If HeartbeatMs is set to its default value of 0, no events will occur. For instance, set HeartbeatMs to 200 to trigger 5 AbortCheck events per second.
Example
$deadline = microtime(true) + 30; // give up after 30 seconds
$bz2->HeartbeatMs = 250; // call the handler 4 times per second
$bz2->onAbortCheck(fn(): bool => microtime(true) > $deadline);PercentDone
public function onPercentDone(?callable $callback): static
This provides the percentage completion for any method involving network communications or time-consuming processing, assuming the progress can be measured as a percentage. This event is triggered only when it's possible and logical to express the operation's progress as a percentage. The pctDone argument will range from 1 to 100. For methods that finish quickly, the number of PercentDone callbacks may vary, but the final callback will have pctDone equal to 100. For longer operations, callbacks will not exceed one per percentage point (e.g., 1, 2, 3, ..., 98, 99, 100).
The PercentDone callback also acts as an AbortCheck event. For fast methods where PercentDone fires, an AbortCheck event may not trigger since the PercentDone callback already provides an opportunity to abort. For longer operations, where time between PercentDone callbacks is extended, AbortCheck callbacks enable more responsive operation termination.
To abort the operation, set the abort output argument to true. This will cause the method to terminate and return a failure status or corresponding failure value.
Example
$bz2->onPercentDone(function (int $pctDone): bool {
// $pctDone ranges from 0 to 100.
echo "Percent done: $pctDone\n";
return false; // return true to abort the method in progress
});ProgressInfo
public function onProgressInfo(?callable $callback): static
This event callback provides tag name/value pairs that detail what occurs during a method call. To discover existing tag names, create code to handle the event, emit the pairs, and review them. Most tag names are self-explanatory.
Note: Some Chilkat methods don't fire any ProgressInfo events.
Example
$bz2->onProgressInfo(function (string $name, string $value): void {
echo "$name: $value\n";
});