Locates original location of closures.

@param mixed $reference File or class name to inspect.
@param integer $callLine Line number of class reference.
@return mixed Returns the line number where the method called is defined.
437917
protected static function _definition($reference, $callLine) {
		if (file_exists($reference)) {
			foreach (array_reverse(token_get_all(file_get_contents($reference))) as $token) {
				if (!is_array($token) || $token[2] > $callLine) {
					continue;
				}
				if ($token[0] === T_FUNCTION) {
					return $token[2];
				}
			}
			return;
		}
		list($class,) = explode('::', $reference);

		if (!class_exists($class)) {
			return;
		}

		$classRef = new ReflectionClass($class);
		$methodInfo = Inspector::info($reference);
		$methodDef = join("\n", Inspector::lines($classRef->getFileName(), range(
			$methodInfo['start'] + 1, $methodInfo['end'] - 1
		)));

		foreach (array_reverse(token_get_all("<?php {$methodDef} ?>")) as $token) {
			if (!is_array($token) || $token[2] > $callLine) {
				continue;
			}
			if ($token[0] === T_FUNCTION) {
				return $token[2] + $methodInfo['start'];
			}
		}
	}
389315
private function resolve(Reference $reference, $class)
    {
        $result = $reference;

        do {
            $refString = (string) $reference->getMergedUri();
            $result = $result->resolve(function ($data) use ($result, $class) {
                return $this->denormalizer->denormalize($data, $class, 'json', [
                    'document-origin' => (string) $result->getMergedUri()->withFragment(''),
                ]);
            });
        } while ($result instanceof Reference);

        return [$refString, $result];
    }
631606
private function parseRefAsPull($reference): ?string
    {
        if (preg_match(self::REGEX_PULL, $reference, $matches) !== 1) {
            return null;
        }

        return $matches[1];
    }
945897
public static function backtrace($trace = null)
	{
		$trace or $trace = debug_backtrace();

		if (\Fuel::$is_cli) {
			// Special case for CLI since the var_dump of a backtrace is of little use.
			$str = '';
			foreach ($trace as $i => $frame)
			{
				$line = "#$i\t";

				if ( ! isset($frame['file']))
				{
					$line .= "[internal function]";
				}
				else
				{
					$line .= $frame['file'] . ":" . $frame['line'];
				}

				$line .= "\t";

				if (isset($frame['function']))
				{
					if (isset($frame['class']))
					{
						$line .= $frame['class'] . '::';
					}

					$line .= $frame['function'] . "()";
				}

				$str .= $line . "\n";

			}

			return $str;
		}
		else
		{
			return static::dump($trace);
		}
	}
788846
public function getByReferenceCallArguments($callNode)
    {
        $byReferenceArguments = $callNode->args;
        if (!$this->calleeReflector->supports($callNode)) {
            return $byReferenceArguments;
        }

        $reflection = $this->calleeReflector->reflect($callNode);
        $byReferenceParameterPositions = array_flip($reflection->getByReferenceParameterPositions());
        $byReferenceArguments = array_intersect_key($byReferenceArguments, $byReferenceParameterPositions);

        return $byReferenceArguments;
    }
100579
public function logReference($type, $ref, $oldRef = null, $method = null, $line = null)
    {
        if (self::getConfig('log', 'reference') || self::getConfig('log', $type . 'Ref')) {
            switch ($type) {
                case 'replace':
                    $this->logMessage('REPLACE REF', 'Replacing Reference From "' . $oldRef . '" to "' . $ref . '"', $method, $line);
                    break;
                case 'load':
                    $this->logMessage('LOAD REF', 'Loading Reference : "' . $ref . '"', $method, $line);
                    break;
                case 'register':
                    $this->logMessage('REGISTER REF', 'Registier Reference Definition : "' . $ref . '"', $method, $line);
                    break;
                case 'drop':
                    $this->logMessage('DROP REF', 'Drop Reference : "' . $ref . '"', $method, $line);
                    break;
            }
        }
    }
634479
public function createReference($reference, Closure $callable, array $parameters = [], $shared = false)
    {
        $reference = $this->mapReference($reference);

        $this[$reference] =
            ($shared) ? static::share($callable) : static::protect($callable);

        return $this[$reference];
    }
622941
public static function getKey($callable)
    {
        /** @var string|null $class */
        $class = null;
        /** @var string|null $method */
        $method = null;

        if (is_string($callable)) {
            $method = $callable; // works for 'Cls::method' case as well
        } elseif (is_array($callable)) {
            $class = is_object($callable[0]) ? get_class($callable[0]) : $callable[0];
            $method = $callable[1];
        } elseif (is_object($callable)) {
            if ($callable instanceof \ReflectionFunctionAbstract) {
                if ($callable->isClosure()) {
                    return null;
                }

                $class = $callable instanceof \ReflectionMethod ? $callable->class : null;
                $method = $callable->name;
            } else {
                if ($callable instanceof \Closure) {
                    return null;
                }

                $class = get_class($callable);
                $method = '__invoke';
            }
        }

        return strtolower(($class ? $class . '::' : '') . $method);
    }
