Пример #1
0
 /**
  * Erstellt eine neue Rule durch eine Spezifikation (was so quasi alles sein kann)
  *
  * Die Parameter dieser Funktion sind sehr Variabel
  * Möglicherweise ist es einfacher generate[A-Za-z+]Rule zu benutzen
  */
 public static function generateRule($ruleSpecification)
 {
     $rs = $ruleSpecification;
     if (is_string($rs)) {
         if ($rs == 'nes') {
             return new NesValidatorRule();
         }
         if ($rs == 'id') {
             return new IdValidatorRule();
         }
         if ($rs == 'pi' || $rs == 'pint') {
             return new PositiveIntValidatorRule();
         }
         if ($rs == 'array') {
             return new ArrayValidatorRule();
         }
         if ($rs == 'pi0' || $rs == 'pint0') {
             $rule = new PositiveIntValidatorRule();
             $rule->setZeroAllowed(TRUE);
             return $rule;
         }
         if (S::startsWith($rs, '/') && S::endsWith($rs, '/')) {
             return self::generateRegexpRule($rs);
         }
         $c = '\\' . __NAMESPACE__ . '\\' . ucfirst($rs) . 'ValidatorRule';
         if (class_exists($c)) {
             return new $c();
         }
         throw new \Psc\Exception('Unbekannte Parameter für generateRule ' . Code::varInfo($rs));
     }
     if (is_array($rs)) {
         $num = count($rs);
     }
     throw new \Psc\Exception('Unbekannte Parameter für generateRule ' . Code::varInfo($rs));
 }
Пример #2
0
 public function testMethod()
 {
     $class = new ReflectionClass('Psc\\Code\\Generate\\TestClass2');
     $factory = GMethod::reflectorFactory($class->getMethod('factory'));
     $method2 = GMethod::reflectorFactory($class->getMethod('method2'));
     $banane = GMethod::reflectorFactory($class->getMethod('banane'));
     $parameters = $method2->getParameters();
     foreach ($parameters as $param) {
         $this->assertInstanceOf('Psc\\Code\\Generate\\GParameter', $param);
     }
     $cr = "\n";
     $factoryCode = 'public static function factory(TestHintMethod $dunno) {' . $cr;
     $factoryCode .= '}';
     $this->assertEquals(0, count($factory->getBodyCode()));
     $this->assertEquals('', $factory->getBody(0));
     $method2Code = 'public function method2($num, Array $p1, stdClass $std = NULL, $bun = array()) { // does matter' . $cr;
     $body = NULL;
     $body .= '$bimbam = \'pling\';' . $cr;
     $body .= $cr;
     $body .= '// anotherinline comment' . $cr;
     $body .= 'return \'schnurpsel\';' . $cr;
     $method2Code .= S::indent($body, 2, $cr);
     $method2Code .= '}';
     $method2->getBodyCode();
     // 2 mal holen darf die anzahl nicht verdoppeln
     $this->assertEquals(4, count($method2->getBodyCode()));
     /* method2 method */
     $this->assertEquals($body, $method2->getBody(0), \Webforge\Common\String::debugEquals($body, $method2->getBody(0)));
     $this->assertEquals($method2Code, $method2->php(), \Webforge\Common\String::debugEquals($method2Code, $method2->php()));
     /* Factory method */
     $this->assertEquals(TRUE, $factory->isStatic());
     $this->assertEquals($factoryCode, $factory->php(), \Webforge\Common\String::debugEquals($factoryCode, $factory->php()));
     $this->assertEquals('abstract public function banane();', $banane->php(), sprintf("output: '%s'", $banane->php()));
 }
Пример #3
0
 protected function expandSourceAndDestination($source, $destination = NULL)
 {
     if (is_string($source)) {
         $sourceUrl = $source;
         if (S::endsWith($source, '/')) {
             $source = $this->sourceProject->getRootDirectory()->sub($source);
         } else {
             $source = File::createFromURL($source, $this->sourceProject->getRootDirectory());
         }
     }
     if (!isset($destination)) {
         if (!isset($sourceUrl)) {
             $sourceUrl = $source->getUrl($this->sourceProject->getRootDirectory());
             if ($source instanceof Dir) {
                 $sourceUrl .= '/';
             }
         }
         $destination = $sourceUrl;
     }
     if (is_string($destination)) {
         if (S::endsWith($destination, '/')) {
             $destination = $this->targetProject->getRootDirectory()->sub($destination);
         } else {
             $destination = File::createFromURL($destination, $this->targetProject->getRootDirectory());
         }
     }
     return array($source, $destination);
 }
