1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
<?php
/**
* @author Brian Dayhoff <mopsyd@me.com>
* @license http://opensource.org/licenses/MIT The MIT License (MIT)
* @copyright (c) 2014, Brian Dayhoff all rights reserved.
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace oroboros\core\traits\patterns\behavioral;
/**
* <Private Registry Pattern>
* Allows for private values to be declared at runtime,
* and maintain scope with specific traits or classes,
* despite inheritance.
*
* Provides a set of methods to abstract complex,
* scoped private values into a simple dot separated
* naming convention. Works with both arrays as well
* as objects, respecting visibility.
*
* Array or object nesting is represented as a dot
* separated string notation, consistent with other
* languages namespacing such as javascript or MySQL.
* This allows for broader universalization of schema
* represenation without as much one-off parsing logic
* as PHP's internal schema normally allows without
* additional abstraction.
*
* Public facing api's in this system honor standard notation.
* As such, this trait does not provide public methods, and you
* will have to expose them manually if used for
* interactive containerization.
*
* @planned This trait is set up to eventually also support tree search algorithms, though that is not yet implemented.
* @planned The indexing functionality will eventually be separated from the container functionality into it's own trait, which will be used by this one. This should not change the protected or public api when this occurs.
*
* --------
* Traits provide extended method support to classes without requiring a direct,
* linear chain of inheritance. This allows functions to inherit subsets of
* related methods without declaring a parent class.
*
* In Oroboros core, ALL methods are granted to classes via traits,
* and the classes themselves are just containers that correlate their methods
* to an interface they are expected to honor. This approach maximizes
* interoperability, by entirely removing class inheritance as a requirement
* for extension of any class in this system.
*
* 3rd parties using this package are not expected to follow this approach,
* but ALL of our internal class and logic structure does.
* --------
*
* @author Brian Dayhoff <mopsyd@me.com>
* @license http://opensource.org/licenses/MIT The MIT License (MIT)
* @link bitbucket.org/oroborosframework/oroboros-core/wiki/development/api/contract_interface.md
* @category traits
* @package oroboros/core
* @subpackage patterns
* @version 0.2.4-alpha
* @since 0.1.1
*/
trait RegistryTrait
{
/**
* We will get a reference to the initializing instance here,
* so that we can scope separately between traits
* and preserve value privacy.
*/
use \oroboros\core\traits\utilities\logic\BackreferenceTrait;
/**
* Primary container for private registry encapsulation.
* @var array
*/
private $_registry_values = [ ];
/**
* the default registry index separator.
* This will be allowed to be overidden later,
* but that will need a lot of testing.
* @var string
*/
private $_registry_default_index_separator = '.';
/**
* the registry index separator.
* This will be allowed to be overidden later,
* but that will need a lot of testing.
* @var string
*/
private $_registry_index_separator = '.';
/**
* -------------------------------------------------------------------------
* Extension Methods (protected)
*
* These methods may be extended by inheriting constructs as needed.
* They represent the interal api.
* -------------------------------------------------------------------------
*/
/**
* <Registry Index Getter>
* Returns the requested value, defined by dot separated depth notation
* (works with both arrays and objects, so they can be treated interchangably
* with by higher logic without mutating their state).
*
* Implementing classes are expected to know their key structure on request,
* and to not ask for invalid keys. Operation will break with an exception
* if invalid keys are requested. This is a control structure, so if you
* need to handle ambiguity, either handle that locally, or containerize
* it within a scope that tolerates ambiguity internally before registering it).
*
* @example 'classname.dependencies' resolves to $this->_registry_values['\namespace\of\local\scope\ClassOrTrait']['classname']['dependencies']
*
* @param scalar $key The name of the registry key, typically a string. May follow dot separated notation to declare depth.
* @param bool $safe (optional) Prevents overwrites if true. Default false.
* @return bool True if the value was set, false if the old value was retained
* @throws \oroboros\core\utilities\exception\InvalidArgumentException if passed a non-scalar key
* @version 0.2.4-alpha
* @since 0.2.4-alpha
*/
protected function _getRegistryValue( $key = null )
{
$value = $this->_getRegistryValueReference( $key );
$non_referential_value = $value;
return $non_referential_value;
}
/**
* <Reset Registry>
* Sets the localized registry back to an empty state.
* @return void
*/
protected function _resetRegistry()
{
$this->_initializeRegistry( true );
}
/**
* <Registry Fetch>
* Returns the entire localized registry.
* @return array
*/
protected function _fetchRegistry()
{
$localized_index_key = $this->_extractRegistryLocalizedIndex( $this->_getBackReference() );
$localized_index = $this->_registry_values[$localized_index_key];
return $localized_index;
}
/**
* <Registry Value Count>
* Returns a count of the registry keys by dot separated scope.
* If $key is null, returns the entire localized scope.
* @param scalar $key a dot separated key to check the registry for
* @return int|bool returns false if $key is not an array or does not exist, otherwise returns the count of values.
* @throws \oroboros\core\utilities\exception\InvalidArgumentException if a non-scalar key is passed and $key is not null
*/
protected function _countRegistryKeys( $key = null )
{
$this->_initializeRegistry();
if ( !is_null( $key ) && !is_scalar( $key ) )
{
throw new \oroboros\core\utilities\exception\InvalidArgumentException(
sprintf( \oroboros\core\interfaces\api\ExceptionMessageApi::ERROR_LOGIC_BAD_PARAMETERS_MESSAGE,
__METHOD__, 'scalar value', gettype( $key ) ),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_LOGIC_BAD_PARAMETERS );
}
$localized_index_key = $this->_extractRegistryLocalizedIndex( $this->_getBackReference() );
$localized_index = $this->_registry_values[$localized_index_key];
if ( is_null( $key ) )
{
return count( $localized_index );
}
$values = $this->_getRegistryKeyMapping( $localized_index, $key, true );
if ( is_array( $values ) )
{
return count( $values );
}
return false;
}
/**
* <Registry Index By-Reference Getter>
* Returns the specified value from the registry,
* but returns a reference to the original instead of a copy.
* Otherwise this method works identically to _getRegistryValue
*
* This method honors dot separated notation (the dot separator is overrideable)
*
* @example 'classname.dependencies' resolves to $this->_registry_values['\namespace\of\local\scope\ClassOrTrait']['classname']['dependencies']
*
* @param scalar $key The name of the registry key, typically a string. May follow dot separated notation to declare depth.
* @param bool $safe (optional) Prevents overwrites if true. Default false.
* @return bool True if the value was set, false if the old value was retained
* @throws \oroboros\core\utilities\exception\InvalidArgumentException if passed a non-scalar key
* @version 0.2.4-alpha
* @since 0.2.4-alpha
*/
protected function &_getRegistryValueReference( $key = null )
{
$this->_initializeRegistry();
if ( !is_null( $key ) && !is_scalar( $key ) )
{
throw new \oroboros\core\utilities\exception\InvalidArgumentException(
sprintf( \oroboros\core\interfaces\api\ExceptionMessageApi::ERROR_LOGIC_BAD_PARAMETERS_MESSAGE,
__METHOD__, 'scalar value', gettype( $key ) ),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_LOGIC_BAD_PARAMETERS );
}
$localized_index_key = $this->_extractRegistryLocalizedIndex( $this->_getBackReference() );
$localized_index = $this->_registry_values[$localized_index_key];
if ( array_key_exists( $key, $localized_index ) )
{
return $localized_index[$key];
} elseif ( is_null( $key ) )
{
return $localized_index;
}
return $this->_getRegistryKeyMapping( $localized_index, $key, true );
}
/**
* <Registry Index Check Method>
* Returns a boolean determination as to whether a specified
* dot separated key exists in the registry for the current scope.
* @param scalar $key
* @return bool
* @throws \oroboros\core\utilities\exception\InvalidArgumentException
* @final
*/
final protected function _checkRegistryValue( $key )
{
$this->_initializeRegistry();
if ( !is_null( $key ) && !is_scalar( $key ) )
{
throw new \oroboros\core\utilities\exception\InvalidArgumentException(
sprintf( \oroboros\core\interfaces\api\ExceptionMessageApi::ERROR_LOGIC_BAD_PARAMETERS_MESSAGE,
__METHOD__, 'scalar value', gettype( $key ) ),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_LOGIC_BAD_PARAMETERS );
}
$localized_index_key = $this->_extractRegistryLocalizedIndex( $this->_getBackReference() );
$localized_index = $this->_registry_values[$localized_index_key];
return $this->_checkRegistryKeyMapping( $localized_index, $key );
}
/**
* <Registry Index Setter>
* Creates a new key in the registry index
* with an empty container as a value.
*
* Honors dot separated notation, and will create
* all non-existent parent keys leading up to the
* leaf-node key also if they do not exist.
*
* If $safe is true, it will not overwrite an
* existing one of the same key.
*
* The default behavior is to overwrite, just like
* any other variable being directly manipulated.
*
* @param scalar $key The name of the registry key, typically a string. May follow dot separated notation to declare depth.
* @param bool $safe (optional) Prevents overwrites if true. Default false.
* @return bool True if the value was set, false if the old value was retained
* @throws \oroboros\core\utilities\exception\InvalidArgumentException if passed a non-scalar key
* @version 0.2.4-alpha
* @since 0.2.4-alpha
* @final
*/
final protected function _setRegistryValue( $key, $value = array(),
$safe = false )
{
if ( !is_scalar( $key ) )
{
throw new \oroboros\core\utilities\exception\InvalidArgumentException(
sprintf( \oroboros\core\interfaces\api\ExceptionMessageApi::ERROR_LOGIC_BAD_PARAMETERS_MESSAGE,
__METHOD__, 'scalar value', gettype( $key ) ),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_LOGIC_BAD_PARAMETERS );
}
$this->_initializeRegistry();
$localized_index_key = $this->_extractRegistryLocalizedIndex( $this->_getBackReference() );
//exclude existing values if safe flag is passed
if ( !( $safe && $this->_checkRegistryKeyMapping( $this->_registry_values[$localized_index_key],
$key ) ) )
{
$this->_registry_values[$localized_index_key] = $this->_setRegistryKeyMapping( $this->_registry_values[$localized_index_key],
$key, $value );
return true;
}
return false;
}
/**
* Deletes a registry key by dot separated key name.
* @param type $key
* @throws \oroboros\core\utilities\exception\InvalidArgumentException if a non-scalar key is passed
* @version 0.2.4-alpha
* @since 0.2.4-alpha
* @final
*/
final protected function _unsetRegistryIndex( $key )
{
if ( !is_scalar( $key ) )
{
throw new \oroboros\core\utilities\exception\InvalidArgumentException(
sprintf( \oroboros\core\interfaces\api\ExceptionMessageApi::ERROR_LOGIC_BAD_PARAMETERS_MESSAGE,
__METHOD__, 'scalar value', gettype( $key ) ),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_LOGIC_BAD_PARAMETERS );
}
$this->_initializeRegistry();
$localized_index_key = $this->_extractRegistryLocalizedIndex( $this->_getBackReference() );
$this->_registry_values[$localized_index_key] = $this->_deleteRegistryKeyMapping( $this->_registry_values[$localized_index_key],
$key );
}
/**
* Returns the current registry index separator.
* @return string
* @version 0.2.4-alpha
* @since 0.2.4-alpha
* @final
*/
final protected function _getRegistryIndexSeparator()
{
return $this->_registry_index_separator;
}
/**
* Resets the recognized registry index separator to it's default ["."].
* @return void
* @version 0.2.4-alpha
* @since 0.2.4-alpha
* @final
*/
final protected function _resetRegistryIndexSeparator()
{
$this->_registry_index_separator = $this->_registry_default_index_separator;
}
/**
* Sets a new registry index separator value, which can then be used to
* determine index depth in place of the default dot syntax.
* This is provided for compatibility with programming logic
* that is not inherently compatible with the dot syntax,
* so that it may still work interchangeably with the registry.
* @example If you want to represent separation within the system $PATH variable, change the separator to a colon [":"], and then your registry functionality can operate equivalently to the system path notation.
* @param string $separator
* @return void
* @throws \oroboros\core\utilities\exception\InvalidArgumentException If the supplied value is not a string
* @version 0.2.4-alpha
* @since 0.2.4-alpha
*/
protected function _setRegistryIndexSeparator( $separator )
{
//type check for string
if ( !is_string( $separator ) )
{
throw new \oroboros\core\utilities\exception\InvalidArgumentException(
sprintf( \oroboros\core\interfaces\api\ExceptionMessageApi::ERROR_LOGIC_BAD_PARAMETERS_MESSAGE,
__METHOD__, 'string', gettype( $separator ) ),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_LOGIC_BAD_PARAMETERS );
}
$this->_registry_index_separator = $separator;
}
/**
* -------------------------------------------------------------------------
* Logic Methods (private)
*
* These methods are not externally exposed.
* They represent the actual work.
* -------------------------------------------------------------------------
*/
/**
* This must be called to initialize an instance of the registry at
* least one time, so all protected methods in this trait do so.
* The root registry index will be scoped to the fully qualified
* trait or class name that called registration.
* It will only distribute values in scope, maintaining privacy,
* and leaving it to the referencing construct to expose those values
* as needed.
*
* This method may be called redundantly without mutating state.
*
* @return void
* @version 0.2.4-alpha
* @since 0.2.4-alpha
*/
private function _initializeRegistry( $reset = false )
{
$root_index = $this->_extractRegistryLocalizedIndex( $this->_getBackReference() );
if ( !array_key_exists( $root_index, $this->_registry_values ) || $reset )
{
$this->_registry_values[$root_index] = array();
}
}
/**
* Returns the root localized key reference from a supplied fully qualified method name
* @param string $backreference fully qualified method name (eg: \namespace\of\reference\ClassOrTraitName::methodName)
* @return string Returns the fully namespaced reference, without the function name
* @version 0.2.4-alpha
* @since 0.2.4-alpha
*/
private function _extractRegistryLocalizedIndex( $backreference )
{
//chop off the method name, so we can treat this as a private class resource
$tmp = explode( '::', $backreference );
return array_shift( $tmp );
}
/**
* Returns whether a specified index exists or not,
* honoring dot separated index notation.
* @param type $index
* @param type $key
* @return type
* @version 0.2.4-alpha
* @since 0.2.4-alpha
*/
private function _resolveRegistryKeyMapping( $index, $key )
{
$stack = explode( $this->_registry_index_separator, $key );
$next_key = array_shift( $stack );
if ( empty( $stack ) )
{
//resolve the index
return (array_key_exists( $next_key, $index )
? $index[$next_key]
: false );
}
return $this->_resolveRegistryKeyMapping( $index[$next_key],
implode( $this->_registry_index_separator, $stack ) );
}
/**
* Returns a determination as to whether or
* not a key exists in any provided subset, as defined in its dot separated notation
* (or literal representation, if no dos separation occurs)
* @recursive
* @param type $index The array or object to begin the search against.
* @param type $key the key or key tree to isolate
* @return bool true if found, false if not
* @throws \oroboros\core\utilities\exception\LogicException as a redundancy if some specific edge case was not considered. This means the core code needs to be patched if this occurs, and otherwise should never occur.
* @version 0.2.4-alpha
* @since 0.2.4-alpha
*/
private function _checkRegistryKeyMapping( $index, $key )
{
$stack = ( ( strpos( $key, $this->_registry_index_separator ) !== false )
? explode( $this->_registry_index_separator, $key )
: array(
$key ) );
if ( count( $stack ) === 1 )
{
return array_key_exists( $key, $index );
} else
{
$next_key = array_shift( $stack );
if ( array_key_exists( $next_key, $index ) )
{
return $this->_checkRegistryKeyMapping( $index[$next_key],
implode( $this->_registry_index_separator, $stack ) );
}
return false;
}
}
/**
* Returns the specified key from the registry,
* honoring dot separated index depth notation.
* @param array|object $index the specific index of the registry to start searching within
* @param scalar $key the key to identify the value by
* @return mixed a reference to the value within the registry corresponding to the key. Higher visibility methods are responsible for conversion if a return reference is not desireable.
* @throws \oroboros\core\utilities\exception\InvalidArgumentException if the key does not exist in the registry
* @version 0.2.4-alpha
* @since 0.2.4-alpha
*/
private function &_getRegistryKeyMapping( $index, $key = null )
{
if ( is_null( $key ) )
{
return $index;
}
if ( !$this->_checkRegistryKeyMapping( $index, $key ) )
{
//this means there is no value to get
throw new \oroboros\core\utilities\exception\InvalidArgumentException(
sprintf( \oroboros\core\interfaces\api\ExceptionMessageApi::ERROR_PHP_KEY_NOT_FOUND_MESSAGE,
$key, __TRAIT__ ),
\oroboros\core\interfaces\api\ExceptionCodeApi::ERROR_PHP_KEY_NOT_FOUND
);
}
if ( strpos( $key, $this->_registry_index_separator ) )
{
$stack = explode( $this->_registry_index_separator, $key );
$next_key = array_shift( $stack );
return $this->_getRegistryKeyMapping( $index[$next_key],
implode( $this->_registry_index_separator, $stack ) );
}
//find the correct index and return the value
return $index[$key];
}
/**
* Sets a value in the registry by dot notated index reference.
* @param array|object $index A specific index of the registry to match within
* @param scalar $key a key identifier for the value
* @param mixed $value the value to set
* @param bool $safe (optional) if true, will not overwrite existing keys. Default false.
* @return bool if true, the value was set. If false, safe mode was declared and the key already existed, or you tried to set a value in a leaf that can't take one (like a string or integer).
* @version 0.2.4-alpha
* @since 0.2.4-alpha
*/
private function _setRegistryKeyMapping( &$index, $key, $value = array() )
{
$stack = explode( $this->_registry_index_separator, $key );
$next_key = array_shift( $stack );
//Create the value directly if it does not exist, and there are no subkeys
if ( empty( $stack ) )
{
$index[$next_key] = $value;
return $index;
}
$remaining_keys = implode( $this->_registry_index_separator, $stack );
$index[$next_key] = $this->_setRegistryKeyMapping( $index[$next_key],
$remaining_keys, $value );
return $index;
}
/**
* Deletes a key from the registry
* @param type $index
* @param type $key
* @return type
* @version 0.2.4-alpha
* @since 0.2.4-alpha
*/
private function _deleteRegistryKeyMapping( &$index, $key )
{
if ( !$this->_checkRegistryKeyMapping( $index, $key ) )
{
//this means there is no value to delete
return;
}
//find and delete the value
$stack = explode( $this->_registry_index_separator, $key );
$next_key = array_shift( $stack );
if ( empty( $stack ) )
{
unset( $index[$next_key] );
} else
{
return $this->_deleteRegistryKeyMapping( $index[$next_key],
implode( $this->_registry_index_separator, $stack ) );
}
return $index;
}
}