883073
public function getFilter(): Closure
    {
        $rootDirectory = $this->rootDirectory;
        $includePaths = $this->includePaths;
        $excludePaths = $this->excludePaths;

        return function (SplFileInfo $file) use ($rootDirectory, $includePaths, $excludePaths) {

            if ($file->getExtension() !== 'php') {
                return false;
            }

            $fullPath = $this->getFileFullPath($file);
            // Do not touch files that not under rootDirectory
            if (strpos($fullPath, $rootDirectory) !== 0) {
                return false;
            }

            if (!empty($includePaths)) {
                $found = false;
                foreach ($includePaths as $includePattern) {
                    if (fnmatch("{$includePattern}*", $fullPath, FNM_NOESCAPE)) {
                        $found = true;
                        break;
                    }
                }
                if (!$found) {
                    return false;
                }
            }

            foreach ($excludePaths as $excludePattern) {
                if (fnmatch("{$excludePattern}*", $fullPath, FNM_NOESCAPE)) {
                    return false;
                }
            }

            return true;
        };
    }
327191
public function share(Closure $callable) : Closure
    {
        return function () use ($callable) {
            static $object;
            $c = $this;

            if (is_null($object) && $callable instanceof Closure) {
                $object = $callable($c);
            }

            return $object;
        };
    }
826233
public function findIndex(callable $callback)
    {
        $array = $this->getArrayCopy();
        foreach ($array as $key => $value) {
            if ($callback($value, $key, $array) === true) {
                return $key;
            }
        }

        return -1;
    }
1002371
protected static function getReflection($callable)
    {

        if (is_array($callable)) {
            return new ReflectionMethod($callable[0], $callable[1]);
        }

        if ($callable instanceof \Closure) {
            return new ReflectionFunction($callable);
        }

        if (is_object($callable)) {
            return new ReflectionMethod($callable, '__invoke');
        }

        // Should be a string until here
        if (strpos($callable, '::')) {
            list($class, $method) = explode('::', $callable);
            return new ReflectionMethod($class, $method);
        }

        return new ReflectionFunction($callable);
    }
598998
protected function parseCall()
    {

        if ($this->call instanceof Closure) {
            $this->callClass = Closure::class;
            $this->callMethod = '';
            $this->isStaticMethod = false;
            $this->isFunction = false;
            $this->isClosure = true;
            return;
        }

        list($class, $method) = $this->toClassAndMethod($this->call);

        if ($class === '') {
            $this->callClass = '';
            $this->callMethod = $method;
            $this->isStaticMethod = false;
            $this->isFunction = true;
            $this->isClosure = false;
            return;
        }

        $this->callClass = $class;
        $this->callMethod = $method;
        $this->isFunction = false;
        $this->isClosure = false;

        $reflection = new ReflectionMethod($class, $method);
        $this->isStaticMethod = $reflection->isStatic();

        if (!$reflection->isPublic()) {
            throw new LogicException("Method '$method' of $class is not public and therefore not callable.");
        }

        return;

    }
553356
public function resolve($reference)
    {
        $reference = substr($reference, 7);
        $method = $this->getMethod($reference);
        $callback = [
            $this->container->resolve($method->getOwner()),
            $method->getName()
        ];

        if ($method->hasArguments()) {
            return function () use($callback, $method)
            {
                return call_user_func_array($callback, $method->extractArguments($this->container, new ArrayResolver()));
            };
        }

        return is_array($callback) ? function () use ($callback) {
            return call_user_func_array($callback, func_get_args());
        } : $callback;
    }
143771
public function resolve($reference)
    {
        $parts = explode('?:', $reference, 2);

        for ($index = 0; $index < count($parts); $index++) {
            try {
                return $this->resolver->resolve(trim($parts[$index]));
            }
            catch (UnknownDefinitionException $exception) {
                continue;
            }
        }

        return null;
    }
1292901
public function whereNested(Closure $callback)
    {
        // To handle nested queries we'll actually create a brand new query instance
        // and pass it off to the Closure that we have. The Closure can simply do
        // do whatever it wants to a query then we will store it for compiling.
        $query = $this->newQuery();

        call_user_func($callback, $query);

        return $this->addNestedWhereQuery($query);
    }
1134290
protected function extractClosureCode(\ReflectionFunction $ref)
	{
		$file = $ref->getFileName();
		$lines = file($file, FILE_IGNORE_NEW_LINES);
		
		if(isset($this->namespaceContextCache[$file]))
		{
			$namespaceContext = $this->namespaceContextCache[$file];
		}
		else
		{
			$tokens = token_get_all(implode("\n", $lines));
			$namespaceContext = $this->namespaceContextCache[$file] = $this->generateNamespaceContext($tokens);
		}
		
		// Extract closure code from file source.
		$funcLines = array_slice($lines, $ref->getStartLine() - 1, $ref->getEndLine() - $ref->getStartLine() + 1);
		$snippet = implode("\n", array_map('trim', $funcLines));
		$snippet = preg_replace("'^.*\{'", '', $snippet);
		$snippet = preg_replace("'\}.*$'", '', $snippet);
		
		// Parse closure code snippet and expand unqualified names.
		$tokens = array_slice(token_get_all('<?php ' . $snippet), 1);
		$buffer = $this->expandNames($tokens, $namespaceContext);
		
		return str_replace("\n", "\n\t\t", "\n" . trim($buffer));
	}