Пример #4
0
 /**
  * Scannt ein Verzeichnis nach einem Dateipattern und
  * vergleicht dabei die Versionen um die aktuellste Version dieser Datei zurückgeben zu können
  *
  * Als Beispiel:
  * jquery-1.3.2.min.js
  * jquery-1.4.1.min.js
  * jquery-1.5.1.min.js
  * jquery-1.5.2.min.js
  *
  * gibt logischerweise jquery-1.5.2.min.js zurück
  *
  * @param string $directory das Verzeichnis (mit trailingsslash) welches durchsucht werden soll
  * @param string $search sollte der String am Anfang der Datei sein. Dies kann auch eine regexp sein (mit / umschlossen)
  * @param array $fileRegexps können zusätzliche reguläre Ausdrücke sein um aus einer Datei den Versionsstring herauszubekommen, diese werden benutzt, wenn das normale vorgehen (match ((?:[0-9]\.)+[0-9]) scheitert
  */
 public static function getLatestFileVersion($directory, $search, array $fileRegexps = array())
 {
     $standardRx = '/((?:[0-9]\\.)+[0-9])/';
     $files = glob($directory . '*.*');
     $maxFile = NULL;
     $maxVersion = 0;
     $searchRx = S::startsWith($search, '/') ? $search : '/^' . $search . '/';
     foreach ($files as $file) {
         $fileName = basename($file);
         if (preg::match($fileName, $searchRx) > 0) {
             if (($version = preg::qmatch($fileName, $standardRx, 1)) == '') {
                 foreach ($fileRegexps as $fileRx) {
                     if (($version = preg::qmatch($fileName, $fileRegexps)) != '') {
                         break;
                     }
                 }
             }
             if ($version == '') {
                 throw new Exception('Für Datei: "' . $fileName . '" konnte keine Version extrahiert werden');
             }
             if (version_compare($version, $maxVersion, '>')) {
                 $maxVersion = $version;
                 $maxFile = $file;
             }
         }
     }
     return array($maxFile, $maxVersion);
 }
Пример #5
0
 public function foldValue($value)
 {
     $value = \Webforge\Common\String::fixEOL($value);
     $value = wordwrap($value, 74, "\n", TRUE);
     $value = str_replace("\n", "\n ", $value);
     return $value;
 }
Пример #6
0
 /**
  * Gibt das JSON für den String zurück
  *
  * asserted dass das dekodieren auch klappt
  * @param $array macht alle objekte im json zu arrays! (huh)
  * @return object|array
  */
 public function json($json, $array = FALSE, $canBeEmpty = FALSE)
 {
     $data = json_decode($json, $array);
     $json_errors = array(JSON_ERROR_NONE => 'Es ist kein Fehler zuvor aufgetreten, aber der Array ist leer. Es kann mit dem 3ten Parameter TRUE umgangen werden, dass der Array überprüft wird', JSON_ERROR_DEPTH => 'Die maximale Stacktiefe wurde erreicht', JSON_ERROR_CTRL_CHAR => 'Steuerzeichenfehler, möglicherweise fehlerhaft kodiert', JSON_ERROR_SYNTAX => 'Syntax Error');
     if ($canBeEmpty && (is_array($data) || is_object($data))) {
         return $data;
     }
     $this->testCase->assertNotEmpty($data, "JSON Error: " . $json_errors[json_last_error()] . " für JSON-String: '" . \Webforge\Common\String::cut($json, 100, '...'));
     return $data;
 }
Пример #7
0
 public function guessLabel($identifier)
 {
     if (array_key_exists($identifier, $this->commonLabels)) {
         return $this->commonLabels[$identifier];
     }
     // camelCase => camel Case
     $identifier = Preg::replace($identifier, '/([a-z])([A-Z])/', '$1 $2');
     // camel Case => Camel Case
     return S::ucfirst($identifier);
 }
