/** * Processes <texy>...</texy> elements. * * @author David Grudl, Jan Tvrdík * @param string * @return string */ public static function texyElements($s) { $texy = self::$texy; if ($texy === NULL) throw new \InvalidStateException(get_class($this) . '::$texy must be set.'); return Nette\String::replace($s, '#<texy>(.*?)</texy>#s', function ($m) use ($texy) { $s = $m[1]; $singleLine = (strpos($s, "\n") === FALSE); $s = trim($s, "\n"); $tabs = strspn($s, "\t"); if ($tabs) $s = Nette\String::replace($s, "#^\t{1,$tabs}#m", ''); $s = $texy->process($s, $singleLine); return "{syntax double}$s{{/syntax}}"; } ); }
/** * Processes <texy>...</texy> elements. * * @author David Grudl, Jan Tvrdík * @param string * @return string */ public function __invoke($s) { $texy = $this->texy; $autoChangeSyntax = $this->autoChangeSyntax; if ($texy === NULL) throw new \InvalidStateException(get_class($this) . '::$texy must be set.'); return Nette\String::replace($s, '#<texy>(.*?)</texy>#s', function ($m) use ($texy, $autoChangeSyntax) { $s = $m[1]; $singleLine = (strpos($s, "\n") === FALSE); $s = trim($s, "\r\n"); $tabs = strspn($s, "\t"); if ($tabs) $s = Nette\String::replace($s, "#^\t{1,$tabs}#m", ''); $s = $texy->process($s, $singleLine); return ($autoChangeSyntax ? "{syntax double}$s{{/syntax}}" : $s); } ); }
/** * @param string * @param array * @return array of [sql, params] */ public function process($sql, $params) { $this->params = $params; $this->counter = 0; $this->remaining = array(); $cmd = strtoupper(substr(ltrim($sql), 0, 6)); // detect array mode $this->arrayMode = $cmd === 'INSERT' || $cmd === 'REPLAC' ? 'values' : 'assoc'; /*~ \'.*?\'|".*?"| ## string :[a-zA-Z0-9_]+:| ## :substitution: \? ## placeholder ~xs*/ $sql = Nette\String::replace($sql, '~\'.*?\'|".*?"|:[a-zA-Z0-9_]+:|\\?~s', array($this, 'callback')); while ($this->counter < count($params)) { $sql .= ' ' . $this->formatValue($params[$this->counter++]); } return array($sql, $this->remaining); }
/** * {attr ...} */ public function macroAttr($content) { return String::replace($content . ' ', '#\)\s+#', ')->'); }
/** * * @param string $document * @param string $charset * @return string */ public static function fixContentTypeMeta($document, $charset = 'utf-8') { return String::replace($document, '~<meta([^>]+http-equiv\\s*=\\s*)["\']*Content-Type["\']*([^>]+content\\s*=\\s*["\'][^;]+;)[\\t ]*charset=[^"\']+(["\'][^>]*)>~i', '<meta\\1"Content-Type"\\2 charset=' . $charset . '\\3>'); }
/** * Process <texy>...</texy> elements. * @param string * @return string */ public static function texyElements($s) { return String::replace($s, '#<texy([^>]*)>(.*?)</texy>#s', function ($m) { list(, $mAttrs, $mContent) = $m; // parse attributes $attrs = array(); if ($mAttrs) { foreach (String::matchAll($mAttrs, '#([a-z0-9:-]+)\\s*(?:=\\s*(\'[^\']*\'|"[^"]*"|[^\'"\\s]+))?()#isu') as $m) { $key = strtolower($m[1]); $val = $m[2]; if ($val == NULL) { $attrs[$key] = TRUE; } elseif ($val[0] === '\'' || $val[0] === '"') { $attrs[$key] = html_entity_decode(substr($val, 1, -1), ENT_QUOTES, 'UTF-8'); } else { $attrs[$key] = html_entity_decode($val, ENT_QUOTES, 'UTF-8'); } } } return TemplateFilters::$texy->process($m[2]); }); }
/** * Formats and adds custom headers to the current request */ protected function setRequestHeaders($request) { $headers = array(); foreach ($this->headers as $key => $value) { //fix HTTP_ACCEPT_CHARSET to Accept-Charset $key = String::replace($key, array('~^HTTP_~i' => '', '~_~' => '-')); $key = String::replace($key, array('~(?P<word>[a-z]+)~i'), function ($match) { return ucfirst(strtolower(current($match))); }); if ($key == 'Et') { $key = 'ET'; } $headers[] = (!is_int($key) ? $key . ': ' : '') . $value; } if (count($this->headers) > 0) { curl_setopt($request, CURLOPT_HTTPHEADER, $headers); } return $headers; }
/** * Indents the HTML content from the left. * @param string UTF-8 encoding or 8-bit * @param int * @param string * @return string */ public static function indent($s, $level = 1, $chars = "\t") { if ($level >= 1) { $s = String::replace($s, '#<(textarea|pre).*?</\\1#si', function ($m) { return strtr($m[0], " \t\r\n", ""); }); $s = String::indent($s, $level, $chars); $s = strtr($s, "", " \t\r\n"); } return $s; }
/** * Creates current HttpRequest object. * @return HttpRequest */ public function createHttpRequest() { // DETECTS URI, base path and script path of the request. $uri = new UriScript; $uri->scheme = isset($_SERVER['HTTPS']) && strcasecmp($_SERVER['HTTPS'], 'off') ? 'https' : 'http'; $uri->user = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : ''; $uri->password = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : ''; // host & port if (isset($_SERVER['HTTP_HOST'])) { $pair = explode(':', $_SERVER['HTTP_HOST']); } elseif (isset($_SERVER['SERVER_NAME'])) { $pair = explode(':', $_SERVER['SERVER_NAME']); } else { $pair = array(''); } $uri->host = preg_match('#^[-._a-z0-9]+$#', $pair[0]) ? $pair[0] : ''; if (isset($pair[1])) { $uri->port = (int) $pair[1]; } elseif (isset($_SERVER['SERVER_PORT'])) { $uri->port = (int) $_SERVER['SERVER_PORT']; } // path & query if (isset($_SERVER['REQUEST_URI'])) { // Apache, IIS 6.0 $requestUri = $_SERVER['REQUEST_URI']; } elseif (isset($_SERVER['ORIG_PATH_INFO'])) { // IIS 5.0 (PHP as CGI ?) $requestUri = $_SERVER['ORIG_PATH_INFO']; if (isset($_SERVER['QUERY_STRING']) && $_SERVER['QUERY_STRING'] != '') { $requestUri .= '?' . $_SERVER['QUERY_STRING']; } } else { $requestUri = ''; } $requestUri = String::replace($requestUri, $this->uriFilters['uri']); $tmp = explode('?', $requestUri, 2); $uri->path = String::replace($tmp[0], $this->uriFilters['path']); $uri->query = isset($tmp[1]) ? $tmp[1] : ''; // normalized uri $uri->canonicalize(); $uri->path = String::fixEncoding($uri->path); // detect script path if (isset($_SERVER['DOCUMENT_ROOT'], $_SERVER['SCRIPT_FILENAME']) && strncmp($_SERVER['DOCUMENT_ROOT'], $_SERVER['SCRIPT_FILENAME'], strlen($_SERVER['DOCUMENT_ROOT'])) === 0) { $script = '/' . ltrim(strtr(substr($_SERVER['SCRIPT_FILENAME'], strlen($_SERVER['DOCUMENT_ROOT'])), '\\', '/'), '/'); } elseif (isset($_SERVER['SCRIPT_NAME'])) { $script = $_SERVER['SCRIPT_NAME']; } else { $script = '/'; } if (strncasecmp($uri->path . '/', $script . '/', strlen($script) + 1) === 0) { // whole script in URL $uri->scriptPath = substr($uri->path, 0, strlen($script)); } elseif (strncasecmp($uri->path, $script, strrpos($script, '/') + 1) === 0) { // directory part of script in URL $uri->scriptPath = substr($uri->path, 0, strrpos($script, '/') + 1); } else { $uri->scriptPath = '/'; } // GET, POST, COOKIE $useFilter = (!in_array(ini_get('filter.default'), array('', 'unsafe_raw')) || ini_get('filter.default_flags')); parse_str($uri->query, $query); if (!$query) { $query = $useFilter ? filter_input_array(INPUT_GET, FILTER_UNSAFE_RAW) : (empty($_GET) ? array() : $_GET); } $post = $useFilter ? filter_input_array(INPUT_POST, FILTER_UNSAFE_RAW) : (empty($_POST) ? array() : $_POST); $cookies = $useFilter ? filter_input_array(INPUT_COOKIE, FILTER_UNSAFE_RAW) : (empty($_COOKIE) ? array() : $_COOKIE); $gpc = (bool) get_magic_quotes_gpc(); $old = error_reporting(error_reporting() ^ E_NOTICE); // remove f*****g quotes and check (and optionally convert) encoding if ($gpc || $this->encoding) { $utf = strcasecmp($this->encoding, 'UTF-8') === 0; $list = array(& $query, & $post, & $cookies); while (list($key, $val) = each($list)) { foreach ($val as $k => $v) { unset($list[$key][$k]); if ($gpc) { $k = stripslashes($k); } if ($this->encoding && is_string($k) && (preg_match(self::NONCHARS, $k) || preg_last_error())) { // invalid key -> ignore } elseif (is_array($v)) { $list[$key][$k] = $v; $list[] = & $list[$key][$k]; } else { if ($gpc && !$useFilter) { $v = stripSlashes($v); } if ($this->encoding) { if ($utf) { $v = String::fixEncoding($v); } else { if (!String::checkEncoding($v)) { $v = iconv($this->encoding, 'UTF-8//IGNORE', $v); } $v = html_entity_decode($v, ENT_QUOTES, 'UTF-8'); } $v = preg_replace(self::NONCHARS, '', $v); } $list[$key][$k] = $v; } } } unset($list, $key, $val, $k, $v); } // FILES and create HttpUploadedFile objects $files = array(); $list = array(); if (!empty($_FILES)) { foreach ($_FILES as $k => $v) { if ($this->encoding && is_string($k) && (preg_match(self::NONCHARS, $k) || preg_last_error())) continue; $v['@'] = & $files[$k]; $list[] = $v; } } while (list(, $v) = each($list)) { if (!isset($v['name'])) { continue; } elseif (!is_array($v['name'])) { if ($gpc) { $v['name'] = stripSlashes($v['name']); } if ($this->encoding) { $v['name'] = preg_replace(self::NONCHARS, '', String::fixEncoding($v['name'])); } $v['@'] = new HttpUploadedFile($v); continue; } foreach ($v['name'] as $k => $foo) { if ($this->encoding && is_string($k) && (preg_match(self::NONCHARS, $k) || preg_last_error())) continue; $list[] = array( 'name' => $v['name'][$k], 'type' => $v['type'][$k], 'size' => $v['size'][$k], 'tmp_name' => $v['tmp_name'][$k], 'error' => $v['error'][$k], '@' => & $v['@'][$k], ); } } error_reporting($old); // HEADERS if (function_exists('apache_request_headers')) { $headers = array_change_key_case(apache_request_headers(), CASE_LOWER); } else { $headers = array(); foreach ($_SERVER as $k => $v) { if (strncmp($k, 'HTTP_', 5) == 0) { $k = substr($k, 5); } elseif (strncmp($k, 'CONTENT_', 8)) { continue; } $headers[ strtr(strtolower($k), '_', '-') ] = $v; } } return new HttpRequest($uri, $query, $post, $files, $cookies, $headers, isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : NULL, isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : NULL, isset($_SERVER['REMOTE_HOST']) ? $_SERVER['REMOTE_HOST'] : NULL ); }
/** * Builds text content. * @return void */ protected function buildText() { $text = $this->getBody(); if ($text instanceof Nette\Templates\ITemplate) { $text->mail = $this; $this->setBody($text->__toString(TRUE)); } elseif ($text == NULL && $this->html != NULL) { // intentionally == $text = String::replace($this->html, array( '#<(style|script|head).*</\\1>#Uis' => '', '#<t[dh][ >]#i' => " $0", '#[ \t\r\n]+#' => ' ', '#<(/?p|/?h\d|li|br|/tr)[ >/]#i' => "\n$0", )); $text = html_entity_decode(strip_tags($text), ENT_QUOTES, 'UTF-8'); $this->setBody(trim($text)); } }
/** * Detects uri, base path and script path of the request. * @return void */ protected function detectUri() { $uri = $this->uri = new UriScript(); $uri->scheme = $this->isSecured() ? 'https' : 'http'; $uri->user = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : ''; $uri->password = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : ''; // host & port if (isset($_SERVER['HTTP_HOST'])) { $pair = explode(':', $_SERVER['HTTP_HOST']); } elseif (isset($_SERVER['SERVER_NAME'])) { $pair = explode(':', $_SERVER['SERVER_NAME']); } else { $pair = array(''); } $uri->host = $pair[0]; if (isset($pair[1])) { $uri->port = (int) $pair[1]; } elseif (isset($_SERVER['SERVER_PORT'])) { $uri->port = (int) $_SERVER['SERVER_PORT']; } // path & query if (isset($_SERVER['REQUEST_URI'])) { // Apache, IIS 6.0 $requestUri = $_SERVER['REQUEST_URI']; } elseif (isset($_SERVER['ORIG_PATH_INFO'])) { // IIS 5.0 (PHP as CGI ?) $requestUri = $_SERVER['ORIG_PATH_INFO']; if (isset($_SERVER['QUERY_STRING']) && $_SERVER['QUERY_STRING'] != '') { $requestUri .= '?' . $_SERVER['QUERY_STRING']; } } else { $requestUri = ''; } $tmp = explode('?', $requestUri, 2); $this->originalUri = new Uri($uri); $this->originalUri->path = $tmp[0]; $this->originalUri->query = isset($tmp[1]) ? $tmp[1] : ''; $this->originalUri->freeze(); $requestUri = String::replace($requestUri, $this->uriFilter[0]); $tmp = explode('?', $requestUri, 2); $uri->path = String::replace($tmp[0], $this->uriFilter[PHP_URL_PATH]); $uri->path = String::fixEncoding($uri->path); $uri->query = isset($tmp[1]) ? $tmp[1] : ''; // normalized uri $uri->canonicalize(); // detect base URI-path - inspired by Zend Framework (c) Zend Technologies USA Inc. (http://www.zend.com), new BSD license $filename = isset($_SERVER['SCRIPT_FILENAME']) ? basename($_SERVER['SCRIPT_FILENAME']) : NULL; $scriptPath = ''; if (isset($_SERVER['SCRIPT_NAME']) && basename($_SERVER['SCRIPT_NAME']) === $filename) { $scriptPath = rtrim($_SERVER['SCRIPT_NAME'], '/'); } elseif (isset($_SERVER['PHP_SELF']) && basename($_SERVER['PHP_SELF']) === $filename) { $scriptPath = $_SERVER['PHP_SELF']; } elseif (isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME']) === $filename) { $scriptPath = $_SERVER['ORIG_SCRIPT_NAME']; // 1and1 shared hosting compatibility } elseif (isset($_SERVER['PHP_SELF'], $_SERVER['SCRIPT_FILENAME'])) { // Backtrack up the script_filename to find the portion matching php_self $path = $_SERVER['PHP_SELF']; $segs = explode('/', trim($_SERVER['SCRIPT_FILENAME'], '/')); $segs = array_reverse($segs); $index = 0; $last = count($segs); do { $seg = $segs[$index]; $scriptPath = '/' . $seg . $scriptPath; $index++; } while ($last > $index && FALSE !== ($pos = strpos($path, $scriptPath)) && 0 != $pos); } // Does the scriptPath have anything in common with the request_uri? if (strncmp($uri->path, $scriptPath, strlen($scriptPath)) === 0) { // whole $scriptPath in URL $uri->scriptPath = $scriptPath; } elseif (strncmp($uri->path, $scriptPath, strrpos($scriptPath, '/') + 1) === 0) { // directory portion of $scriptPath in URL $uri->scriptPath = substr($scriptPath, 0, strrpos($scriptPath, '/') + 1); } elseif (strpos($uri->path, basename($scriptPath)) === FALSE) { // no match whatsoever; set it blank $uri->scriptPath = '/'; } elseif (strlen($uri->path) >= strlen($scriptPath) && (FALSE !== ($pos = strpos($uri->path, $scriptPath)) && $pos !== 0)) { // If using mod_rewrite or ISAPI_Rewrite strip the script filename // out of scriptPath. $pos !== 0 makes sure it is not matching a value // from PATH_INFO or QUERY_STRING $uri->scriptPath = substr($uri->path, 0, $pos + strlen($scriptPath)); } else { $uri->scriptPath = $scriptPath; } $uri->freeze(); }
/** * Indents the HTML content from the left. * @param string UTF-8 encoding or 8-bit * @param int * @param string * @return string */ public static function indent($s, $level = 1, $chars = "\t") { if ($level >= 1) { $s = String::replace($s, '#<(textarea|pre).*?</\\1#si', callback(create_function('$m', 'return strtr($m[0], " \\t\\r\\n", "\\x1F\\x1E\\x1D\\x1A");'))); $s = String::indent($s, $level, $chars); $s = strtr($s, "", " \t\r\n"); } return $s; }
/** * Process <texy>...</texy> elements. * @param string * @return string */ public static function texyElements($s) { return String::replace($s, '#<texy([^>]*)>(.*?)</texy>#s', callback(__CLASS__, 'texyCb')); }
/** * Prints out a syntax highlighted version of the SQL command. * * @author David Grudl * @param $sql string|DibiResult * @return string */ public static function dump($sql) { $keywords1 = 'CREATE\\s+TABLE|CREATE(?:\\s+UNIQUE)?\\s+INDEX|SELECT|UPDATE|INSERT(?:\\s+INTO)?|REPLACE(?:\\s+INTO)?|DELETE|FROM|WHERE|HAVING|GROUP\\s+BY|ORDER\\s+BY|LIMIT|SET|VALUES|LEFT\\s+JOIN|INNER\\s+JOIN|TRUNCATE'; $keywords2 = 'ALL|DISTINCT|DISTINCTROW|AS|USING|ON|AND|OR|IN|IS|NOT|NULL|LIKE|TRUE|FALSE|INTEGER|CLOB|VARCHAR|DATETIME|TIME|DATE|INT|SMALLINT|BIGINT|BOOL|BOOLEAN|DECIMAL|FLOAT|TEXT|VARCHAR|DEFAULT|AUTOINCREMENT|PRIMARY\\s+KEY'; // insert new lines $sql = " {$sql} "; $sql = String::replace($sql, "#(?<=[\\s,(])({$keywords1})(?=[\\s,)])#", "\n\$1"); if (strpos($sql, "CREATE TABLE") !== FALSE) { $sql = String::replace($sql, "#,\\s+#i", ", \n"); } // reduce spaces $sql = String::replace($sql, '#[ \\t]{2,}#', " "); $sql = wordwrap($sql, 100); $sql = htmlSpecialChars($sql); $sql = String::replace($sql, "#([ \t]*\r?\n){2,}#", "\n"); $sql = String::replace($sql, "#VARCHAR\\(#", "VARCHAR ("); // syntax highlight $sql = String::replace($sql, "#(/\\*.+?\\*/)|(\\*\\*.+?\\*\\*)|(?<=[\\s,(])({$keywords1})(?=[\\s,)])|(?<=[\\s,(=])({$keywords2})(?=[\\s,)=])#s", function ($matches) { if (!empty($matches[1])) { // comment return '<em style="color:gray">' . $matches[1] . '</em>'; } if (!empty($matches[2])) { // error return '<strong style="color:red">' . $matches[2] . '</strong>'; } if (!empty($matches[3])) { // most important keywords return '<strong style="color:blue">' . $matches[3] . '</strong>'; } if (!empty($matches[4])) { // other keywords return '<strong style="color:green">' . $matches[4] . '</strong>'; } }); $sql = trim($sql); return '<pre class="dump">' . $sql . "</pre>\n"; }
/** * Formats parameters to PHP array. * @param string * @param string * @return string */ public static function formatArray($s, $prefix = '') { $s = String::replace(trim($s), '~ ' . self::RE_STRING . '| ## single or double quoted string (?<=[,=(]|=>|^)\\s*([a-z\\d_]+)(?=\\s*[,=)]|$) ## 1) symbol ~xi', callback(__CLASS__, 'cbArgs')); $s = String::replace($s, '#\\$(' . self::RE_IDENTIFIER . ')\\s*=>#', '"$1" =>'); return $s === '' ? '' : $prefix . "array({$s})"; }
/** * Automatically insert USE statement. Please setup specify source and libs directories * * <b>WARNING: This method overwrite original source files, please backup it before use </b> * @see setSource, addLibrary */ public function run() { $this->analyse(); // insert neccessery use statements foreach($this->fileInfo as $filename => $namespaces) { $modified = FALSE; $fileAsArray = array(); foreach($namespaces as $namespace => &$nsInfo) { $useInsertLine = NULL; $nsInfo[self::NS_MISSING_USE] = $nsInfo[self::NS_USED_CLASS]; // find out which classes has already USE statement foreach($nsInfo[self::NS_MISSING_USE] as $usedClass => $line) { $relativeNs = !String::startsWith($usedClass, "\\"); $lastBackslash = strrpos($usedClass, "\\"); $classNs = substr($usedClass, $relativeNs?0:1, ($lastBackslash)?($lastBackslash - ($relativeNs?0:1)):NULL); $class = substr($usedClass, ($lastBackslash !== FALSE)?($lastBackslash+1):0); if(isset($this->definedClasses[$class][$namespace]) || (isset($this->definedClasses[$class][$classNs]) && strlen($classNs))) { // class exist in specified namespace unset($nsInfo[self::NS_MISSING_USE][$usedClass]); } else if(!$relativeNs) { // class was used with absolute namespace unset($nsInfo[self::NS_MISSING_USE][$usedClass]); if(!isset($this->definedClasses[$class][$classNs])) { // class used with absolute namespace doesn't exists (forgotten library?) $this->onOutput(self::OI_CLASS_NOT_FOUND, array( self::NAMESPACE_NAME => $namespace, self::FILE => $filename, self::LINE => $line, self::CLASS_NAME => $usedClass, )); // dump("$filename, $line : $usedClass class used with absolute namespace doesn't exists (forgotten library?)"); } } else { // looking for use statement associated with used class foreach($nsInfo[self::NS_USE_STATEMENTS] as $as => $useStatement) { $lastBackslash = strrpos($useStatement[self::USE_ST_NAME], "\\"); $relativeNs = !String::startsWith($useStatement[self::USE_ST_NAME], "\\"); if(!isset($useInsertLine) || $useStatement["line"] > ($useInsertLine+1)) { $useInsertLine = $useStatement["line"]-1; } $useNs = substr($useStatement[self::USE_ST_NAME], $relativeNs?0:1, ($lastBackslash)?($lastBackslash - ($relativeNs?0:1)):NULL); if(isset($this->definedClasses[$as][$namespace]) && $useNs != $namespace) { // require of file with "$namespace\$as" class can cause error $this->onOutput(self::OI_AMBIGOUS_CLASS_IN_NS, array( self::NAMESPACE_NAME => $namespace, self::FILE => $filename, self::USE_ST_AS => $as, self::LINE => $useStatement[self::LINE], )); } if($usedClass === $as) { // mark use statement as used $nsInfo[self::NS_USE_STATEMENTS][$as]["used"] = TRUE; unset($nsInfo[self::NS_MISSING_USE][$usedClass]); } else if(String::startsWith($classNs, $as . "\\")) { // check for NS aliases $tmpNs = String::replace($classNs, "/[^\\\\]+/", $useStatement[self::USE_ST_NAME], 1); if(isset($this->definedClasses[$class][$tmpNs])) { // mark use statement as used $nsInfo[self::NS_USE_STATEMENTS][$as]["used"] = TRUE; unset($nsInfo[self::NS_MISSING_USE][$class]); } } } } } // inform about unnecessary use statements foreach($nsInfo[self::NS_USE_STATEMENTS] as $as => $useStatement) { if(!$useStatement["used"]) { $this->onOutput(self::OI_UNUSED_USE_ST, array( self::FILE => $filename, self::LINE => $useStatement[self::LINE], self::NAMESPACE_NAME => $namespace, self::USE_ST_AS => $as, )); // dump("$as not used USE statement"); } } // try to insert missing USE statements foreach($nsInfo[self::NS_MISSING_USE] as $class => $line) { if(!isset($this->definedClasses[$class]) || !count($this->definedClasses[$class])) { // class doesn't exists $this->onOutput(self::OI_CLASS_NOT_FOUND, array( self::FILE => $filename, self::LINE => $line, self::NAMESPACE_NAME => $namespace, self::CLASS_NAME => $class, )); } else if(count($this->definedClasses[$class]) > 1) { $this->onOutput(self::OI_CANT_ADD_USE_ST, array( self::FILE => $filename, self::LINE => $line, self::NAMESPACE_NAME => $namespace, self::CLASS_NAME => $class, self::CLASS_OCCURENCES => $this->definedClasses[$class], )); } else { if(!$modified) { // convert file to array $fileAsArray = file($filename, FILE_IGNORE_NEW_LINES); } if(!isset($useInsertLine)) { // we create one row space after NS statement $useInsertLine = $nsInfo[self::LINE]-1; $fileAsArray[$useInsertLine] .= PHP_EOL; } reset($this->definedClasses[$class]); // make sure array pointer is at first element $namespace = key($this->definedClasses[$class]); // we get original class name (not converted to lower case) $className = $this->definedClasses[$class][$namespace][self::CLASS_NAME]; $fileAsArray[$useInsertLine] .= PHP_EOL . "use $namespace".(strlen($namespace)?"\\":""). "$className;"; $this->onOutput(self::OI_USE_ST_ADDED, array( self::FILE => $filename, self::LINE => $line, self::NAMESPACE_NAME => $namespace, self::CLASS_NAME => $className, )); $modified = TRUE; } } } if($modified) { $file = fopen($filename, "w"); fwrite($file, implode(PHP_EOL, $fileAsArray)); fclose($file); } } }