Oihana PHP

MakeFileOptions extends Options

Enumeration class that defines various options to use in the makeFile function.

Tags
author

Marc Alcaraz (ekameleon)

since
1.0.0

Table of Contents

Properties

$append  : bool
If true, appends content instead of overwriting. Default: false.
$content  : string|null
The content of the robots.txt file.
$file  : string|null
Set the robots.txt file path.
$force  : bool
If true, creates parent directories if they do not exist. Default: true.
$group  : string|null
Set the group of the file.
$lock  : bool
If true, creates parent directories if they do not exist. Default: true.
$overwrite  : bool|null
If true, overwrites existing files. Default: true.
$owner  : string|null
Set the owner of the file.
$permissions  : int|null
File permissions to set (octal). Default: 0644.

Methods

__construct()  : mixed
Initializes the object using an associative array or object.
__toString()  : string
Returns the string expression of the object.
clone()  : static
Creates a deep copy of the current instance.
create()  : static
Instantiates the class from an array or another Options instance.
format()  : string|null
Formats a template string by replacing placeholders like `{{property}}` with the corresponding public property values of the current object.
formatArray()  : array<string|int, mixed>
Recursively formats all string values in an array using internal or external values.
formatFromDocument()  : void
Formats all public string properties using external data instead of internal values.
getOptions()  : string
Returns a string representing the current options formatted as CLI arguments.
jsonSerialize()  : object
Returns data to be serialized by json_encode().
resolve()  : static
Resolves options by merging multiple configuration sources.
toArray()  : array<string, mixed>
Converts the current object to an associative array.

Properties

$append

If true, appends content instead of overwriting. Default: false.

public bool $append = false

$content

The content of the robots.txt file.

public string|null $content

$force

If true, creates parent directories if they do not exist. Default: true.

public bool $force = true

$lock

If true, creates parent directories if they do not exist. Default: true.

public bool $lock = true

$overwrite

If true, overwrites existing files. Default: true.

public bool|null $overwrite = true

$permissions

File permissions to set (octal). Default: 0644.

public int|null $permissions = null

Methods

__construct()

Initializes the object using an associative array or object.

public __construct([array<string|int, mixed>|object|null $init = null ]) : mixed

Only public properties declared on the class will be set. Unknown or non-public properties are silently ignored.

Parameters
$init : array<string|int, mixed>|object|null = null

Initial values to populate the instance.

__toString()

Returns the string expression of the object.

public __toString() : string
Return values
string

clone()

Creates a deep copy of the current instance.

public clone() : static

This performs a full deep copy by serializing and unserializing the object. Useful when duplicating options to avoid shared references.

Return values
static

A new cloned instance.

create()

Instantiates the class from an array or another Options instance.

public static create([array<string|int, mixed>|Options|null $options = null ]) : static
  • If $options is an array, it is passed to the constructor.
  • If $options is already an Options instance, it is returned as-is.
  • If null, a new empty instance is returned.
Parameters
$options : array<string|int, mixed>|Options|null = null

The initial values or existing options instance.

Return values
static

A new or reused instance of the called class.

format()

Formats a template string by replacing placeholders like `{{property}}` with the corresponding public property values of the current object.

public format([string|null $template = null ][, string $prefix = '{{' ][, string $suffix = '}}' ][, string|null $pattern = null ]) : string|null

Supports custom placeholder delimiters. If a referenced property is not defined or is null, it is replaced with an empty string.

Parameters
$template : string|null = null

The template string. Placeholders must match the format {{property}} or a custom format.

$prefix : string = '{{'

The prefix that begins a placeholder (default: {{).

$suffix : string = '}}'

The suffix that ends a placeholder (default: }}).

$pattern : string|null = null

Optional full regex pattern to match placeholders (including delimiters).

Tags
throws
ReflectionException
example
$opts = new ServerOptions();
$opts->domain    = 'example.com';
$opts->subdomain = 'www';

echo $opts->format('https://{{subdomain}}.{{domain}}');
// → https://www.example.com