Пример #8
0
 /**
  *
  * @param File $out die Datei in die das phar geschrieben werden soll
  * @param Dir $classPath das Verzeichnis für die Dateien von $namespace z. B. Umsetzung\base\src\SerienLoader\
  * @param string $namespace der Name des Namespaces dessen Klassen in $classPath liegen z. B. SerienLoader
  */
 public function __construct(File $out, Dir $classPath, $namespace, $logger = NULL)
 {
     $this->out = $out;
     $this->namespace = $namespace;
     $this->classPath = $classPath;
     $this->logger = $logger;
     $this->logLevel = 2;
     if (\Webforge\Common\String::endsWith($this->namespace, '_')) {
         $this->underscoreStyle = TRUE;
     }
 }
Пример #9
0
 protected function expandDestination($destination)
 {
     if (is_string($destination)) {
         if (S::endsWith($destination, '/')) {
             $destination = $this->targetProject->getRoot()->sub($destination);
         } else {
             $destination = Dir::createFromURL($destination, $this->targetProject->getRoot());
         }
     }
     return $destination;
 }
Пример #10
0
 /**
  * @return array mit den Werten als relative Pfade getrennt mit / (unsortiert)
  */
 public function listFiles()
 {
     $out = $this->exec('vb');
     $out = S::fixEOL($out);
     $files = explode("\n", $out);
     $files = array_filter($files);
     $files = array_map(function ($file) {
         return str_replace(DIRECTORY_SEPARATOR, '/', $file);
     }, $files);
     return $files;
 }
Пример #11
0
 public function testExtractFile()
 {
     $destination = $this->newFile('unpacked.srt');
     $destination->delete();
     $archive = $this->getArchive('3files.rar');
     $files = $archive->listFiles();
     sort($files);
     $srt = $files[1];
     $archive->extractFile($srt, $destination);
     $this->assertFileExists((string) $destination);
     $this->assertGreaterThan(0, $destination->getSize());
     // das asserted, dass der Anfang der Datei gleich ist, da hier die Credits von unrar nicht reinsollen
     $this->assertEquals($start = "1\r\n00:00:00,475 --> 00:00:04,995\r\nHey, what do you guys think of my new ducky tie?\r\nPretty cute, right?", mb_substr($destination->getContents(), 0, 103), \Webforge\Common\String::debugEquals($start, mb_substr($destination->getContents(), 0, 103)));
 }
Пример #12
0
    public function run()
    {
        if (!isset($this->changes) || !is_array($this->changes)) {
            throw new \InvalidArgumentException('changes muss gesetzt sein');
        }
        if (!$this->changelog->exists()) {
            throw new \RuntimeException('changelogFile ' . $targetFile . ' muss existieren');
        }
        require $this->changelog;
        /* changeslist : 
           
           'bugfix: Im Sound Content stand nur "content" statt dem eigentlichen Soundtext',
           'geändert: Bei der Soundsuche wird bei sehr großen Results das Ergebnis auf 15 Einträge eingeschränkt'
           
           */
        /* version */
        //2.0.9-Beta
        $version = \Psc\Preg::qmatch($data[0]['version'], '/^([0-9]+)\\.([0-9]+)\\.([0-9]+)\\-(Alpha|Beta|Gamma)$/i', array(1, 2, 3, 4));
        if (!is_array($version)) {
            throw new \RuntimeException('Fehler beim Version Parsing. Alte Version ' . $oldVersion);
        }
        if ($this->versionIncrement === 'minor') {
            $version[2]++;
        } else {
            throw new \InvalidArgumentException('Kann nichts anderes als minor für versionIncrement');
        }
        $newVersion = vsprintf('%d.%d.%d-%s', $version);
        $php = <<<'PHP'
$data[] = array(
  'version'=>'%version%',
  'time'=>'%time%',
  'changelog'=>array(
    %changesList%
  )
);

PHP;
        $php = \Psc\TPL\TPL::miniTemplate($php, array('version' => $newVersion, 'time' => date('H:i d.m.Y'), 'changesList' => \Webforge\Common\ArrayUtil::implode($this->changes, ",\n    ", function ($change) {
            return var_export($change, true);
        })));
        $contents = $this->changelog->getContents();
        $pos = mb_strpos($contents, $needle = '$data = array();' . "\n");
        if ($pos === FALSE) {
            throw new \RuntimeException('Cannot Modify File: ' . \Webforge\Common\String::cutAt($contents, 300) . ' enhält nicht ' . $needle);
        }
        $pos += mb_strlen($needle);
        $contents = mb_substr($contents, 0, $pos) . $php . "\n" . mb_substr($contents, $pos);
        $this->changelog->writeContents($contents);
    }
