Overview

Classes

  • Packager_Common_Base
  • Packager_Common_StaticCopies
  • Packager_Phar
  • Packager_Phar_ResultCompleter
  • Packager_Php
  • Packager_Php_Base
  • Packager_Php_Completer
  • Packager_Php_Scripts_Completer
  • Packager_Php_Scripts_Dependencies
  • Packager_Php_Scripts_Order
  • Packager_Php_Scripts_Replacer
  • Packager_Php_Wrapper
  • Packager_Php_Wrapper_DirectoryIterator
  • Packager_Php_Wrapper_SplFileInfo

Exceptions

  • Packager_Php_Scripts_Throwable
  • Overview
  • Class
  • Tree
  • Todo
  • Deprecated
  • Download
  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: 
<?php

include_once(__DIR__.'/Order.php');

if (PHP_VERSION_ID < 70000)
    include_once(__DIR__.'/Throwable.php');

class Packager_Php_Scripts_Dependencies extends Packager_Php_Scripts_Order
{
    protected $includedFiles = [];
    protected $composerClassLoader = NULL;
    private static $_includePaths = [
        '',
        '/App',
        '/Libs',
    ];
    public static function AutoloadCall ($className) {
        $fileName = str_replace(['_', '\\'], '/', $className) . '.php';
        $includePath = '';
        foreach (self::$_includePaths as $path) {
            $fullPath = self::$instance->cfg->sourcesDir . $path . '/' . $fileName;
            if (file_exists($fullPath)) {
                $includePath = $fullPath;
                break;
            }
        }
        if ($includePath) {
            self::$instance->includedFiles[] = self::_virtualRealPath($includePath);
            return include_once($includePath);
        } else {
            $includePath = self::$instance->composerClassLoader->findFile($className);
            if ($includePath) {
                self::$instance->includedFiles[] = self::_virtualRealPath($includePath);
                return include_once($includePath);
            }
        }
        return FALSE;
    }
    protected function completePhpFilesDependencies () {
        // complete dependencies - requires
        foreach ($this->files->all as $fullPath => & $fileInfo) {
            if ($fileInfo->extension == 'php') {
                $this->filesPhpDependencies[$fullPath] = $this->_completeRequireRecords($fullPath, $fileInfo);
            }
        }
        // complete dependencies - requiredBy
        $this->_completeRequiredByRecords();
    }
    private function _completeRequireRecords ($fullPath, & $fileInfo) {
        // capture all dependent files defined by require, require_once, include, include_once as relative paths
        $byRequiresAndIncludes = $this->_completeDependenciesByRequiresAndIncludes($fullPath, $fileInfo);
        if ($this->cfg->autoloadingOrderDetection) {
            // try to load file and try to capture what was necessary to auto load
            $autoloadedByDeclaration = $this->_completePhpFileDependenciesByAutoloadDeclaration($fileInfo);
            // if there is no record about auto loaded file and it is not foreign file - add auto loaded file at the end
            foreach ($autoloadedByDeclaration as $autoLoadItem) {
                if (isset($this->files->all[$autoLoadItem]) && !in_array($autoLoadItem, $byRequiresAndIncludes, TRUE)) {
                    $byRequiresAndIncludes[] = $autoLoadItem;
                }
            }
        }
        return (object) [
            'requiredBy'    => [],
            'requires'      => $byRequiresAndIncludes,
        ];
    }
    private function _completeRequiredByRecords () {
        foreach ($this->filesPhpDependencies as $fullPath => & $requirements) {
            $requirements->requiredBy = $this->_completeRequiredByRecordsRecursive(
                $fullPath, $requirements->requiredBy
            );
        }
        foreach ($this->filesPhpDependencies as $fullPath => & $requirements) {
            $requirements->requiredByCount = count($requirements->requiredBy);
            $requirements->requiresCount = count($requirements->requires);
        }
    }
    private function _completeRequiredByRecordsRecursive ($searchedFullPath, & $searchedRequirementsRequiredBy) {
        foreach ($this->filesPhpDependencies as $fullPath => $requirements) {
            if (in_array($searchedFullPath, $requirements->requires, TRUE)) {
                if (!in_array($fullPath, $searchedRequirementsRequiredBy, TRUE)) {
                    $searchedRequirementsRequiredBy[] = $fullPath;
                    $requiredByLocal = $this->_completeRequiredByRecordsRecursive(
                        $searchedFullPath, $searchedRequirementsRequiredBy
                    );
                    foreach ($requiredByLocal as $requiredByLocalItem) {
                        if (!in_array($requiredByLocalItem, $searchedRequirementsRequiredBy, TRUE)) {
                            $searchedRequirementsRequiredBy[] = $requiredByLocalItem;
                        }
                    }
                }
            }
        }
        return $searchedRequirementsRequiredBy;
    }
    private function _completeDependenciesByRequiresAndIncludes ($fullPath, & $fileInfo) {
        $capturedItems = $this->_completeDependenciesByFileContentCapture(
            $fileInfo
        );
        $capturedItems = $this->_completeDependenciesByReqsAndInclsReplaceConstsAndEval(
            $fileInfo, $capturedItems
        );
        $this->_removeProperlyCapturedReqsAndInclsFromPhpFilesContents(
            $fileInfo, $capturedItems
        );
        $dependentFilesByRequiresAndIncludes = $this->_completeDependenciesByReqsAndInclsAbsolutizeCapturedPaths(
            $fileInfo, $capturedItems
        );
        return $dependentFilesByRequiresAndIncludes;
    }
    private function _completeDependenciesByFileContentCapture (& $fileInfo) {
        $capturedItems = [];
        $regExps = [
            // do not read anything from require() and include(),
            // these functions are always used for dynamically included files
            //"#([^a-zA-Z0-9_\\/\*])(require)([^_a-zA-Z0-9])([^;]*);#m" => array('$1', array(3, 4)),
            //"#([^a-zA-Z0-9_\\/\*])(include)([^_a-zA-Z0-9])([^;]*);#m" => array('$1', array(3, 4)),

            // read everything from require_once() and include_once(),
            // these functions are always used for fixed including to declare content classes
            "#([^a-zA-Z0-9_\\/\*])(require_once)(\s|\()([^;]*);#mu" => ['$1', [4]],
            "#([^a-zA-Z0-9_\\/\*])(include_once)(\s|\()([^;]*);#mu" => ['$1', [4]],
        ];
        foreach ($regExps as $regExp => $backReferences) {
            $matches = [];
            $caught = preg_match_all($regExp, $fileInfo->content, $matches, PREG_OFFSET_CAPTURE);
            if ($caught > 0) {
                // xcv(array($fileInfo->fullPath, $matches));
                foreach ($matches[0] as $matchKey => $matchItem) {
                    $backReferenceStr = '';
                    foreach ($backReferences[1] as $backReferenceIndex) {
                        $backReferenceStr .= $matches[$backReferenceIndex][$matchKey][0];
                    }
                    $caughtTextIndex = $matchItem[1];
                    // this is very very very crazy result fix from `preg_match_all()` with PREG_OFFSET_CAPTURE
                    /*
                    $caughtTextIndexFixMatchItem = $matches[2][0][0];
                    $caughtTextIndexFixOffset = $caughtTextIndex - mb_strlen($caughtTextIndexFixMatchItem) - 4;
                    if ($caughtTextIndexFixOffset > 0 && mb_strlen($fileInfo->content) > $caughtTextIndexFixOffset + mb_strlen($caughtTextIndexFixMatchItem)) {
                        $caughtTextIndexFix = mb_strpos(
                            $fileInfo->content,
                            $caughtTextIndexFixMatchItem,
                            $caughtTextIndexFixOffset
                        );
                        if ($caughtTextIndexFix !== $caughtTextIndex && $caughtTextIndexFix !== FALSE) {
                            $caughtTextIndex = $caughtTextIndexFix;
                        }
                    }
                    */
                    // end of fix
                    $caughtTextLength = mb_strlen($matchItem[0]);
                    $capturedItems[] = [$backReferenceStr, $caughtTextIndex, $caughtTextLength];
                }
            }
        }
        usort($capturedItems, function ($a, $b) {
            if ($a[1] == $b[1]) return 0;
            return ($a[1] < $b[1]) ? -1 : 1;
        });
        return $capturedItems;
    }
    private function _completeDependenciesByReqsAndInclsReplaceConstsAndEval (& $fileInfo, & $capturedItems) {
        $fullPathLastSlash = strrpos($fileInfo->fullPath, '/');
        $fullPathDir = $fullPathLastSlash !== FALSE
            ? substr($fileInfo->fullPath, 0, $fullPathLastSlash)
            : $fileInfo->fullPath ;
        $capturedItemKeysToUnset = [];
        ob_start();
        $this->errorHandlerData = [];
        foreach ($capturedItems as $key => & $capturedItem) {
            $capturedText = trim($capturedItem[0], "\t \r\n()");
            $capturedText = str_replace(
                ['__FILE__', '__DIR__',],
                ["'".$fileInfo->fullPath."'", "'".$fullPathDir."'",],
                $capturedText
            );
            $addDependency = TRUE;
            ob_clean();
            try {
                @eval('echo '.$capturedText . ';');
            } catch (Exception $e) {
                $addDependency = FALSE;
            }
            if ($this->errorHandlerData) {
                // if there was any unknown variables in captured include_once() or require_once() content,
                // do not add any evaluated dependency, because there is not relevant eval result
                $addDependency = FALSE;
                $this->errorHandlerData = [];
            } else {
                $capturedText = ob_get_contents();
            }
            ob_clean();
            if ($addDependency && $capturedText) {
                $capturedItem[3] = $capturedText;
            } else {
                $capturedItemKeysToUnset[] = $key;
            }
        }
        foreach ($capturedItemKeysToUnset as $key) {
            unset($capturedItems[$key]);
        }
        return $capturedItems;
    }
    private function _removeProperlyCapturedReqsAndInclsFromPhpFilesContents (& $fileInfo, & $capturedItems) {
        if (count($capturedItems) > 0) {
            $newFileContent = '';
            $previousItem = [];
            $currentIndex = 0;
            $currentLength = 0;
            //var_dump([$fileInfo->fullPath, $capturedItems]);
            foreach ($capturedItems as $key => & $capturedItem) {
                $previousItem = ($key > 0 && isset($capturedItems[$key - 1]))
                    ? $capturedItems[$key - 1]
                    : [0, 0, 0] ;
                $previousIndex = $previousItem[1];
                $previousLength = $previousItem[2];
                $currentIndex = $capturedItem[1];
                $currentLength = $capturedItem[2];
                $start = $previousIndex + $previousLength;
                $length = $currentIndex - $start;
                $newFileContent .= mb_substr($fileInfo->content, $start, $length);
            }
            $newFileContent .= mb_substr($fileInfo->content, $currentIndex + $currentLength);
            $fileInfo->content = $newFileContent;
        }
    }
    private function _completeDependenciesByReqsAndInclsAbsolutizeCapturedPaths (& $fileInfo, & $capturedItems) {
        $byRequiresAndIncludes = [];
        $result = [];
        foreach ($capturedItems as $key => $capturedItem) {
            $requiredOrIncluded = $capturedItem[3];
            $realPath = realpath($requiredOrIncluded);
            $fullPath = '';
            if ($realPath !== FALSE) {
                $fullPath = self::_virtualRealPath($requiredOrIncluded);
            } else {
                $fullPathLastSlash = strrpos($fileInfo->fullPath, '/');
                $fullPathDir = $fullPathLastSlash !== FALSE
                    ? substr($fileInfo->fullPath, 0, $fullPathLastSlash)
                    : $fileInfo->fullPath ;
                $possibleFullPath = $fullPathDir . '/' . ltrim($requiredOrIncluded, '/');
                $realPath = realpath($possibleFullPath);
                if ($realPath !== FALSE) {
                    $fullPath = self::_virtualRealPath($possibleFullPath);
                }
            }
            if (!$fullPath) {
                foreach (self::$_includePaths as $possibleAutoloadingDirectory) {
                    $possibleFullPath = $this->cfg->sourcesDir . $possibleAutoloadingDirectory . '/' . ltrim($requiredOrIncluded, '/');
                    $realPath = realpath($possibleFullPath);
                    if ($realPath !== FALSE) {
                        $fullPath = self::_virtualRealPath($possibleFullPath);
                        break;
                    }
                }
            }
            if (!$fullPath) {
                $fullPath = $requiredOrIncluded;
            }
            $byRequiresAndIncludes[$key] = str_replace('\\', '/', $fullPath);
        }
        // remove duplicates and foreign files
        foreach ($byRequiresAndIncludes as $key => $byRequiresAndIncludesItem) {
            if (isset($this->files->all[$byRequiresAndIncludesItem]) && !isset($result[$byRequiresAndIncludesItem])) {
                $result[$byRequiresAndIncludesItem] = 1;
            }
        }
        return array_keys($result);
    }
    private function _completePhpFileDependenciesByAutoloadDeclaration (& $fileInfo) {
        $result = [];
        $autoloadJobResult = $this->executeJobAndGetResult(
            'autoloadJob', ['file' => $fileInfo->fullPath], 'json'
        );
        //var_dump([$fileInfo->fullPath, $autoloadJobResult]);
        if ($autoloadJobResult instanceof stdClass && $autoloadJobResult->success) {
            $result = $autoloadJobResult->includedFiles;
        } else if ($fileInfo->relPath !== '/index.php') {
            if ($autoloadJobResult->type == 'json') {
                $this->sendResult(
                    implode('<br />', $autoloadJobResult->exceptionsMessages),
                    $autoloadJobResult->exceptionsTraces,
                    'error'
                );
            } else {
                $relPath = $fileInfo->relPath;
                $newLine = php_sapi_name() == 'cli' ? "\n" : "<br />";
                $this->sendResult(
                    "Auto load error by including file: $newLine"
                     . "'$relPath' $newLine"
                     . "Is this file used also in your development versions? $newLine"
                     . "Or does this file generates any output by calling simple $newLine "
                     . "`include(\$thisFileFullPath);`, which breaks compiling process?",
                    $fileInfo->fullPath . "\r\n" . $autoloadJobResult->data,
                    'error'
                );
                var_dump($autoloadJobResult);
            }
        }
        return $result;
    }
    protected function completePhpFilesDependenciesByAutoloadDeclaration ($file = '') {
        ob_clean();
        $success = TRUE;
        $content = '';
        if (!$file) {
            $success = FALSE;
            $this->exceptionsMessages[] = 'File is an empty string.';
        } else {
            // store included files count included till now to remove them later at the end
            $this->includedFiles = get_included_files();
            $this->includedFilesCountTillNow = count($this->includedFiles);
            if ($this->_prepareIncludePathsOrComposerAutoloadAndErrorHandlers($file)) {
                // process target file include command
                try {
                    include($file);
                } catch (Packager_Php_Scripts_Throwable $e) {
                    $success = FALSE;
                    $this->exceptionsMessages[] = $e->getMessage();
                    $this->exceptionsTraces[] = $e->getTrace();
                }
            } else {
                if ($this->exceptionsMessages) $success = FALSE;
            }
            $content = ob_get_clean();
            // complete included files by target file
        }
        $this->sendJsonResultAndExit((object) [
            'success'           => $success,
            'includedFiles'     => self::CompleteIncludedFilesByTargetFile(),
            'exceptionsMessages'=> $this->exceptionsMessages,
            'exceptionsTraces'  => $this->exceptionsTraces,
            'content'           => $content,
        ]);
    }
    private function _prepareIncludePathsOrComposerAutoloadAndErrorHandlers ($file) {
        // try to find composer loader usually placed in $documentRoot/vendor/autoload.php
        $scriptFileName = $_SERVER['SCRIPT_FILENAME'];
        $scriptFileName = strtoupper(mb_substr($scriptFileName, 0, 1)) . mb_substr($scriptFileName, 1);
        $lastSlash = mb_strrpos($scriptFileName, DIRECTORY_SEPARATOR);
        $documentRoot = ($lastSlash !== FALSE) ? mb_substr($scriptFileName, 0, $lastSlash) : $scriptFileName ;
        $wrongComposerAutoloadFullPath = $documentRoot . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
        // count already included files
        $alreadyIncludedFiles = get_included_files();
        // check if packager use include_once("vendor/autoload.php") or not
        if (in_array($wrongComposerAutoloadFullPath, $alreadyIncludedFiles, TRUE)) {
            $this->exceptionsMessages = [
                "Do not use 'include_once(\"vendor/autoload.php\");' for result packing.",
                "Use direct path instead: 'include_once(\"vendor/mvccore/packager/src/Packager/Php.php\");'"
            ];
            return FALSE;
        }
        $sourcesDir = trim($this->cfg->sourcesDir, '/');
        $composerAutoloadFullPath = $sourcesDir . '/vendor/autoload.php';
        $errorMsgs = [];
        $errorTraces = [];
        $selfClass = get_class();
        if (file_exists($composerAutoloadFullPath)) {
            // if project is using composer autoloader
            try {
                $this->composerClassLoader = include_once($composerAutoloadFullPath);
            } catch (Exception $e1) {
                //var_dump($e1);
                $errorMsgs = [$e1->getMessage()];
                $errorTraces = $e1->getTrace();
            } catch (Error $e2) {
                //var_dump($e2);
                $errorMsgs = [$e2->getMessage()];
                $errorTraces = $e2->getTrace();
            } //finally {
                if ($errorMsgs) {
                    var_dump(get_included_files());
                    var_dump($errorMsgs);
                }
            //}
            if ($this->_isFileIncluded($file)) {
                // file has no dependency, because it's part of composer
                // auto load or in composer auto load static includes array
                return FALSE;
            }
            spl_autoload_register([$selfClass, 'AutoloadCall'], false, true);
        } else {
            // if composer auto load doesn't exists, MvcCore project is probably
            // developed with manually placed files in document root, '/App' dir or in '/Libs' dir,
            spl_autoload_register([$selfClass, 'AutoloadCall']);
        }
        // set custom error handlers to catch eval warnings and errors
        register_shutdown_function([$selfClass, 'ShutdownHandler']);
        set_exception_handler([$selfClass, 'ExceptionHandler']);
        set_error_handler([$selfClass, 'ErrorHandler']);
        $this->errorResponse = [
            'autoloadJob',
            (object) [
                'success'           => FALSE,
                'includedFiles'     => [],
                'exceptionsMessages'=> $errorMsgs,
                'exceptionsTraces'  => $errorTraces,
                'content'           => '',
            ]
        ];
        return TRUE;
    }
    public static function CompleteIncludedFilesByTargetFile () {
        $includedFilesCountTillNow = self::$instance->includedFilesCountTillNow;
        //$allIncludedFiles = array_slice(get_included_files(), $includedFilesCountTillNow);
        $allIncludedFiles = array_slice(self::$instance->includedFiles, $includedFilesCountTillNow);
        $autoLoadedFiles = [];
        foreach ($allIncludedFiles as $includedFileFullPath) {
            $autoLoadedFiles[] = str_replace('\\', '/', $includedFileFullPath);
        }
        return $autoLoadedFiles;
    }
    private function _isFileIncluded ($file) {
        $result = FALSE;
        $inclFiles = get_included_files();
        foreach ($inclFiles as $inclFile) {
            $inclFile = str_replace('\\', '/', $inclFile);
            if ($inclFile == $file) {
                $result = TRUE;
                break;
            }
        }
        return $result;
    }
    private static function _virtualRealPath ($path) {
        $path = str_replace('\\', '/', $path);
        $path = rtrim($path, '/');
        while (strpos($path, '//') !== FALSE)
            $path = str_replace('//', '/', $path);
        $parts = explode('/', $path);
        $absolutes = [];
        foreach ($parts as $part) {
            if (strlen($part) === 0) {
                $absolutes[] = $part;
                continue;
            }
            if ($part == '.') continue;
            if ($part == '..') {
                array_pop($absolutes);
            } else {
                $absolutes[] = $part;
            }
        }
        return implode('/', $absolutes);
    }
}
Packager API Documentation API documentation generated by ApiGen