echo $opts->format('Hello %%domain%%!', '%%', '%%');
// → Hello example.com!

echo $opts->format('Missing: {{nonexistent}}');
// → Missing:
Return values
string|null

The formatted string, or null if the template is invalid.

formatArray()

Recursively formats all string values in an array using internal or external values.

public formatArray(array<string|int, mixed> &$data[, array<string|int, mixed>|object|null $source = null ][, string $prefix = '{{' ][, string $suffix = '}}' ][, string $separator = '.' ][, string|null $pattern = null ]) : array<string|int, mixed>
  • If $source is null, the object itself is used as the placeholder provider (via $this->format()).
  • If $source is provided (array or object), it is used via formatFromDocument().
Parameters
$data : array<string|int, mixed>

The input array to be formatted (by reference).

$source : array<string|int, mixed>|object|null = null

External document used to resolve placeholders. If null, use $this.

$prefix : string = '{{'

Placeholder prefix (default {{).

$suffix : string = '}}'

Placeholder suffix (default }}).

$separator : string = '.'

Separator used in keys (default .).

$pattern : string|null = null

Optional custom placeholder regex.

Tags
example
$opts = new class(['host' => 'example.com', 'apiVersion' => 'v1']) extends Options
{
    public string $host;
    public string $apiVersion;
};

$payload = [
    'base' => 'https://{{host}}/api/{{apiVersion}}',
    'endpoints' => [
        'users' => 'https://{{host}}/api/{{apiVersion}}/users',
        'auth'  => 'https://{{host}}/api/{{apiVersion}}/auth'
    ],
    'unchanged' => 42
];

$opts->formatArray($payload);

// $payload now equals:
// [
//   'base' => 'https://example.com/api/v1',
//   'endpoints' => [
//       'users' => 'https://example.com/api/v1/users',
//       'auth'  => 'https://example.com/api/v1/auth'
//   ],
//   'unchanged' => 42
// ]
Return values
array<string|int, mixed>

The formatted array.

formatFromDocument()

Formats all public string properties using external data instead of internal values.

public formatFromDocument(array<string|int, mixed>|object $document[, string $prefix = '{{' ][, string $suffix = '}}' ]) : void
Parameters
$document : array<string|int, mixed>|object

Associative array or an object of placeholder values.

$prefix : string = '{{'

Placeholder prefix (default {{).

$suffix : string = '}}'

Placeholder suffix (default }}).

Tags
throws
ReflectionException
example
$opts->url = 'https://{{host}}/{{path}}';
$opts->formatFromDocument(['host' => 'example.com', 'path' => 'docs']);
echo $opts->url; // → https://example.com/docs

getOptions()

Returns a string representing the current options formatted as CLI arguments.

public getOptions([class-string $clazz = null ][, null|callable|string $prefix = Char::DOUBLE_HYPHEN ][, array<string|int, string> $excludes = null ][, callable|string $separator = Char::SPACE ][, array<string|int, string> $order = null ][, bool $reverseOrder = false ]) : string

This method converts the properties of the current options object into a list of command-line arguments, using a configurable prefix and separator for each property.

You can pass a string or a callable to dynamically generate prefixes or separators based on the property name.

Parameters
$clazz : class-string = null

Class implementing the getCommandOption(string $property): string method.

$prefix : null|callable|string = Char::DOUBLE_HYPHEN

Prefix for each option (e.g. '--', '-', '/opt:'), or a callable (string $property): string.

$excludes : array<string|int, string> = null

Optional list of property names to exclude from the output.

$separator : callable|string = Char::SPACE

Separator between option and value (default is a space), or a callable (string $property): string.

$order : array<string|int, string> = null

Optional list of property names to force order.

$reverseOrder : bool = false

If true, ordered properties are placed at the end instead of the beginning.

Tags
throws
ReflectionException
example
class MyOption extends Option
{
    public const string FOO     = 'foo' ;
    public const string LIST    = 'list' ;
    public const string VERBOSE = 'verbose' ;
}

class MyOptions extends Options
{
    public string $foo     = 'value';
    public bool   $verbose = true;
    public array  $list    = ['a', 'b'];

    public string $internalFlag = 'hello' ;
}

$options = new MyOptions();

$result = $options->getOptions
(
    MyOption::class ,
    prefix : fn( string $name ) => match($name)
   {
        MyOption::FOO     => '--' ,
        MyOption::VERBOSE => '-' ,
        MyOption::LIST    => '/opt:' ,
        default           => '' ,
    },
    excludes : [ 'internalFlag' ] ,
    separator : fn( string $name ) => $name === 'list' ? '=' : ' '
);

echo $result;
// Output:
// --foo "value" -verbose /opt:list="a" /opt:list="b"

Use the order parameter :

$options->getOptions
(
   MyOption::class,
   prefix: fn($name) => match ($name)
   {
      'foo' => '--',
      'verbose' => '-',
       default => '/opt:'
   },
   excludes  : ['internal'],
   separator : fn($name) => $name === 'list' ? '=' : ' ',
   order: ['verbose', 'foo'],
   reverseOrder: false // Place these first
);
Return values
string

CLI-formatted options string, e.g. '--foo "bar" -v --list "one" --list "two"'

jsonSerialize()

Returns data to be serialized by json_encode().

public jsonSerialize() : object

This implementation converts the cleaned public properties of the object to an object representation, ensuring that json_encode always returns a JSON object (e.g. } instead of [] when empty).

Tags
throws
ReflectionException
example
example
$options = new ServerOptions
([
    'host' => 'localhost',
    'port' => 8080,
    'debug' => null,
]);

echo json_encode($options);
// → {"host":"localhost","port":8080}

$options = new ServerOptions([ 'host' => '' , 'debug' => null ]);

echo json_encode($options); // → }
Return values
object

An object representing the public non-empty properties.

resolve()

Resolves options by merging multiple configuration sources.

public static resolve(mixed ...$sources) : static

This method accepts multiple sources of configuration and merges them in order to create a final options object.

Sources can be:

  • Associative arrays
  • Options classes, and generally ClearableArrayable or Arrayable classes ( which will be converted to arrays via toArray() ).
  • null values (which will be ignored).

The sources are merged in the order they are provided, with later sources overriding earlier ones for conflicting keys.

Parameters
$sources : mixed

Variable number of configuration sources. Each can be an array, Options instance, or null.

Tags
throws
InvalidArgumentException

If a source is not a valid type.

example
// Merge multiple arrays
$options = MyOptions::resolve
(
    [ 'host' => 'localhost', 'port' => 8080],
    [ 'debug' => true ],
    [ 'port' => 9000  ] // This will override the previous port value
);

// Merge arrays and Options instances
$defaultOptions = new MyOptions( ['host' => 'localhost'] ) ;
$userOptions    = ['port' => 8080 , 'debug' => true ] ;
$overrides      = new MyOptions( [ 'debug' => false ] ) ;

$finalOptions = MyOptions::resolve( $defaultOptions , $userOptions , $overrides ) ;
Return values
static

An instance of the calling Options class with merged configuration.

toArray()

Converts the current object to an associative array.

public toArray([bool $clear = false ]) : array<string, mixed>

Only public properties defined on the class are included. Useful for serialization, debugging, or exporting the object state.

Parameters
$clear : bool = false

If true, removes entries with null values. Default: false.

Tags
throws
ReflectionException
example
$options = new ServerOptions([
    'host' => 'localhost',
    'port' => 8080,
    'debug' => null,
    'empty' => '',
    'values' => [],
]);

print_r($options->toArray());
// → [ 'host' => 'localhost', 'port' => 8080, 'debug' => null , 'empty' => '' , 'values' => [] ]

print_r($options->toArray(true));
// → [ 'host' => 'localhost', 'port' => 8080 ]
Return values
array<string, mixed>

The associative array representation of the object.


        
On this page

Search results