Пример #13
0
 public function createRule($class, array $constructorParams = array())
 {
     if ($class instanceof ValidatorRule) {
         return $class;
     }
     if (!\Webforge\Common\String::endsWith($class, 'ValidatorRule')) {
         $class .= 'ValidatorRule';
     }
     $class = ClassUtil::expandNamespace($class, 'Psc\\Form');
     if (count($constructorParams) === 0) {
         return new $class();
     } else {
         return ClassUtil::newClassInstance($class, $constructorParams);
     }
 }
Пример #14
0
 public function testSaveImageThumbnailInOtherFormatThanpng()
 {
     $this->resetDatabaseOnNextTest();
     $image = $this->manager->store($this->im('image2.jpg'), $title = 'my nice title');
     $url = $image->getUrl('thumbnail', array(300, 200, 'outbound'), array('format' => 'jpg', 'quality' => 70));
     // /dimg bla
     if (S::startsWith($url, '/dimg/')) {
         $url = mb_substr($url, 6);
     }
     $file = File::createFromURL($url, $this->cacheDir);
     $this->assertTrue($file->exists(), $file . ' does not exist');
     $this->assertEquals('jpg', $file->getExtension());
     $finfo = finfo_open(FILEINFO_MIME_TYPE);
     $mimeType = finfo_file($finfo, (string) $file);
     finfo_close($finfo);
     $this->assertEquals('image/jpeg', $mimeType);
 }
Пример #15
0
 public function errorToString($error)
 {
     $context = array_key_exists($error->line - 1, $this->rawLines) ? $this->rawLines[$error->line - 1] : '[no context avaible]';
     $ret = NULL;
     switch ($error->level) {
         case LIBXML_ERR_WARNING:
             $ret .= "Libxml-Warning {$error->code}: ";
             break;
         case LIBXML_ERR_ERROR:
             $ret .= "Libxml-Error {$error->code}: ";
             break;
         case LIBXML_ERR_FATAL:
             $ret .= "Libxml-Fatal Error {$error->code}: ";
             break;
     }
     $ret .= trim($error->message) . "\n  near: '" . \Webforge\Common\String::cut($context, 140, "'...") . "\n  Line: {$error->line}" . "\n  Column: {$error->column}";
     return $ret;
 }
Пример #16
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $project = \Psc\PSC::getProject();
     $em = $project->getModule('Doctrine')->getEntityManager($input->getOption('con'));
     try {
         $r = new \Psc\Form\EmailValidatorRule();
         $email = $r->validate($input->getArgument('email'));
     } catch (\Exception $e) {
         $output->writeln('FEHLER: E-Mail-Adresse ist nicht korrekt.');
         return 1;
     }
     if (($password = $input->getOption('password')) == NULL) {
         $password = \Webforge\Common\String::random(6);
     }
     $c = $project->getUserClass();
     if ($input->getOption('reset-password') == TRUE) {
         $userRep = $em->getRepository($c);
         $user = $userRep->find($email);
         if (!$user instanceof \Psc\CMS\User) {
             $output->writeln('User mit der Email: "' . $email . '" nicht gefunden.');
             return 2;
         }
         $output->writeln('Passwort Reset für: ' . $email);
     } else {
         $user = new $c($email);
     }
     $user->hashPassword($password);
     try {
         $em->persist($user);
         $em->flush();
     } catch (\PDOException $e) {
         if (\Psc\Doctrine\Exception::convertPDOException($e) instanceof \Psc\Doctrine\UniqueConstraintException) {
             $output->writeln('User existiert bereits. --reset-password / -r nehmen, um ein neues Passwort zu erzeugen');
             return 3;
         }
         throw $e;
     }
     $output->writeln(sprintf('Passwort: "%s"', $password));
     $output->writeln('done.');
     return 0;
 }
