Commit 390e32b2 authored by Marco Schmiedel's avatar Marco Schmiedel

validation stage 1

parent 7cc44f02
<?php
namespace Ceetrox\Commands\CodebeautifierCommand;
use Illuminate\Console\Command;
use Ceetrox\Managers\TerminalManager\TerminalManager;
// This provider implements all artisan commands of sidekick and is triggered by the core provider.
class CodebeautifierCommand extends Command
{
public function __construct()
{
$this->signature = 'sidekick:CodebeautifierCommand {path?}';
$this->description = TerminalManager::brightBlue("This command is a php code beautifier.");
/*
|------------------------------------------------------------------------------------------------
| Information
|------------------------------------------------------------------------------------------------
|
| This file is beautified by the command "sidekick:CodebeautifierCommand" of the ceetrox
| sidekick package.
|
| Author: Marco Schmiedel <marco.schmiedel@itmax.email>
| Date: 2021-12-20 16:46:13
|
*/
namespace Ceetrox\Commands\CodebeautifierCommand;
/*
|------------------------------------------------------------------------------------------------
| Dependencies
|------------------------------------------------------------------------------------------------
*/
use Ceetrox\Managers\TerminalManager\TerminalManager;
use Illuminate\Console\Command;
/*
|------------------------------------------------------------------------------------------------
| Class "CodebeautifierCommand"
|------------------------------------------------------------------------------------------------
*/
class CodebeautifierCommand extends Command
{
/*
|--------------------------------------------------------------------------------------------
| Method "__construct"
|--------------------------------------------------------------------------------------------
*/
public function __construct()
{
$this->signature = 'sidekick:CodebeautifierCommand {path?}';
$this->description = TerminalManager::brightBlue("This command is a php code beautifier.");
parent::__construct();
}
/*
|--------------------------------------------------------------------------------------------
| Method "handle"
|--------------------------------------------------------------------------------------------
*/
public function handle()
{
/*
|----------------------------------------------------------------------------------------
| Try to get the filepath from the command line argument.
*/
$file = $this->argument('path');
/*
|----------------------------------------------------------------------------------------
| Diese Schleife wird so lang durchgeführt, bis ein gültiges Script übergeben wird.
| Check if the given file exists.
*/
while(!isset($fileexists))
{
# Pfad überprüfen
if(file_exists($file))
{
$fileexists = true;
}
else
{
# Eingang abfragen
/*
|--------------------------------------------------------------------------------
| Ask again if the file does not exist.
*/
$file = $this->ask('Bitte geben Sie den absoluten Pfad zum gewünschten Script ein');
}
}
# Beautifier starten
/*
|----------------------------------------------------------------------------------------
| Boot the Beautifier class.
*/
$beauty = new Beautifier();
# Dokument analysieren
$beauty -> Analyse($file);
# Dokument speichern
$beauty -> Render($file);
/*
|----------------------------------------------------------------------------------------
| Analyse the given file.
*/
$beauty -> analyseDocument($file);
/*
|----------------------------------------------------------------------------------------
| Render the given file.
*/
$beauty -> renderDocument($file);
}
}
}
/*
|------------------------------------------------------------------------------------------------
| Klasse
| Class "Beautifier"
|------------------------------------------------------------------------------------------------
| Der Beautifier ist eine eigenständige Klasse und könnte ggf. als Manager abstrahiert werden.
*/
class Beautifier
{
/*
|--------------------------------------------------------------------------------------------
| Klassenvariablen
| Variables
|--------------------------------------------------------------------------------------------
*/
var $Content = [];
var $Classes = [];
var $Comments = [];
var $Linedeph = 1;
var $content = [];
var $classes = [];
var $comments = [];
var $linedeph = 1;
/*
|--------------------------------------------------------------------------------------------
| Method "Analyse"
| Method "analyseDocument"
|--------------------------------------------------------------------------------------------
| Diese Method analysiert alle Elemente aus dem Code.
*/
function Analyse($file)
function analyseDocument($file)
{
# PHP File einlesen
$this->Content = file_get_contents($file);
/*
|----------------------------------------------------------------------------------------
| Read the php file.
*/
$this->content = file_get_contents($file);
# Basisparameter erfassen
$this->Basics();
/*
|----------------------------------------------------------------------------------------
| Read all base parameters.
*/
$this->scanBasics();
# Kommentare erfassen
$this->Content = $this-> ScanComments($this->Content);
/*
|----------------------------------------------------------------------------------------
| Read all comments.
*/
$this-> scanComments();
# Klassen einscannen
$this->ScanClass();
/*
|----------------------------------------------------------------------------------------
| Read all classes.
*/
$this->scanClass();
# Methodn einscannen
$this->ScanMethods();
/*
|----------------------------------------------------------------------------------------
| Read all methods.
*/
$this->scanMethods();
# Rückgabe
return $this->Classes;
/*
|----------------------------------------------------------------------------------------
| Return the full analyse.
*/
return $this->classes;
}
/*
|--------------------------------------------------------------------------------------------
| Method "Basics"
| Method "scanBasics"
|--------------------------------------------------------------------------------------------
| Mit dieser Method werden die Basisparameter aus dem Code gelesen. Zum Beispiel werden die
| Dokumentation, der Namespace und die Abhänigkeiten ausgelesen.
| This method is used to read the basic parameters from the file (for example namespace and
| dependencies).
*/
function Basics()
function scanBasics()
{
# Namespace erfassen
$preg = preg_match('/(^|\s)+namespace\s+[A-Za-z\\\]+;/', $this->Content, $matches, PREG_OFFSET_CAPTURE);
/*
|----------------------------------------------------------------------------------------
| read namespace
*/
$preg = preg_match('/(^|\s)+namespace\s+[A-Za-z\\\]+;/', $this->content, $matches, PREG_OFFSET_CAPTURE);
if(isset($matches[0]))
{
......@@ -132,9 +191,11 @@ class CodebeautifierCommand extends Command
$this->namespace = false;
}
# Abhängigkeiten erfassen
$preg = preg_match_all('/(^|\s)+use\s+[^"\'\n]+[;]/', $this->Content, $matches, PREG_OFFSET_CAPTURE);
/*
|----------------------------------------------------------------------------------------
| read dependencies
*/
$preg = preg_match_all('/(^|\s)+use\s+[^"\'\n]+[;]/', $this->content, $matches, PREG_OFFSET_CAPTURE);
if(isset($matches[0]))
{
......@@ -155,173 +216,182 @@ class CodebeautifierCommand extends Command
/*
|--------------------------------------------------------------------------------------------
| Method "DetectAnker"
| Method "getCommentFromPregMatch"
|--------------------------------------------------------------------------------------------
| Die nachfolgende Method unterstützt "Doku" bei der Erkennung bestehender Beschreibungen.
| Die passenden Anker werden gesetzt.
| With this method a string that has been hashed by "scanClass" can be converted back.
*/
function DetectAnker($OldHtml, $Key)
function getCommentFromPregMatch($pattern, $string)
{
# Erkennungshash erstellen
$md5 = md5($Key);
$Result = $this->SimpleFilter($OldHtml, '/(?<=('.$md5.'Start<\/ac:parameter><\/ac:structured-macro>)).+?(?=(<ac:structured-macro))/');
# Template starten
$tpl = '<ac:structured-macro ac:name="anchor" ac:schema-version="1">
<ac:parameter ac:name="">'.$md5.'Start</ac:parameter>
</ac:structured-macro>
';
# Text einsetzen
if($Result != '')
{
$tpl .= $Result;
}
else
{
$tpl .= '<ul>
<li>Unbekannt</li>
</ul>';
}
# Template stoppen
$tpl .= '<ac:structured-macro ac:name="anchor" ac:schema-version="1">
<ac:parameter ac:name="">'.$md5.'Stop</ac:parameter>
</ac:structured-macro>
';
# Rückgabe
return $tpl;
}
/*
|--------------------------------------------------------------------------------------------
| Method "GetCommentFromPregMatch"
|--------------------------------------------------------------------------------------------
| Mit dieser Method kann ein String, welcher durch ScanClass gehasht wurde,
| zurückverwandelt werden.
*/
function GetCommentFromPregMatch($pattern, $string)
{
# Pattern überprüfen
/*
|----------------------------------------------------------------------------------------
| check pattern
*/
preg_match($pattern, $string, $description, PREG_OFFSET_CAPTURE);
$Result = false;
$result = false;
# Beschreibung aus Cache laden
/*
|----------------------------------------------------------------------------------------
| load description from cache
*/
if(isset($description[0][0]))
{
preg_match('/(?<=(#COMMENT-)).+(?=(-COMMENT#))/', $description[0][0], $md5, PREG_OFFSET_CAPTURE);
if(isset($md5[0][0]))
{
$Result = $this->Comments[$md5[0][0]];
$result = $this->comments[$md5[0][0]];
}
}
# Beschreibung normalisieren
$Result = $this->Normalize($Result);
/*
|----------------------------------------------------------------------------------------
| normalize description
*/
$result = $this->normalize($result);
return $Result;
return $result;
}
/*
|--------------------------------------------------------------------------------------------
| Method "MatchBetweenTwoPatterns"
| Method "matchBetweenTwoPatterns"
|--------------------------------------------------------------------------------------------
| Diese Method filtert einen String, zwischen 2 Regex Patterns und gibt diesen zurück.
| This method filters a string between 2 regex patterns and returns it.
*/
function MatchBetweenTwoPatterns($String, $StartPattern, $StopPattern, $Debug = false)
function matchBetweenTwoPatterns($string, $startPattern, $stopPattern, $debug = false)
{
# Arbeitsarray für den korrekten Ablauf
$Informationen = array();
/*
|----------------------------------------------------------------------------------------
| Create empty array for the following patterns..
*/
$informations = array();
# alle Startpattern filtern
$Start = preg_match_all($StartPattern, $String, $StartResults, PREG_OFFSET_CAPTURE);
/*
|----------------------------------------------------------------------------------------
| Filter all start patterns.
*/
$start = preg_match_all($startPattern, $string, $startResults, PREG_OFFSET_CAPTURE);
if($Start == false)
if($start == false)
{
return false;
}
foreach($StartResults[0] as $Result)
foreach($startResults[0] as $result)
{
preg_match_all('/.*/s', $String, $FullResult, PREG_OFFSET_CAPTURE, $Result[1]);
$Informationen[$Result[1].'2'] = ['Offset' => $Result[1], 'Type' => 'Start', 'String' => $FullResult[0][0][0]];
preg_match_all('/.*/s', $string, $fullResult, PREG_OFFSET_CAPTURE, $result[1]);
$informations[$result[1].'2'] = ['Offset' => $result[1], 'Type' => 'start', 'String' => $fullResult[0][0][0]];
}
# alle Stoppattern filtern
$Stop = preg_match_all($StopPattern, $String, $StopResults, PREG_OFFSET_CAPTURE);
/*
|----------------------------------------------------------------------------------------
| Filter all stop patterns.
*/
$stop = preg_match_all($stopPattern, $string, $stopResults, PREG_OFFSET_CAPTURE);
if($Stop == false)
if($stop == false)
{
return false;
}
foreach($StopResults[0] as $Result)
foreach($stopResults[0] as $result)
{
preg_match_all('/.*/s', $String, $FullResult, PREG_OFFSET_CAPTURE, $Result[1]);
$Informationen[$Result[1].'1'] = ['Offset' => $Result[1], 'Type' => 'Stop', 'String' => $FullResult[0][0][0]];
preg_match_all('/.*/s', $string, $fullResult, PREG_OFFSET_CAPTURE, $result[1]);
$informations[$result[1].'1'] = ['Offset' => $result[1], 'Type' => 'stop', 'String' => $fullResult[0][0][0]];
}
# richtige Reihenfolge (des Offsets) einhalten
ksort($Informationen);
/*
|----------------------------------------------------------------------------------------
| Sort all informations in the right order.
*/
ksort($informations);
# Ergebnisarray anlegen
$Result = array();
/*
|----------------------------------------------------------------------------------------
| Create an array for the results.
*/
$result = array();
# Ergebnisse rendern
foreach($Informationen as $Information)
/*
|----------------------------------------------------------------------------------------
| Loop prepared patterns.
*/
foreach($informations as $information)
{
# Start erkennen
if($Information['Type'] == 'Start')
/*
|------------------------------------------------------------------------------------
| detect start
*/
if($information['Type'] == 'start')
{
# Puffer befüllen
$Puffer = $Information['String'];
/*
|--------------------------------------------------------------------------------
| fill buffer
*/
$puffer = $information['String'];
}
# Stop erkennen
elseif(isset($Puffer))
/*
|------------------------------------------------------------------------------------
| dedect stop
*/
elseif(isset($puffer))
{
# Ergebnis rendern
$Result[] = substr($Puffer, 0, (strlen( $Information['String'])*-1 ) );
/*
|--------------------------------------------------------------------------------
| save result
*/
$result[] = substr($puffer, 0, (strlen( $information['String'])*-1 ) );
# Puffer zurücksetzen
unset($Puffer);
/*
|--------------------------------------------------------------------------------
| reset buffer
*/
unset($puffer);
}
}
# Rückgabe
return $Result;
/*
|----------------------------------------------------------------------------------------
| Return the results.
*/
return $result;
}
/*
|--------------------------------------------------------------------------------------------
| Method "Normalize"
| Method "normalize"
|--------------------------------------------------------------------------------------------
| Diese Method normalisiert einen String.
*/
function Normalize($string)
function normalize($string)
{
# Allman Style erstellen
/*
|----------------------------------------------------------------------------------------
| Force the allman style.
*/
$string = preg_replace('/{\s*$/m', "\n{", $string);
# leere Zeilen und Tabstops entfernen
/*
|----------------------------------------------------------------------------------------
| Remove empty lines and tabs.
*/
$string = preg_replace('/^[\s\t]+[\n]*/m', '', $string);
# doppelte Leerzeichen entfernen
/*
|----------------------------------------------------------------------------------------
| Remove double spaces.
*/
$string = preg_replace("#[ \t]+#", " ", $string);
# Rückgabe
/*
|----------------------------------------------------------------------------------------
| Return the filtered data.
*/
return $string;
}
......@@ -329,25 +399,36 @@ class CodebeautifierCommand extends Command
/*
|--------------------------------------------------------------------------------------------
| Method "Render"
| Method "renderDocument"
|--------------------------------------------------------------------------------------------
| Mit dieser Method wird das Template gerendert. Standardmäßig wird der Output in eine
| Datei geschrieben. Mit der Variable "$fake" kann der Output aber auch als Variable zurück
| gegeben werden.
| This method is used to render the template. By default, the output is written to a file.
| With the variable "$fake" the output can also be returned as a variable.
*/
function Render($file, $fake = false)
function renderDocument($file, $fake = false)
{
# Template einlesen
/*
|----------------------------------------------------------------------------------------
| Read the default template.
*/
$this->tpl = file_get_contents(__dir__.'/Template.tpl');
# Zeitstempel in Template einsetzen
/*
|----------------------------------------------------------------------------------------
| Render the timestamp.
*/
$this->tpl = str_replace('%timestasmp%', date('Y-m-d H:i:s'), $this->tpl);
# Authoor
/*
|----------------------------------------------------------------------------------------
| Render the GIT user.
*/
$git = str_replace("\n",'',shell_exec("git config user.name").' <'.shell_exec("git config user.email").'>');
$this->tpl = str_replace('%author%', $git, $this->tpl);
# Namespace in Template einsetzen
/*
|----------------------------------------------------------------------------------------
| Render the namespace.
*/
if($this->namespace != false)
{
$this->tpl = str_replace('%namespace%', $this->S().$this->namespace, $this->tpl);
......@@ -357,39 +438,63 @@ class CodebeautifierCommand extends Command
$this->tpl = str_replace("\n%namespace%", '', $this->tpl);
}
# Abhänigkeiten in Template einsetzen (wenn vorhanden)
/*
|----------------------------------------------------------------------------------------
| Render all dependencies.
*/
if($this->relations != false)
{
# Abhänigkeiten nach Zeichenlänge sortieren
/*
|------------------------------------------------------------------------------------
| sort dependencies by length
*/
usort($this->relations, function($a, $b)
{
return strlen($b) - strlen($a);
});
# Implodieren aller Abhänigkeiten
/*
|------------------------------------------------------------------------------------
| implode dependencies
*/
$implode = implode("\n".$this->S(), $this->relations);
# implodierte Abhänigkeiten in Template einsetzen
/*
|------------------------------------------------------------------------------------
| write dependencies
*/
$this->tpl = str_replace('%relations%', $this->S().$implode, $this->tpl);
}
# Abhänigkeiten aus Template löschen (wenn nicht vorhanden)
/*
|----------------------------------------------------------------------------------------
| Remove dependencies placeholder if not used in template.
*/
else
{
$this->tpl = str_replace("\n%relations%", '', $this->tpl);
}
# Klassen rendern und in Template einsetzen
$stream = $this->RenderClasses();
/*
|----------------------------------------------------------------------------------------
| Render classes to template.
*/
$stream = $this->renderDocumentClasses();
$this->tpl = str_replace("%classes%", $stream, $this->tpl);
# Rückgabe des validierten Dokuments
/*
|----------------------------------------------------------------------------------------
| Return document as variable.
*/
if($fake == true)
{
return $this->tpl;
}
# fertige Daten in physische Datei schreiben
/*
|----------------------------------------------------------------------------------------
| Write document to file.
*/
file_put_contents($file, $this->tpl);
}
......@@ -397,62 +502,96 @@ class CodebeautifierCommand extends Command
/*
|--------------------------------------------------------------------------------------------
| Method "RenderClasses"
| Method "renderDocumentClasses"
|--------------------------------------------------------------------------------------------
| Diese Method unterstützt den Renderprozess "Render" beim durchlaufen der einzelnen
| Klassen.
| This method supports "renderDocument" when going through the individual classes.
*/
function RenderClasses()
function renderDocumentClasses()
{
# Informationsstream für Template erstellen
/*
|----------------------------------------------------------------------------------------
| create string for informations.
*/
$classstream = '';
# alle Klassen durchlaufen
foreach($this->Classes as $class)
/*
|----------------------------------------------------------------------------------------
| Loop all classes.
*/
foreach($this->classes as $class)
{
# Opening Tag bereinigen
/*
|------------------------------------------------------------------------------------
| cleanup opening tag
*/
$class['OpeningTag'] = preg_replace("/[\n\t\r]+/", " ", $class['OpeningTag']);
$preg = preg_match('/ (?<=class.)[A-Za-z]*/', $class['OpeningTag'], $matches, PREG_OFFSET_CAPTURE);
$preg = preg_match('/(?<=clas{2}.)[A-Za-z]*/', $class['OpeningTag'], $matches, PREG_OFFSET_CAPTURE);
$classname = str_replace(" ", "",$matches[0][0]);
# Klassenkommentar hinzufügen
/*
|------------------------------------------------------------------------------------
| add comment to class
*/
$classstream .= $this->WriteComment($class['Comment'], 'Class "'.$classname.'"');
# Tag öffnen
/*
|------------------------------------------------------------------------------------
| open class tag
*/
$classstream .= $this->S().$class['OpeningTag']."\n";
$classstream .= $this->S().'{'."\n";
# Klassenvariablen einfügen (sofern vorhanden)
if(!empty($class['Variables']))
/*
|------------------------------------------------------------------------------------
| add optional class variables
*/
if(!empty($class['variables']))
{
# Zeilentiefe erhöhen
$this->Linedeph++;
/*
|--------------------------------------------------------------------------------
| increase linedepth
*/
$this->linedeph++;
# Kommentar vermerken
$classstream .= $this->WriteComment('', 'Klassenvariablen');
/*
|--------------------------------------------------------------------------------
| write title comment
*/
$classstream .= $this->WriteComment('', 'Variables');
# Variablen implodieren und einsetzen
$classstream .= $this->S().implode("\n".$this->S(), $class['Variables']);
/*
|--------------------------------------------------------------------------------
| setup variables
*/
$classstream .= $this->S().implode("\n".$this->S(), $class['variables']);
$classstream .= "\n\n";
# Zeilentiefe herabsetzen
$this->Linedeph--;
/*
|--------------------------------------------------------------------------------
| decrease linedepth
*/
$this->linedeph--;
}
/*
|------------------------------------------------------------------------------------
| Nachfolgend wird eine SubMethod zum Rendern der einzelnen Methodn aufgerufen.
| The following method renders the indivual methods to the class.
*/
$this->Linedeph++;
$classstream .= $this->RenderMethods($class['Methods']);
$this->Linedeph--;
$this->linedeph++;
$classstream .= $this->renderDocumentMethods($class['Methods']);
$this->linedeph--;
# Tag schließen
/*
|------------------------------------------------------------------------------------
| Close the class tag.
*/
$classstream .= $this->S().'}'."\n\n\n";
}
# Rückgabe
/*
|----------------------------------------------------------------------------------------
| Return the completed string.
*/
return $classstream;
}
......@@ -460,51 +599,59 @@ class CodebeautifierCommand extends Command
/*
|--------------------------------------------------------------------------------------------
| Method "RenderMethods"
| Method "renderDocumentMethods"
|--------------------------------------------------------------------------------------------
| Diese Method unterstützt den Renderprozess "Render" beim durchlaufen der einzelnen
| Methodn. Sie wird durch die Method "RenderClasses" aufgerufen.
| This method supports "renderDocument" when running through the individual methods. It is
| called by the "renderDocumentClasses" method.
*/
function RenderMethods($methods)
function renderDocumentMethods($methods)
{
# Informationsstream für Template erstellen
/*
|----------------------------------------------------------------------------------------
| create string for informations.
*/
$methodstream = '';
# Methodn alphabetisch ordnen
//$methods = MARR::OrderArray($methods, 'Title', SORT_ASC);
# jede Method durchlaufen
/*
|----------------------------------------------------------------------------------------
| Loop every method.
*/
foreach($methods as $method)
{
# Kommentar zur Method einfügen
/*
|------------------------------------------------------------------------------------
| Add individual comment to the method.
*/
$methodstream .= "\n";
$methodstream .= $this->WriteComment($method['Comment'], 'Method "'.$method['Title'].'"');
# Mit dieser Variable wird die Einrücktiefe auf Methodninterner Ebene geprüft
/*
|------------------------------------------------------------------------------------
| This variable is used to check the indentation depth on the internal method level.
*/
$internaldeph = 0;
/*
|------------------------------------------------------------------------------------
| Mit dieser Variabele wird vermerkt, ob das letzte Element, im nachfolgenden
| Durchlauf, ein Kommentar war.
| This variable is used to note whether the last element in the subsequent run was a
| comment.
*/
$lastwascomment = false;
$lastWasComment = false;
/*
|------------------------------------------------------------------------------------
| Jede Zeile der Method wird durch Explode getrennt und einzeln überprüft.
| Each line of the method is separated by explode and checked individually.
*/
foreach(explode("\n", $method['Body']) as $body)
{
/*
|--------------------------------------------------------------------------------
| Wird das "Close" Tag erkannt, wird die Einrücktiefe reudziert. Handelt es
| sich um die letzte Ebene (Ebene 0) wird ein weiteres Leerzeichen ergänzt.
| If the "Close" tag is recognized, the indentation depth is reduced. If it is
| the last level (level 0), an additional space is added.
*/
if(substr($body, 0,1) == '}')
{
$this->Linedeph--;
$this->linedeph--;
$internaldeph--;
if($internaldeph != 0)
......@@ -519,13 +666,13 @@ class CodebeautifierCommand extends Command
/*
|--------------------------------------------------------------------------------
| Nachfolgend werden Kommentare erkannt und eingesetzt.
| The folloiwing part does add comments.
*/
elseif(substr($body, 0,8) == '#COMMENT')
{
$comment = $this->GetCommentFromPregMatch('/#.+-.+-.+#/',$body );
$comment = $this->getCommentFromPregMatch('/#.+-.+-.+#/',$body );
if($lastwascomment == true)
if($lastWasComment == true)
{
$methodstream .= $this->WriteComment( $comment );
}
......@@ -533,13 +680,13 @@ class CodebeautifierCommand extends Command
{
$methodstream .= "\n".$this->WriteComment( $comment );
}
$lastwascomment = true;
$lastWasComment = true;
}
/*
|--------------------------------------------------------------------------------
| Für if, foreach, while und return wird ein weiterer Zeilenumbruch
| hinzugefügt, sofern das letzte Element kein Kommentar war.
| Another line break is added for if, foreach, while and return if the last
| element was not a comment.
*/
elseif(
(
......@@ -548,7 +695,7 @@ class CodebeautifierCommand extends Command
substr($body, 0,5) == 'while' or
substr($body, 0,6) == 'return'
)
and $lastwascomment == false
and $lastWasComment == false
)
{
$methodstream .= "\n".$this->S().$body."\n";
......@@ -556,32 +703,40 @@ class CodebeautifierCommand extends Command
/*
|--------------------------------------------------------------------------------
| Nachfolgend wird ganz normaler Text geschrieben, welcher zuvor nicht durch
| eine Sonderbehandlung erkannt wurde.
| In the following, normal text is written that was not previously recognized by
| special treatment.
*/
else
{
$methodstream .= $this->S().$body."\n";
$lastwascomment = false;
$lastWasComment = false;
}
/*
|--------------------------------------------------------------------------------
| Wir das "Open" Tag erkannt, wird die Einrücktiefe erhöht. "$lastwascomment"
| wird an dieser Stelle verwendet um, vor dem ersten Kommentar, den
| Zeilenumbruch zu vermeiden.
| If the "Open" tag is recognized, the indentation level is increased.
| "$lastWasComment" is used here to avoid the line break before the first
| comment.
*/
if(substr($body, 0,1) == '{')
{
$lastwascomment = true;
$this->Linedeph++;
$lastWasComment = true;
$this->linedeph++;
$internaldeph++;
}
}
/*
|------------------------------------------------------------------------------------
| Add another linebreak at the end of the method.
*/
$methodstream .= "\n";
}
# Rückgabe
/*
|----------------------------------------------------------------------------------------
| Return the completed method stream.
*/
return $methodstream;
}
......@@ -591,15 +746,15 @@ class CodebeautifierCommand extends Command
|--------------------------------------------------------------------------------------------
| Method "S"
|--------------------------------------------------------------------------------------------
| Diese Method ünterstützt das Script bei der aktuellen Einrücktiefe. Es gibt einen
| String mit den entsprechenden Leerzeichen zurück.
| This method supports the script at the current indentation level. It returns a string with
| the appropriate spaces.
*/
function S()
{
$c = 0;
$x = '';
while ($c < $this->Linedeph*4)
while ($c < $this->linedeph*4)
{
$c++;
$x .= ' ';
......@@ -612,32 +767,47 @@ class CodebeautifierCommand extends Command
/*
|--------------------------------------------------------------------------------------------
| Method "ScanClass"
| Method "scanClass"
|--------------------------------------------------------------------------------------------
| Diese Method ist für das einscannen der Klasse zuständig. Mit Hilfe der Method
| "MatchBetweenTwoPatterns" wird der jeweilige Bereich zwischen Start und Stop extrahiert.
| This method is responsible for scanning the class. With the help of the
| "matchBetweenTwoPatterns" method, the respective area between start and stop is extracted.
*/
function ScanClass()
function scanClass()
{
# Start Pattern
/*
|----------------------------------------------------------------------------------------
| start Pattern
*/
$OpenPattern = '/[^;{}$*"]+class[^a-z\\\[(=-][^{;()[\]]+/s';
# Stop Pattern
/*
|----------------------------------------------------------------------------------------
| stop Pattern
*/
$ClosePattern = '/([^;{$}>*$()"]+\s*class[^a-z\\[(=-])|[\s\t\n]+$/';
# Bereich extrahieren
$Classes = $this->MatchBetweenTwoPatterns($this->Content, $OpenPattern, $ClosePattern);
/*
|----------------------------------------------------------------------------------------
| extract inbetween
*/
$classes = $this->matchBetweenTwoPatterns($this->content, $OpenPattern, $ClosePattern);
# erkannte Klassen verarbeiten
foreach($Classes as $Class)
/*
|----------------------------------------------------------------------------------------
| loop detected clases.
*/
foreach($classes as $Class)
{
# Text der Klasse normalisieren
$Class = $this->Normalize($Class);
/*
|------------------------------------------------------------------------------------
| Normalize text of the class.
*/
$Class = $this->normalize($Class);
/*
|------------------------------------------------------------------------------------
| Nachfolgend wird überprüft, ob es sicht tatsächlich um eine Klasse handelt.
| Wenn nicht wird das Element nicht weiter bearbeitet.
| A check is then carried out to determine whether it is actually a class. If not,
| the element will not be processed any further.
*/
$preg = preg_match('/class[^{;()[\]]+/', $Class, $matches, PREG_OFFSET_CAPTURE);
......@@ -648,14 +818,14 @@ class CodebeautifierCommand extends Command
/*
|------------------------------------------------------------------------------------
| Die Beschreibung der Klasse wird extrahiert und vermerkt.
| The description of the class is extracted and noted.
*/
$description = $this->GetCommentFromPregMatch('/#.+-.+-.+#(?=(\n\s*class))/',$Class );
$description = $this->getCommentFromPregMatch('/#.+-.+-.+#(?=(\n\s*class))/',$Class );
/*
|------------------------------------------------------------------------------------
| Nachfolgend wird geprüft, ob Klassenvariablen vorhanden sind. Diese werden
| später vermerkt oder auf "false" gesetzt.
| A check is then carried out to determine whether class variables are available.
| These will be noted later or set to "false".
*/
$preg = preg_match_all('/(public|protected|private|var)\s*\$.*\;/', $Class, $variables, PREG_OFFSET_CAPTURE);
......@@ -673,8 +843,11 @@ class CodebeautifierCommand extends Command
$classvariables = false;
}
# Informationen aus der Klasse speichern
$this->Classes[] = ['OpeningTag' => $matches[0][0], 'Body' => $Class, 'Comment' => $description, 'Methods' => [] , 'Variables' => $classvariables];
/*
|------------------------------------------------------------------------------------
| Save informations to the class.
*/
$this->classes[] = ['OpeningTag' => $matches[0][0], 'Body' => $Class, 'Comment' => $description, 'Methods' => [] , 'variables' => $classvariables];
}
}
......@@ -682,93 +855,117 @@ class CodebeautifierCommand extends Command
/*
|--------------------------------------------------------------------------------------------
| Method "ScanComments"
| Method "scanComments"
|--------------------------------------------------------------------------------------------
| Diese Method ist dafür zuständig, Kommentare aus der Originaldatei zu extrahieren, und
| während des Verarbeitungsprozesses in ein ein einfacherers, temporäres Format zu
| übertragen. Der Originalinhalt des Kommentaras wird in der Klasse gepuffert.
| This method is responsible for extracting comments from the original file and transferring
| them to a simpler, temporary format during the processing process. The original content of
| the comment is buffered in the class.
*/
function ScanComments($Content)
function scanComments()
{
# Filter
preg_match_all('/^[\s]*(\/\/)[^\n]+|^[\s]*#.+[^\n]|(^|\s)+\/\*(.|\n)+?(?<=(\*\/))/m', $Content, $Comments, PREG_OFFSET_CAPTURE);
$content = $this->content;
# alle Kommentare durchlaufen
/*
|----------------------------------------------------------------------------------------
| Filter
*/
preg_match_all('/^[\s]*(\/\/)[^\n]+|^[\s]*#.+[^\n]|(^|\s)+\/\*(.|\n)+?(?<=(\*\/))/m', $content, $Comments, PREG_OFFSET_CAPTURE);
/*
|----------------------------------------------------------------------------------------
| Loop all comments.
*/
foreach($Comments[0] as $Com)
{
/*
|------------------------------------------------------------------------------------
| Das Kommentar wird zur besseren identifizierung gehasth.
| The comment is hashed for better control.
*/
$md = md5($Com[0]);
# Kommentar in den Puffer speichern
$this->Comments[$md] = $Com[0];
/*
|------------------------------------------------------------------------------------
| Save comment to the buffer.
*/
$this->comments[$md] = $Com[0];
}
/*
|----------------------------------------------------------------------------------------
| Nachfolgend wird das Kommentar nach Zeichenlänge sortiert. Damit wird ein Bug
| verhindert, welche kleinere, gleiche Strings falsch ersetzt.
| The comment is then sorted by character length. This prevents a bug which incorrectly
| replaces smaller, identical strings.
*/
usort($this->Comments, function($a, $b)
usort($this->comments, function($a, $b)
{
return strlen($b) - strlen($a);
});
/*
|----------------------------------------------------------------------------------------
| Die Kommentare werden aus dem Dokument entfernt.
| The comments are removed from the document.
*/
foreach($this->Comments as $key=>$value)
foreach($this->comments as $key=>$value)
{
$Content = str_replace($value, "\n#COMMENT-".$key."-COMMENT#\n", $Content);
$content = str_replace($value, "\n#COMMENT-".$key."-COMMENT#\n", $content);
}
# Rückgabe
return $Content;
/*
|----------------------------------------------------------------------------------------
| The cleaned content is returned.
*/
$this->content = $content;
return $content;
}
/*
|--------------------------------------------------------------------------------------------
| Method "ScanMethods"
| Method "scanMethods"
|--------------------------------------------------------------------------------------------
| Diese Method scannt alle Methodn jeder Klasse ein und vermerkt diese.
| This method scans all methods of each class and notes them.
*/
function ScanMethods()
function scanMethods()
{
# alle Klassen durchlaufen
foreach($this->Classes as $Key=>$Class)
/*
|----------------------------------------------------------------------------------------
| Loop all classes.
*/
foreach($this->classes as $Key=>$Class)
{
# Methodn Klasse
/*
|------------------------------------------------------------------------------------
| Create an array for methods.
*/
$Methods = array();
/*
|------------------------------------------------------------------------------------
| Nachfolgend werden überreste der Klasse aus dem String entfernt, um nur nach
| Methodn suchen zu können.
| In the following, remnants of the class are removed from the string in order to be
| able to search for methods only.
*/
$ClassStart = strpos($Class['Body'] , '{')+1;
$ClassStop = strrpos($Class['Body'] , '}');
$Classstart = strpos($Class['Body'] , '{')+1;
$Classstop = strrpos($Class['Body'] , '}');
$ClassCount = strlen($Class['Body']);
$Prepared = substr($Class['Body'], $ClassStart, ($ClassCount-$ClassStart)-($ClassCount-$ClassStop)) ;
$Prepared = substr($Class['Body'], $Classstart, ($ClassCount-$Classstart)-($ClassCount-$Classstop)) ;
/*
|------------------------------------------------------------------------------------
| Ähnlich wie beim extrahieren der Klassen, wird bei den Methodn ein Start und
| Stoppattern definiert. Zwischen diesen regulären Ausdrücken werden die Methodn
| extrahiert.
| Similar to extracting the classes, a start and stopPattern is defined for the
| methods. The methods are extracted between these regular expressions.
*/
$OpenPattern = '/([^;{}]+function[^a-z\\\[(][^{;()[\]]+)/';
$ClosePattern = '/([^;{$}>\'"*]+\s*function[^a-z\\[(])|[\s\t\n]+$/';
$Results = $this->MatchBetweenTwoPatterns($Prepared, $OpenPattern, $ClosePattern);
$results = $this->matchBetweenTwoPatterns($Prepared, $OpenPattern, $ClosePattern);
# alle Methodn verarbeiten
foreach($Results as $Result)
/*
|------------------------------------------------------------------------------------
| Loop all methods.
*/
foreach($results as $result)
{
preg_match('/(private|public|protected|static)*\s*function\s*\w+.*(?<=\))/', $Result, $opener, PREG_OFFSET_CAPTURE);
preg_match('/(private|public|protected|static)*\s*function\s*\w+.*(?<=\))/', $result, $opener, PREG_OFFSET_CAPTURE);
if(!isset($opener[0]))
{
......@@ -777,29 +974,28 @@ class CodebeautifierCommand extends Command
/*
|--------------------------------------------------------------------------------
| Mit Hilfe der nachfolgenden Verschachtelung, wird der Title der Method
| extrahiert.
| With the help of the following nesting, the title of the method is extracted.
*/
$OpenerArray = str_replace(' ' , '', explode( '(',str_replace(')','',$opener[0][0])));
$Title = substr($OpenerArray[0], (strrpos($OpenerArray[0],'function')+8) );
$description = $this->GetCommentFromPregMatch('/#.+-.+-.+#(?=(\n(public|protected|private|static|\s)*function))/',$Result );
$description = $this->getCommentFromPregMatch('/#.+-.+-.+#(?=(\n(public|protected|private|static|\s)*function))/',$result );
/*
|--------------------------------------------------------------------------------
| Mit diesem Befehl wird das Kommentar vor der Funktion entfernt
| (Duplettenschutz).
| This command removes the comment before the function (duplicate protection).
*/
$Result = preg_replace('/(#COMMENT.+\s*(?=(\n.*function[^a-z\\[(])))/', '', $Result);
$result = preg_replace('/(#COMMENT.+\s*(?=(\n.*function[^a-z\\[(])))/', '', $result);
/*
|--------------------------------------------------------------------------------
| Nach mehrfacher Änderung wird der String normalisiert.
| After multiple changes, the string is normalized.
*/
$Result = $this->Normalize($Result);
$result = $this->normalize($result);
/*
|--------------------------------------------------------------------------------
| Aus der Parameter Array darf nur alle, nach dem Dollerzeichen verwendet werden.
| From the parameter array, only all those after the dollar are allowed to be
| used.
*/
$afterdollar = [];
......@@ -808,58 +1004,25 @@ class CodebeautifierCommand extends Command
$afterdollar[] = preg_replace('/.+(?=(\$))/', '', $dollar);
}
# Method speichern
/*
|--------------------------------------------------------------------------------
| Save the method.
*/
$Methods[] = [
'Title' => $Title,
'Parameter' => $afterdollar,
'Comment' => $description,
'Body' => $Result
'Body' => $result
];
}
# alle Methodn in der Klasse vermerken
$this->Classes[$Key]['Methods'] = $Methods;
}
}
/*
|--------------------------------------------------------------------------------------------
| Method "SimpleFilter"
|--------------------------------------------------------------------------------------------
| Diese Method hat die Aufgabe, Textbausteine aus einer bestehenden Dokumentation zu
| extrahieren. Zur besseren Verarbeitung werden leerzeichen entfernt.
*/
function SimpleFilter($String, $Pattern)
{
# Sonderzeichen entfernen
$String = str_replace("\n", '', $String);
# Pattern
preg_match($Pattern, $String, $Extract);
# Fallback
if(!isset($Extract[0]))
{
return '';
}
# Anfang bereinigen
if(substr($Extract[0], 0,4) == '</p>')
{
$Extract[0] = substr($Extract[0], 4);
}
# Ende bereinigen
if(substr($Extract[0], -3) == '<p>')
{
$Extract[0] = substr($Extract[0], 0, -3);
/*
|------------------------------------------------------------------------------------
| Save all methods from the class.
*/
$this->classes[$Key]['Methods'] = $Methods;
}
# Rückgabe
return $Extract[0];
}
......@@ -867,40 +1030,38 @@ class CodebeautifierCommand extends Command
|--------------------------------------------------------------------------------------------
| Method "WriteComment"
|--------------------------------------------------------------------------------------------
| Diese Method unterstützt beim erstellen, eines korrekt formatierten Kommentars. Mit der
| Variable "$fake" wird nur der Text des Kommentars zurück gegeben.
| This method helps to create a correctly formatted comment. With the variable "$fake" only
| the text of the comment is returned.
*/
function WriteComment($comment, $title = null, $fake = false)
{
/*
|----------------------------------------------------------------------------------------
| Die nachfolgende Variable startet den String für ein neues Kommentar.
| The following variable starts the string for a new comment.
*/
$k = '';
/*
|----------------------------------------------------------------------------------------
| nachfolgend wird das übertagene Kommentar bereinigt und normalisiert.
| Subsequently the transmitted comment is cleaned up and normalized.
*/
$comment = preg_replace('/[^a-zA-Z:,.0-9_=$+!? äÄüÜÖöß"\'()]/', '', $comment);
$comment = $this->Normalize($comment);
$comment = $this->normalize($comment);
/*
|----------------------------------------------------------------------------------------
| Der Beautifier verwendet für z.B. Klassen und Methodn bestimmte Keywords. Diese
| werden hier gefiltert um bei mehrfachen Renderprozessen keine Dupletten zu bilden.
| The beautifier uses certain keywords for e.g. classes and methods. These are filtered
| here in order not to create duplicates in multiple render document processes.
*/
if(strpos($comment, $title) === 0)
{
$comment = substr($comment, strlen($title));
$comment = $this->Normalize($comment);
$comment = $this->normalize($comment);
}
/*
|----------------------------------------------------------------------------------------
| Das Kommentar wird im Fakemodus ohne Formatierung zurück gegeben.
| The comment is returned in fake mode without formatting.
*/
if($fake == true)
{
......@@ -909,28 +1070,21 @@ class CodebeautifierCommand extends Command
/*
|----------------------------------------------------------------------------------------
| Das Kommentar wird auf mehrere Zeilen aufgeteilt (sofern mehrere Zeilen vorhanden
| sind).
| The comment is split over several lines (if there are several lines).
*/
$comment = wordwrap($comment,98 - (strlen($this->S())));
$comment = explode("\n", $comment);
/*
|----------------------------------------------------------------------------------------
| Falls das Kommentar mehr als eine Zeile besitzt oder ein Title übergeben wurde, wird
| ein großes Kommentar verwendet. Andernfalls wird nur ein einzeiliges Kommentar
| eingesetzt.
| At the moment, only large comments are supportet.
*/
if($title != null or isset($comment[1]) or strstr($comment[0], '.'))
{
$large = true;
}
else
{
$large = false;
}
$large = true;
# großes Kommentar verarbeiten
/*
|----------------------------------------------------------------------------------------
| Large comment...
*/
if($large == true )
{
$k = $this->S().'/*'."\n";
......@@ -952,15 +1106,24 @@ class CodebeautifierCommand extends Command
$k .= $this->S().'*/'."\n";
}
# kleines Kommentar verarbeiten
/*
|----------------------------------------------------------------------------------------
| Small comment...
*/
else
{
$k .= $this->S().'# '.$comment[0]."\n";
}
# Rückgabe
/*
|----------------------------------------------------------------------------------------
| Return the comment.
*/
return $k;
}
}
......@@ -10,7 +10,7 @@
| sidekick package.
|
| Author: Marco Schmiedel <marco.schmiedel@itmax.email>
| Date: 2021-12-20 15:21:14
| Date: 2021-12-20 15:38:03
|
*/
namespace Ceetrox\Managers\TerminalManager;
......@@ -28,7 +28,7 @@
| Class "TerminalManager"
|------------------------------------------------------------------------------------------------
*/
class TerminalManager
class TerminalManager
{
/*
......@@ -79,25 +79,25 @@
{
/*
|----------------------------------------------------------------------------------------
| Create an empty string for all upcoming colors...
| Create an empty string for all upcoming colors.
*/
$text = "\n";
/*
|----------------------------------------------------------------------------------------
| Create counter value...
| Create the counter value.
*/
$i1=16;
/*
|----------------------------------------------------------------------------------------
| Loop counter value within the color range...
| Loop counter value within the color range.
*/
while ( $i1 < 52 )
{
/*
|------------------------------------------------------------------------------------
| Calculate 7 columns per line...
| Calculate 7 columns per line.
*/
$i1=$i1;
$i2=$i1+36;
......@@ -111,7 +111,7 @@
/*
|------------------------------------------------------------------------------------
| Calculate for bright and dark...
| Calculate output for bright and dark colors.
*/
$text .= TerminalManager::darkColor(" D".str_pad($i1, 3, "0", STR_PAD_LEFT)." ",$i1);
$text .= TerminalManager::darkColor(" D".str_pad($i2, 3, "0", STR_PAD_LEFT)." ",$i2);
......@@ -130,17 +130,21 @@
/*
|------------------------------------------------------------------------------------
| Add linebreak...
| Add break at the end of the line.
*/
$text .= "\n";
/*
|------------------------------------------------------------------------------------
| Add value to counter...
| Increase value to the line counter.
*/
$i1 += 1;
}
/*
|----------------------------------------------------------------------------------------
| Return string for terminal output.
*/
return $text;
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment