Browse Source

Create DataURL.php

dev
Cerys 1 month ago
parent
commit
1f1cedc550
  1. 97
      src/DataStructures/DataURL.php

97
src/DataStructures/DataURL.php

@ -0,0 +1,97 @@
<?php
namespace Darksparrow\DeegraphInteractions\DataStructures;
class DataURL
{
/**
* If a MIME type is in this array, then the data will just be URL encoded, otherwise it'll be base64 encoded.
* @var array|string[] MIME Types.
*/
public static array $EncodedMIMETypes = [
"text/plain",
"application/json",
];
private ?string $Data = null;
private ?string $MIMEType = null;
public function __construct(string $stringRepresentation)
{
// Trim leading/trailing whitespace
$stringRepresentation = trim($stringRepresentation);
// Validate and process if it's a data URL
if(mb_strpos($stringRepresentation, "data:") !== 0) return;
// Remove the "data:" prefix
$stringRepresentation = mb_substr($stringRepresentation, 5);
if(mb_strpos($stringRepresentation, ",") === false) return;
// Split into header and data parts
$parts = explode(",", $stringRepresentation, 2);
$header = $parts[0];
// Check if the data is Base64-encoded
if(mb_strpos($stringRepresentation, ";base64") === false)
{
// Extract MIME type (up to the ";base64" part) and decode the data
$this->MIMEType = $header;
$this->Data = urldecode($parts[1]);
return;
}
// Data is URL-encoded; set MIME type and decode the data
$this->MIMEType = explode(";", $header, 2)[0];
$this->Data = base64_decode($parts[1]);
}
/**
* Gets the raw data extracted from the data URL.
*
* @return string|null The raw data or null if parsing failed.
*/
public function GetData(): ?string
{
return $this->Data;
}
/**
* Gets the size of the raw data in bytes.
*
* @return int The size of the data, or 0 if data is null.
*/
public function GetSize(): int
{
return $this->Data ? strlen($this->Data) : 0;
}
/**
* Gets the MIME type of the data URL.
*
* @return string|null The MIME type or null if parsing failed.
*/
public function GetMimeType(): ?string
{
return $this->MIMEType;
}
/**
* Converts the object back to a valid data URL string.
*
* @return string The reconstructed data URL.
*/
public function __toString()
{
// If data or MIME type is missing, return an empty string
if (!$this->Data || !$this->MIMEType) return '';
// Encode based on the MIME type
if (in_array($this->MIMEType, self::$EncodedMIMETypes))
return "data:{$this->MIMEType}," . urlencode($this->Data);
// Base64-encode all other data
return "data:{$this->MIMEType};base64," . base64_encode($this->Data);
}
}
Loading…
Cancel
Save