Пример #17
0
 /**
  * Wie man hier sehen kann, ist des natürlich Käse
  * aber ich hab keine Lust auf den ganzen Annotation-Rumble
  * (siehe Annotation.php)
  * @TODO ding dong (Annotation Writer schreiben)
  */
 public function addSimpleAnnotation($name, array $values = array())
 {
     if (isset($this->body)) {
         $this->body .= "\n";
     }
     $this->body .= S::expand((string) $name, '@', S::START);
     if (count($values) > 0) {
         $this->body .= '(';
         foreach ($values as $key => $value) {
             if (is_string($value)) {
                 $this->body .= sprintf('%s="%s", ', $key, str_replace('"', '""', $value));
             } elseif (is_integer($value)) {
                 $this->body .= sprintf('%s=%d, ', $key, $value);
             } elseif (is_array($value)) {
                 throw new Exception('Ich kann keine verschachtelten Arrays');
             } else {
                 throw new Exception('Ich kann noch nichts anderes');
             }
         }
         $this->body = mb_substr($this->body, 0, -2);
         $this->body .= ')';
     }
     return $this;
 }
Пример #18
0
 /**
  * {@inheritdoc}
  */
 public function startQuery($sql, array $params = null, array $types = null)
 {
     if ($params != NULL) {
         foreach ($params as $p) {
             try {
                 if (is_array($p)) {
                     $p = Helper::implodeIdentifiers($p);
                 }
             } catch (\Exception $e) {
                 $p = '[unconvertible array]';
             }
             if (is_string($p)) {
                 $p = "'" . \Webforge\Common\String::cut($p, 50, '...') . "'";
             }
             if ($p instanceof \DateTime) {
                 $p = $p->format('YDM-H:I');
             }
             $sql = preg_replace('/\\?/', (string) $p, $sql, 1);
             // ersetze das erste ? mit dem parameter
         }
     }
     print $sql . PHP_EOL;
     flush();
 }
Пример #19
0
use Webforge\Setup\ConfigurationTester\ConfigurationTester;
use Psc\System\System;
use Psc\Code\Generate\ClassWriter;
use Webforge\Common\JS\JSONConverter;
use Psc\JS\jQuery;
use Seld\JsonLint\JsonParser;
/**
 *
 * $createCommand = function ($name, array|closure $configure, closure $execute) {
 * 
 * $arg = function ($name, $description = NULL, $required = TRUE) // default: required
 * $opt = function($name, $short = NULL, $withValue = TRUE, $description = NULL) // default: mit value required
 * $flag = function($name, $short = NULL, $description) // ohne value
 */
