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
<?php
/*
* The MIT License
*
* @author Brian Dayhoff <mopsyd@me.com>
* @copyright (c) 2017, Brian Dayhoff <mopsyd@me.com> all rights reserved.
* @license http://opensource.org/licenses/MIT The MIT License (MIT)
*
* 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\utilities\logic;
/**
* <Backreference Trait>
* Provides a simple means for a trait to get a reference to another trait method
* that called it, providing the fully qualified method name one level up the
* stack from the calling method, so it can determine it's caller.
* --------
* 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 contract-interfaces
* @package oroboros/core
* @subpackage utilities
* @version 0.2.4
* @since 0.2.4-alpha
*/
trait BackreferenceTrait
{
/**
* -------------------------------------------------------------------------
* Extension Methods (protected)
*
* These methods may be extended by inheriting constructs as needed.
* They represent the interal api.
*
* @example
* class foo {
*
* use \oroboros\core\traits\utilities\BackReferenceTrait;
*
* public function whoCalledMe() {
* return $this->_getBackReference();
* }
*
* }
*
* //displays false
* $foo = new foo();
* var_dump($foo->whoCalledMe);
*
* @example
* //displays '\bar'
* function bar() {
* return new foo()->whoCalledMe();
* }
*
* var_dump(bar());
*
* @example
* //It also finds traits directly.
* trait baz
* {
* public function quux()
* {
* return new foo()->whoCalledMe();
* }
* }
* class foobar
* {
* use baz;
* }
*
* //displays '\baz::quux'
* var_dump( new foobar()->quux() );
*
* -------------------------------------------------------------------------
*/
/**
* Returns the accurate, immediate backreference of one prior level of the
* stack up from wherever it was called, honoring inheritance and trait
* definitions that were not overridden within a class.
* @return string|bool Returns false if backreference is a global call. Otherwise returns the fully qualified method or function declaration, from the class or trait that declared it.
*/
protected function _getBackReference()
{
$backtrace = debug_backtrace();
//This takes care of an invalid stack
if ( !array_key_exists( 2, $backtrace ) )
{
return false;
}
$reference = $backtrace[2];
//$reflector_caller = $this->_getBackReferenceTraceReferenceReflector( $backtrace[1] );
$reflector_reference = $this->_getBackReferenceTraceReferenceReflector( $backtrace[2] );
unset( $backtrace );
//This takes care of procedural functions, namespaced or otherwise.
if ( $reflector_reference instanceof \ReflectionFunction )
{
//not a class, return the literal
return '\\' . $reflector_reference->name;
}
return $this->_findBackReferenceRealInheritanceLocation( $reflector_reference,
$reference );
}
/**
* -------------------------------------------------------------------------
* Logic Methods (private)
*
* These methods are not externally exposed.
* They represent the actual work.
* -------------------------------------------------------------------------
*/
private function _getBackReferenceTraceReferenceReflector( array $reference )
{
//Figure out whether this is a global
//function and whether or not it is namespaced.
$has_class = isset( $reference['class'] );
$has_function = isset( $reference['function'] );
$has_namespace = isset( $reference['namespace'] );
//we cannot reflect a global command,
//which can happen if _getBackReference
//was called from a public method.
if ( !$has_class && !$has_function )
{
return false;
}
//construct the prefix.
$prefix = '\\' . (($has_namespace)
? $reference['namespace'] . '\\'
: null ) . (($has_class)
? $reference['class'] . '::'
: null);
if ( $has_class )
{
$reflector = new \ReflectionMethod( $prefix . $reference['function'] );
} else
{
$reflector = new \ReflectionFunction( $prefix . $reference['function'] );
}
return $reflector;
}
private function _findBackReferenceRealInheritanceLocation( \ReflectionFunctionAbstract $reflector,
array $reference )
{
$expected_class = '\\' . $reflector->class;
$traits = $this->_getBackReferenceMatchingTraits( $reflector );
$traits_match = array();
foreach ( $traits as
$trait )
{
if ( !method_exists( $trait, $reflector->name ) )
{
continue;
}
$traits_match[] = new \ReflectionMethod( '\\' . $trait . '::' . $reflector->name );
}
if ( empty( $traits_match ) )
{
//no traits have this method, it has to be from the provided class.
return '\\' . $reflector->class . '::' . $reflector->name;
}
//this will filter it down to one possibility,
//if there are multiple declarations of the
//same function within inherited traits.
if ( count( $traits_match ) > 1 )
{
//filter for trait inheritance
$top_level_traits = array();
foreach ( $traits_match as
$trait_valid )
{
$top_level_traits = array_merge( $top_level_traits,
$this->_filterBackReferenceTraitInheritance( $trait_valid,
$traits_match ) );
}
}
//We know it is not possible to have more than one result now,
//because otherwise it would cause a fatal error at compile time
//due to ambiguous inheritance of a method between the class are
//evaluating against and multiple traits (double diamond of death).
$check_trait = array_shift( $traits_match );
//Here we have two options.
//One is to analyze the file contents of the
//class and specifically check for the existence
//of function ${function_name}. This is more exact,
//but also a pretty heavy operation, and this needs
//to remain lightweight.
//
//So instead we are going to make an assumption that the class and
//the filename have the same text, and that the namespace (if provided)
//also reflects the class file path, as is typical with Psr-0 and Psr-4.
//This will reflect in the doc block to clarify also, because we cannot
//justify the overhead of scraping the whole filesystem every time this
//is used.
//It SHOULD be possible to scrape the file directly, to make this
//also compatible with nonstandard projects, but that will incur
//some performance impact in that case, and is better avoided if
//ossible during normal production. The file utility will need
//to be completed before this.
$class_scrape = false; //This is a placeholder for optionally allowing sanity checks against the literal files, which is too slow for normal runtime operation. Do not remove. See todo below.
if ( !$class_scrape )
{
//Compare class reflectors to get the file paths,
//and see if they correspond to the namespace and/or
//filename.
$reflector_class_literal = new \ReflectionClass( $reference['class'] );
//if true, it's the trait. If false, it's the class.
if ( strpos( $check_trait->getFileName(),
$this->_convertBackReferenceNameSpaceToRelativeFilePath( $check_trait->class ) ) !==
false )
{
return '\\' . $check_trait->class . '::' . $check_trait->name;
}
return '\\' . $check_trait->class . '::' . $check_trait->name;
} else
{
/**
* @todo We will abstract this out better with a opt-flag to scrape verbosely at request discretion at a later time.
*/
//This code will never be reached under the current build.
//Very near future releases will use this block,
//so it's a placeholder for expected functionality.
//Do not factor this out.
d( $reference['file'], $reference );
d( $top_level_traits, $traits_match, $reflector, $expected_class,
$traits, $reference['function'], count( $traits_match ) );
exit;
}
}
/**
* Will check if a reflector uses traits recursively
* through all levels of inheritance.
* @param \ReflectionFunctionAbstract $trait
*/
private function _getBackReferenceMatchingTraits( \ReflectionFunctionAbstract $instance )
{
$traits = class_uses( '\\' . $instance->class );
foreach ( $traits as
$trait )
{
if ( !method_exists( $trait, $instance->name ) )
{
//This trait does not inherit the specified method,
//and we can also rule out any that it uses on
//account of this.
continue;
}
$reflector = new \ReflectionMethod( '\\' . $trait . '::' . $instance->name );
$traits = array_merge( $traits,
$this->_getBackReferenceMatchingTraits( $reflector ) );
}
return $traits;
}
private function _filterBackReferenceTraitInheritance( \ReflectionFunctionAbstract $trait,
array &$traits )
{
//remove the current trait from the array
foreach ( $traits as
$key =>
$match )
{
if ( $match->class === $trait->class )
{
continue;
}
if ( in_array( $match->class, class_uses( $trait->class ) ) )
{
//our target inherits this trait,
//so it takes precedence.
//We can remove this one.
unset( $traits[$key] );
}
if ( empty( $traits ) )
{
//the instance is the only match.
return array(
$trait );
}
return $traits;
}
}
private function _convertBackReferenceNameSpaceToRelativeFilePath( $class )
{
$class_bits = explode( '\\', $class );
if ( count( $class_bits ) > 2 )
{
//trim the vendor level namespace
array_shift( $class_bits );
//This covers front controller classes that represent
//the package name by the same classname
if ( count( $class_bits ) > 1 )
{
//trim the package level namespace
array_shift( $class_bits );
}
}
$path = DIRECTORY_SEPARATOR . implode( DIRECTORY_SEPARATOR, $class_bits ) . '.php';
return $path;
}
}