$createCommand('compile:komodo-command-call', array($arg('extension-name')), function ($input, $output, $command) {
    $extensionClass = Code::expandNamespace(\Webforge\Common\String::expand($input->getArgument('extension-name'), 'Extension'), 'Psc\\Code\\Compile');
    $extension = GClass::factory($extensionClass);
    $fields = array();
    if ($extension->hasMethod('__construct')) {
        foreach ($extension->getMethod('__construct')->getParameters() as $param) {
            $fields[] = $param->getName();
        }
    }
    // das nimmt vielleicht zu viele, weis nicht, alternativ würds auch ne statische methode zur extension tun
    foreach ($extension->getProperties() as $property) {
        $fields[] = $property->getName();
    }
    $json = array();
    foreach (array_unique($fields) as $field) {
        $json[$field] = '%(ask:' . $field . ')';
    }
Пример #20
0
 /**
  * Gibt die Klasse (den vollen Namen) eines Entities zurück
  * 
  * speaker => 'projectNamespace\Entities\Speaker'
  * oid => 'projectNamespace\Entities\OID'
  *
  * Dies wird z.B. für die Umwandlung von entity-bezeichnern in URLs in echte Klassen gebraucht.
  * Irreguläre Namen (sowas wie OID) können in $this->getEntityNames() eingetragen werden
  *
  * @param string $input kann ein Name in LowerCase sein, eine volle Klasse oder auch ein TabsContentItem2::getTabsResourceName() sein
  */
 public function getEntityName($input)
 {
     if (is_string($input)) {
         if (array_key_exists($input, $names = $this->getEntityNames())) {
             $name = $names[$input];
         } elseif (mb_strpos($input, '\\') === FALSE) {
             $name = \Webforge\Common\String::ucfirst($input);
         } else {
             $name = $input;
         }
         return Code::expandNamespace($name, $this->getEntitiesNamespace());
     }
     throw new \Psc\Exception('unbekannter Fall für getEntityName. Input ist: ' . Code::varInfo($input));
 }
Пример #21
0
 public static function escapeArgument($argument, $commandQuotes = String::DOUBLE_QUOTE)
 {
     $otherQuote = $commandQuotes == String::DOUBLE_QUOTE ? String::SINGLE_QUOTE : String::DOUBLE_QUOTE;
     /* wenn das letzte zeichen von argument ein backslash ist würde dies das quoting escapen.
           also escapen wird den backslash indem wir einen weiteren backslash anfügen
        */
     if (String::endsWith($argument, String::BACKSLASH) && !String::endsWith(mb_substr($argument, 0, -1), String::BACKSLASH)) {
         $argument = $argument . String::BACKSLASH;
     }
     $argument = $otherQuote . addcslashes($argument, $otherQuote) . $otherQuote;
     return $argument;
 }
Пример #22
0
 protected function phpBody($baseIndent = 0)
 {
     $php = NULL;
     $cr = "\n";
     // das hier zuerst ausführen, damit möglicherweise cbraceComment noch durchrs extracten gesetzt wird
     $body = $this->getBody($baseIndent + 2, $cr);
     // Body direkt + 2 einrücken
     $php .= ' {';
     // das nicht einrücken, weil das direkt hinter der signatur steht
     if ($this->cbraceComment != NULL) {
         // inline comment wie dieser
         $php .= ' ' . $this->cbraceComment;
     }
     $php .= $cr;
     // jetzt beginnt der eigentlich body
     $php .= $body;
     $php .= S::indent('}', $baseIndent, $cr);
     // das auf Base einrücken
     return $php;
 }
Пример #23
0
 /**
  * wird automatisch mit dependencies erstellt
  * @param string $name der Name des Tasks ohne Namespace und "Task" dahinter
  */
 public function createTask($name)
 {
     $this->init();
     $class = Code::expandNamespace(\Webforge\Common\String::expand($name, 'Task'), 'Psc\\System\\Deploy');
     $gClass = GClass::factory($class);
     $params = array();
     if ($gClass->hasMethod('__construct')) {
         $constructor = $gClass->getMethod('__construct');
         foreach ($constructor->getParameters() as $parameter) {
             $params[] = $this->resolveTaskDependency($parameter, $gClass);
         }
     }
     return $gClass->newInstance($params);
 }
Пример #24
0
 protected function parseExtensionGClass($input)
 {
     $extensionClass = Code::expandNamespace(\Webforge\Common\String::expand($input->getArgument('name'), 'Extension'), 'Psc\\Code\\Compile');
     return GClass::factory($extensionClass);
 }
Пример #25
0
 /**
  * return array
  */
 public function getRequestPath()
 {
     $uri = $this->getRequestURI();
     if (\Webforge\Common\String::startsWith($uri, '/index.php')) {
         $uri = mb_substr($uri, mb_strlen('index.php'));
     }
     if (empty($uri) || $uri == '/') {
         return array();
     }
     $uri = ltrim($uri, '/');
     $parts = explode('/', $uri);
     return array_filter($parts, function ($p) {
         return trim($p) != '';
     });
 }
Пример #26
0
 /**
  * Bestimmt ob für eine Klasse des Projektes ein Test erstellt werden soll, wenn diese automatisch erstellt wird
  *
  * z. B. Exceptions haben erstmal keinen Test
  */
 public function shouldAutomaticTestCreated(GClass $class)
 {
     if (\Webforge\Common\String::endsWith($class->getName(), 'Exception')) {
         return FALSE;
     }
     /* more exceptions to come */
     return TRUE;
 }
Пример #27
0
 /**
  * 
  * @param string $source der PHP Code als String
  */
 protected function scan($source)
 {
     $source = str_replace(array("\r\n", "\r"), "\n", $source);
     if ($this->eol != "\n") {
         $source = str_replace("\n", $this->eol, $source);
     }
     /* token get all ist php intern */
     $currentLine = 1;
     foreach (token_get_all($source) as $token) {
         if (is_string($token)) {
             switch ($token) {
                 default:
                     $type = self::LITERAL;
                     break;
                 case ',':
                     $type = self::T_COMMA;
                     break;
                 case '.':
                     $type = self::T_DOT;
                     break;
                 case '{':
                     $type = self::T_CBRACE_OPEN;
                     break;
                 case '}':
                     $type = self::T_CBRACE_CLOSE;
                     break;
                 case '(':
                     $type = self::T_BRACE_OPEN;
                     break;
                 case ')':
                     $type = self::T_BRACE_CLOSE;
                     break;
                 case '=':
                     $type = self::T_EQUAL;
                     break;
                 case '&':
                     $type = self::T_AMPERSAND;
                     break;
                 case ';':
                     $type = self::T_SEMICOLON;
                     break;
                 case '+':
                     $type = self::T_PLUS;
                     break;
                 case '-':
                     $type = self::T_MINUS;
                     break;
             }
             $t = array('value' => $token, 'type' => $type, 'line' => $currentLine);
         } else {
             $t = array('value' => $token[1], 'type' => token_name($token[0]), 'line' => $token[2]);
             /* fix */
             if ($t['type'] == 'T_DOUBLE_COLON') {
                 $t['type'] = 'T_PAAMAYIM_NEKUDOTAYIM';
             }
             $currentLine = $t['line'];
         }
         /* whitespace analyisieren */
         if ($t['type'] == 'T_WHITESPACE' && $this->parseWhitespace) {
             Preg::match($t['value'], '/([^\\n]+|\\n)/g', $matches);
             foreach ($matches as $m) {
                 // das geht kaputt mit $this->eol anders als "\n"
                 list($NULL, $white) = $m;
                 if ($white === "\n") {
                     $currentLine++;
                     $type = self::T_EOL;
                 } else {
                     $type = self::T_PLAIN_WHITESPACE;
                 }
                 $this->tokens[] = array('value' => $white, 'type' => $type, 'line' => $currentLine);
             }
         } elseif ($t['type'] == 'T_COMMENT' && $this->parseWhitespace) {
             // EOL abschneiden und als einzelnes T_EOL dahinter machen
             if (S::endsWith($t['value'], $this->eol)) {
                 $t['value'] = mb_substr($t['value'], 0, -1);
                 $this->tokens[] = $t;
                 // comment hinzufügen
                 $currentLine++;
                 $this->tokens[] = array('value' => "\n", 'type' => self::T_EOL, 'line' => $currentLine);
             } else {
                 $this->tokens[] = $t;
                 // comment hinzufügen, auch wenn er kein EOL hata
             }
         } else {
             if (trim($t['value']) == '' && mb_strpos($t['value'], $this->eol) !== FALSE) {
                 // leer und mit umbruch
                 $currentLine += mb_substr_count($t['value'], $this->eol);
             }
             $this->tokens[] = $t;
         }
     }
     return $this;
 }
Пример #28
0
 public function extract($code, $startLine, $endLine)
 {
     $source = S::fixEOL($code);
     $source = explode("\n", $source);
     if (!array_key_exists($startLine - 1, $source) || !array_key_exists($endLine - 1, $source)) {
         throw new \Psc\Exception('In source: ' . $file . ' gibt es keinen Code von ' . $startLine . ' bis ' . $endLine);
     }
     return implode("\n", array_slice($source, $startLine - 1, $endLine - $startLine + 1));
 }
Пример #29
0
 public function phpDocBlock($baseIndent = 0)
 {
     if (isset($this->docBlock)) {
         return \Webforge\Common\String::indent($this->docBlock->toString(), $baseIndent);
     }
 }
Пример #30
0
 /**
  * Gibt das Template als String zurück
  *
  * @return string
  */
 public function get()
 {
     $__html = NULL;
     if ($this->validate()) {
         /* dies ersetzt variablen die durch das template verändert werden können: $$__varName */
         extract((array) $this->vars);
         $tpl = $this;
         /* get as String */
         try {
             ob_start();
             require $this->file;
             $__html = ob_get_contents();
             ob_end_clean();
         } catch (\Psc\Exception $e) {
             $e->setMessage(sprintf('in TPL(%s): %s', $this->getDisplayName(), $e->getMessage()));
             throw $e;
         }
         /* testen ob noch variablen übrig sind */
         //if (DEV) {
         //  $__matches = array();
         //  if (preg_match_all('/\{\$([a-zA-Z_0-9]*)\}/',$__html,$__matches,PREG_SET_ORDER) > 0) {
         //    foreach ($__matches as $__match) {
         //    //throw new Exception('in Template: '.$__fileName.' ist Variable "'.$__match[1].'" nicht definiert');
         //      trigger_error('in Template: '.$__fileName.' wird die Variable "'.$__match[1].'" nicht definiert (die von einem anderen Template benötigt wird)',E_USER_WARNING);
         //    }
         //  }
         //}
         if ($this->indent !== NULL) {
             $__html = S::indent($__html, $this->indent);
         }
     }
     return $__html;
 }