Beispiel #1
0
 public function read(DOMElement $e) {
     $tn = end(explode(':',$e->tagName));
     switch($tn) {
       case 'function':
       
         foreach($e->childNodes as $cnn) {
             if (typeOf($cnn) == 'DOMElement') {
                 $cnt = end(explode(':',$cnn->tagName));
                 if ($cnt == 'from') {
                     $this->from[] = $cnn->nodeValue;
                 } elseif ($cnt == 'to') {
                     $this->to = $cnn->nodeValue;
                 } else {
                     printf("Warning: Didn't expect %s here\n", $cnn->nodeName); 
                 }
             }
         }
         
         printf(__astr("[\b{phprefactor}] Refactoring{%s} --> %s\n"), join(', ',$this->from), $this->to);
         break;
         
       default:
         printf("I don't know what to do with %s!\n", $tn);
         
     }
 }
Beispiel #2
0
 static function inspectArray($data)
 {
     $ret = '<table>';
     foreach ($data as $key => $value) {
         $ret .= '<tr><th>' . htmlentities($key) . ' <br><em style="font-size:10px; font-weight:normal">' . typeOf($value) . '</em></th><td>';
         if (typeOf($value) == 'boolean') {
             if ($value) {
                 $ret .= '<img src="data:image/gif;base64,R0lGODlhEwAHAIABAAAAAP///yH5BAEKAAEALAAAAAATAAcAAAIajI+ZwMFgoHMt2imhPNn2x0XVt1zZuSkqUgAAOw==" alt="true">';
             } else {
                 $ret .= '<img src="data:image/gif;base64,R0lGODlhFwAHAIABAAAAAP///yH5BAEKAAEALAAAAAAXAAcAAAIejI+pB20eAGqSPnblxczp2nmQFlkkdpJfWY3QAi8FADs=" alt="false">';
             }
         } else {
             if (is_array($value) || is_a($value, 'StdClass')) {
                 $ret .= self::inspectArray((array) $value);
             } else {
                 if ($value === null) {
                     $ret .= '<img src="data:image/gif;base64,R0lGODdhEwAHAKECAAAAAPj4/////////ywAAAAAEwAHAAACHYSPmWIB/KKBkznIKI0iTwlKXuR8B9aUXdYprlsAADs=" alt="null">';
                 } else {
                     $ret .= htmlentities($value);
                 }
             }
         }
         $ret .= '</td></tr>';
     }
     $ret .= '</table>';
     return $ret;
 }
Beispiel #3
0
 /**
  * Escapes (secures) data for output.<br>
  *
  * <p>Array values are converted to space-separated value string lists.
  * > A useful use case for an array attribute is the `class` attribute.
  *
  * Object values generate either:
  * - a space-separated list of keys who's corresponding value is truthy;
  * - a semicolon-separated list of key:value elements if at least one value is a string.
  *
  * Boolean values will generate the string "true" or "false".
  *
  * NULL is converted to an empty string.
  *
  * Strings are HTML-encoded.
  *
  * @param mixed $o
  * @return string
  */
 function e($o)
 {
     switch (gettype($o)) {
         case 'string':
             break;
         case 'boolean':
             return $o ? 'true' : 'false';
         case 'integer':
         case 'double':
             return strval($o);
         case 'array':
             $at = [];
             $s = ' ';
             foreach ($o as $k => $v) {
                 if (!is_string($v) && !is_numeric($v)) {
                     throw new \InvalidArgumentException("Can't output an array with values of type " . gettype($v));
                 }
                 if (is_numeric($k)) {
                     $at[] = $v;
                 } else {
                     $at[] = "{$k}:{$v}";
                     $s = ';';
                 }
             }
             $o = implode($s, $at);
             break;
         case 'NULL':
             return '';
         default:
             return typeOf($o);
     }
     return htmlentities($o, ENT_QUOTES, 'UTF-8', false);
 }
 public function testShouldFormatManyAccordingToConvertMethod()
 {
     $items = ['foo', 'bar', 'baz'];
     $formatter = new MockFormatter();
     $result = $formatter->formatMany($items);
     assertThat('The result of `formatMany` should be an array of arrays.', $result, everyItem(is(typeOf('array'))));
     assertThat('The result should be the same size as the number of items passed to `formatMany`.', $result, is(arrayWithSize(count($items))));
     assertThat('The result should be correctly formatted.', $result, is(anArray([['count' => 1], ['count' => 2], ['count' => 3]])));
 }
Beispiel #5
0
 public function addAnimator($property, ILpfAnimator $animator, $frstart, $frend)
 {
     if (arr::hasKey($this->_properties, $property)) {
         $this->_animators[$property][] = array('animator' => $animator, 'framestart' => $frstart, 'frameend' => $frend);
         console::writeLn("Attached animator: %s => %s", typeOf($animator), $property);
     } else {
         logger::warning("Animator attached to nonexisting property %s of object %s", $property, (string) $this->_object);
     }
 }
Beispiel #6
0
 /**
  * @brief Recursive decoder
  * @private
  * 
  * @param String $json The JSON data to process
  * @return Mixed The parsed data
  */
 private static function decodeRecursive($json)
 {
     $arr = (array) $json;
     foreach ($arr as $k => $v) {
         if (typeOf($v) == 'stdClass' || typeOf($v) == 'array') {
             $arr[$k] = (array) self::decodeRecursive($v);
         }
     }
     return $arr;
 }
Beispiel #7
0
 /**
  * @Then the SpikeApi Request Time should be very recent
  */
 public function theRequestTimeShouldBeVeryRecent()
 {
     $now = time();
     $data = json_decode($this->response);
     $actual = $data->request_time;
     assertThat($actual, typeOf('integer'));
     #assertInternalType('integer', $actual);
     // we need to allow some fuzz-time, a few seconds should be OK
     assertThat("request time should be close", $now, closeTo($actual, 3));
     // We give it a little fuzz to allow for potential clock drift between machines
 }
/**
* @param Any? $value a value or null
*/
function mixedValueSummary($value, $valueIfEmpty = null, $returnKind = false)
{
    $valueToReturn = $value ? $value : (isset($valueIfEmpty) ? $valueIfEmpty : $value);
    if (!$returnKind) {
        return $valueToReturn;
    } else {
        $r = array();
        $r['kind'] = typeOf($valueToReturn);
        $r['value'] = $valueToReturn;
        return $r;
    }
}
Beispiel #9
0
 function exception(Exception $e)
 {
     if (ob_get_length() != false) {
         @ob_end_clean();
     }
     $et = typeOf($e);
     if ($et == 'FileNotFoundException' || $et == 'NavigationException') {
         response::setStatus(404);
         header('HTTP/1.1 404 Not Found', true);
         printf("<h1>404: Not Found</h1>");
         return;
     }
     if ($et == 'HttpException') {
         response::setStatus($e->getCode());
         $code = $e->getMessage();
         list($code) = explode(':', $code);
         $code = str_replace('Error ', '', $code);
         $msg = HttpException::getHttpMessage($code);
         header('HTTP/1.1 ' . $code . ' ' . $msg . ' ' . $msg);
         printf("<h1>%s: %s</h1>\n<pre>%s</pre>", $code, $msg, $msg);
         return;
     }
     response::setStatus(500);
     logger::emerg("Unhandled exception: (%s) %s in %s:%d", get_class($e), $e->getMessage(), str_replace(BASE_PATH, '', $e->getFile()), $e->getLine());
     header('HTTP/1.1 501 Server Error', true);
     $id = uniqid();
     $dbg = sprintf("Unhandled exception: (%s) %s\n  in %s:%d", get_class($e), $e->getMessage(), str_replace(SYS_PATH, '', $e->getFile()), $e->getLine()) . Console::backtrace(0, $e->getTrace(), true) . "\n" . "Loaded modules:\n" . ModuleManager::debug() . "\n" . request::getDebugInformation();
     logger::emerg($dbg);
     if (config::get('lepton.mvc.exception.log', false) == true) {
         $logfile = config::get('lepton.mvc.exception.logfile', "/tmp/" . $_SERVER['HTTP_HOST'] . "-debug.log");
         $log = "=== Unhandled Exception ===\n\n" . $dbg . "\n";
         $lf = @fopen($logfile, "a+");
         if ($lf) {
             fputs($lf, $log);
             fclose($lf);
         }
     }
     $ico_error = resource::get('warning.png');
     header('content-type: text/html; charset=utf-8');
     echo '<html><head><title>Unhandled Exception</title>' . self::$css . self::$js . '</head><body>' . '<div id="box"><div id="left"><img src="' . $ico_error . '" width="32" height="32"></div><div id="main">' . '<h1>An Unhandled Exception Occured</h1>' . '<hr noshade>' . '<p>This means that something didn\'t go quite go as planned. This could be ' . 'caused by one of several reasons, so please be patient and try ' . 'again in a little while.</p>';
     if (config::get('lepton.mvc.exception.feedback', false) == true) {
         echo '<p>The administrator of the website has been notified about this error. You ' . 'can help us find and fix the problem by writing a line or two about what you were doing when this ' . 'error occured.</p>';
         echo '<p id="feedbacklink"><a href="javascript:doFeedback();">If you would like to assist us with more information, please click here</a>.</p>';
         echo '<div id="feedback" style="display:none;"><p>Describe in a few short lines what you were doing right before you encountered this error:</p><form action="/errorevent.feedback/' . $id . '" method="post"><div><textarea name="text" style="width:100%; height:50px;"></textarea></div><div style="padding-top:5px; text-align:right;"><input type="button" value=" Close " onclick="closeFeedback();"> <input type="submit" value=" Submit Feedback "></div></form></div>';
     }
     if (config::get('lepton.mvc.exception.showdebug', false) == true) {
         echo '<hr noshade>' . '<a href="javascript:toggleAdvanced();">Details &raquo;</a>' . '<pre id="advanced" style="display:none; height:300px;">' . $dbg . '</pre>';
     }
     echo '<div>' . '</body></html>';
 }
Beispiel #10
0
 /**
  * @param $file
  *
  * @return array
  *
  * @throws \Stefanius\LaravelFixtures\Exception\FileNotFoundException
  */
 public function loadYmlData($file)
 {
     if (is_null($file)) {
         throw new \InvalidArgumentException(sprintf('The argument has to be a string. NULL given.'));
     }
     if (!is_string($file)) {
         throw new \InvalidArgumentException(sprintf('The argument has to be a string. %s given.', typeOf($file)));
     }
     $ymlFilename = sprintf($this->fixtureDataPath . DIRECTORY_SEPARATOR . '%s.yml', $file);
     if (!file_exists($ymlFilename)) {
         throw new FileNotFoundException($ymlFilename);
     }
     return Yaml::parse(file_get_contents($ymlFilename));
 }
 public function testShouldFormatTraversableAccordingToConvertMethod()
 {
     $items = ['foo', 'bar', 'baz'];
     /** @var Generator **/
     $result = (new MockFormatter())->formatTraversable(new ArrayIterator($items));
     assertThat('The result of `formatTraversable` should be a Generator.', $result, is(anInstanceOf('Generator')));
     /** @var Generator **/
     $result = (new MockFormatter())->formatTraversable(new ArrayIterator($items));
     assertThat('Every item in the result should be an array.', iterator_to_array($result), everyItem(is(typeOf('array'))));
     /** @var Generator **/
     $result = (new MockFormatter())->formatTraversable(new ArrayIterator($items));
     assertThat('The result should be the same size as the number of items passed to `formatTraversable`.', $result, is(traversableWithSize(count($items))));
     /** @var Generator **/
     $result = (new MockFormatter())->formatTraversable(new ArrayIterator($items));
     assertThat('The result should be correctly formatted.', iterator_to_array($result), is(anArray([['count' => 1], ['count' => 2], ['count' => 3]])));
 }
Beispiel #12
0
/**
 * Extracts and escapes text from the given value, for outputting to the HTTP client.
 *
 * <p>Note: this returns escaped text, except if the given argument is a {@see RawText} instance, in which case it
 * returns raw text.
 *
 * @param string|RawText $s
 * @return string
 */
function _e($s)
{
    if (!is_scalar($s)) {
        if (is_null($s)) {
            return '';
        }
        if ($s instanceof RawText) {
            return $s->toString();
        }
        if ($s instanceof RenderableInterface) {
            $s = $s->getRendering();
        } elseif (is_object($s) && method_exists($s, '__toString')) {
            $s = (string) $s;
        } else {
            if (is_iterable($s)) {
                return iteratorOf($s)->current();
            }
            return sprintf('[%s]', typeOf($s));
        }
    }
    return htmlentities($s, ENT_QUOTES, 'UTF-8', false);
}
 /**
  * @internal
  * @param mixed $arg
  * @return string
  */
 public static function formatErrorArg($arg)
 {
     if (is_object($arg)) {
         switch (get_class($arg)) {
             case \ReflectionMethod::class:
                 /** @var \ReflectionMethod $arg */
                 return sprintf('ReflectionMethod<%s::$s>', $arg->getDeclaringClass()->getName(), $arg->getName());
             case \ReflectionFunction::class:
                 /** @var \ReflectionFunction $arg */
                 return sprintf('ReflectionFunction<function at %s line %d>', $arg->getFileName(), $arg->getStartLine());
             case \ReflectionParameter::class:
                 /** @var \ReflectionParameter $arg */
                 return sprintf('ReflectionParameter<$%s>', $arg->getName());
             default:
                 return typeOf($arg);
         }
     }
     if (is_array($arg)) {
         return sprintf('[%s]', implode(',', map($arg, [__CLASS__, 'formatErrorArg'])));
     }
     return str_replace('\\\\', '\\', var_export($arg, true));
 }
Beispiel #14
0
 function __inspect_recurs($data, $head = '')
 {
     $maxlenk = 30;
     $maxlent = 8;
     foreach ($data as $k => $v) {
         if (strlen($k) > $maxlenk) {
             $maxlenk = strlen($k);
         }
         if (strlen(typeOf($v)) > $maxlent) {
             $maxlent = strlen(typeOf($v));
         }
     }
     $maxlent += 2;
     $itemcount = count($data);
     $idx = 0;
     foreach ($data as $k => $v) {
         $idx++;
         if (typeOf($v) == 'array' || typeOf($v) == 'stdClass') {
             $ttl = $head . $k . ' ';
             console::writeLn($ttl);
             $myend = '|_';
             $nhead = $head;
             if ($idx++ > 0) {
                 $nhead = substr($head, 0, strlen($head) - 1) . ' ';
             }
             self::__inspect_recurs($v, $nhead . $myend);
         } else {
             switch (typeOf($v)) {
                 case 'boolean':
                     $sv = $v ? 'true' : 'false';
                     break;
                 default:
                     $sv = '"' . $v . '"';
             }
             console::writeLn('%s = %s', $head . sprintf('%s<%s>', $k, typeOf($v)), $sv);
         }
     }
 }
Beispiel #15
0
 /**
  * @brief Run the application. Invoked by Lepton.
  * Will parse the arguments and make sure everything is in order.
  *
  */
 function run()
 {
     global $argc, $argv;
     if (isset($this->arguments)) {
         if (is_string($this->arguments)) {
             $strargs = $this->arguments;
             $longargs = array();
         } elseif (is_array($this->arguments)) {
             $strargs = '';
             $longargs = array();
             foreach ($this->arguments as $arg) {
                 $strargs .= $arg[0];
                 // Scope is the : or ::
                 $scope = substr($arg[0], 1);
                 $longargs[] = $arg[1] . $scope;
             }
         } elseif (typeOf($this->arguments) == 'AppArgumentList') {
             $args = $this->arguments->getData();
             $strargs = '';
             $longargs = array();
             foreach ($args as $arg) {
                 $strargs .= $arg[0];
                 // Scope is the : or ::
                 $scope = substr($arg[0], 1);
                 $longargs[] = $arg[1] . $scope;
             }
         } else {
             console::warn('Application->$arguments is set but format is not understood');
         }
         list($args, $params) = $this->parseArguments($strargs, $longargs);
         foreach ($args as $arg => $val) {
             if (in_array($arg, $longargs)) {
                 foreach ($args as $argsrc => $v) {
                     if ($argsrc == $arg) {
                         $args[$argsrc[0]] = $val;
                         $olarg = $argsrc[0];
                     }
                 }
             } else {
                 foreach ($args as $argsrc => $v) {
                     if ($argsrc == $arg) {
                         $arg[$argsrc] = $val;
                         $olarg = $argsrc[0];
                         // Do any matching we need here
                     }
                 }
             }
         }
         $this->_args = $args;
         $this->_params = $params;
     }
     if (isset($args['h'])) {
         if (method_exists($this, 'usage')) {
             $this->usage();
         }
         return 1;
     }
     return $this->main($argc, $argv);
 }
function CountItems()
{
    global $db;
    $cat = $db->query('SELECT ID,type,access,sc FROM ' . PRE . 'cats')->fetchAll(3);
    //FETCH_NUM
    $ile = count($cat);
    if ($ile > 0) {
        #Dla każdej kategorii policz liczbę zawartości
        for ($i = 0; $i < $ile; ++$i) {
            $id = $cat[$i][0];
            $num[$id] = dbCount(typeOf($cat[$i][1]) . ' WHERE cat=' . $id . ' AND access=1');
            #ID kategorii nadrzędnej
            $sub[$id] = $cat[$i][3];
            #Tablica będzie zawierać ilość kategorii w podkategoriach
            $total[$id] = $num[$id];
        }
        for ($i = 0; $i < $ile; $i++) {
            #Jeżeli dostępna - znajdź podkategorie i dolicz ilość zawartości
            if ($cat[$i][2] != 2 && $cat[$i][2] != 3) {
                $x = $cat[$i][3];
                #Nadkategoria
                while ($x != 0 && is_numeric($x)) {
                    $total[$x] += $total[$cat[$i][0]];
                    $x = $sub[$x];
                }
            }
        }
        #Zapisz ilość dla każdej kategorii
        $q = $db->prepare('UPDATE ' . PRE . 'cats SET num=?, nums=? WHERE ID=?');
        foreach ($total as $k => $x) {
            if (is_numeric($x) && is_numeric($num[$k])) {
                $q->execute(array($num[$k], $x, $k));
            }
        }
    }
}
 /**
  * Performs the actual routing.
  *
  * @param mixed                  $routable
  * @param ServerRequestInterface $request
  * @param ResponseInterface      $response
  * @param callable               $next
  * @return ResponseInterface
  */
 function route($routable, ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     if (is_null($routable)) {
         return $next();
     }
     if (is_callable($routable)) {
         if ($routable instanceof FactoryRoutable) {
             $instance = $this->runFactory($routable);
             return $this->route($instance, $request, $response, $next);
         } else {
             $response = $this->callHandler($routable, $request, $response, $next);
         }
     } else {
         if ($routable instanceof \IteratorAggregate) {
             $routable = $routable->getIterator();
         } elseif (is_array($routable)) {
             $routable = new \ArrayIterator($routable);
         }
         if ($routable instanceof Iterator) {
             $response = $this->iteration_start($routable, $request, $response, $next, ++self::$stackCounter);
         } elseif (is_string($routable)) {
             $routable = $this->injector->make($routable);
             if (is_callable($routable)) {
                 $response = $this->callHandler($routable, $request, $response, $next);
             } else {
                 throw new \RuntimeException(sprintf("Instances of class <span class=class>%s</span> are not routable.", Debug::getType($routable)));
             }
         } else {
             throw new \RuntimeException(sprintf("Invalid routable type <span class=type>%s</span>.", typeOf($routable)));
         }
     }
     return $response;
 }
Beispiel #18
0
 public function testDecribesActualTypeInMismatchMessage()
 {
     $this->assertMismatchDescription('was null', typeOf('boolean'), null);
     $this->assertMismatchDescription('was an integer <5>', typeOf('float'), 5);
 }
 /**
  * For internal use.
  *
  * @param Component $component
  * @param bool      $deep
  * @throws ComponentException
  */
 private static function _inspect(Component $component, $deep = true)
 {
     if (self::$recursionMap->contains($component)) {
         echo "<i>recursion</i>";
         return;
     }
     self::$recursionMap->attach($component);
     $COLOR_BIND = '#5AA';
     $COLOR_CONST = '#5A5';
     $COLOR_INFO = '#CCC';
     $COLOR_PROP = '#B00';
     $COLOR_TAG = '#000;font-weight:bold';
     $COLOR_TYPE = '#55A';
     $COLOR_VALUE = '#333';
     $COLOR_SHADOW_DOM = '#5AA;font-weight:bold';
     $Q = "<i style='color:#CCC'>\"</i>";
     $tag = $component->getTagName();
     $hasContent = false;
     echo "<div class=__component><span style='color:{$COLOR_TAG}'>&lt;{$tag}</span>";
     $isDoc = $component instanceof DocumentFragment;
     if (!$component->parent && !$isDoc) {
         echo "&nbsp;<span style='color:{$COLOR_INFO}'>(detached)</span>";
     }
     $type = typeOf($component) . ' #' . Debug::objectId($component);
     echo "<span class='icon hint--rounded hint--right' data-hint='Component:\n{$type}'><i class='fa fa-info-circle'></i></span>";
     $type1 = str_pad('#' . Debug::objectId($component->context), 4, ' ', STR_PAD_LEFT);
     $type2 = str_pad('#' . Debug::objectId($component->getDataBinder()), 4, ' ', STR_PAD_LEFT);
     $type3 = str_pad('#' . Debug::objectId($component->getViewModel()), 4, ' ', STR_PAD_LEFT);
     $type4 = str_pad('#' . Debug::objectId($component->getDataBinder()->getViewModel()), 4, ' ', STR_PAD_LEFT);
     $type5 = str_pad('#' . Debug::objectId($component->getDataBinder()->getProps()), 4, ' ', STR_PAD_LEFT);
     echo "<span class='icon hint--rounded hint--bottom' data-hint='Context:    {$type1}  Data binder:       {$type2}\nView model: {$type3}  Binder view model: {$type4}\nProperties: {$type5}'><i class='fa fa-database'></i></span>";
     // Handle text node
     if ($component instanceof Text) {
         echo "<span style='color:{$COLOR_TAG}'>&gt;</span><div style='margin:0 0 0 15px'>";
         try {
             if ($component->isBound('value')) {
                 /** @var Expression $exp */
                 $exp = $component->getBinding('value');
                 $exp = self::inspectString((string) $exp);
                 echo "<span style='color:{$COLOR_BIND}'>{$exp}</span> = ";
                 $v = self::getBindingValue('value', $component, $error);
                 if ($error) {
                     echo $v;
                     return;
                 }
                 if (!is_string($v)) {
                     echo Debug::typeInfoOf($v);
                     return;
                 }
             } else {
                 $v = $component->props->value;
             }
             $v = strlen(trim($v)) ? HtmlSyntaxHighlighter::highlight($v) : "<i>'{$v}'</i>";
             echo $v;
         } finally {
             echo "</div><span style='color:{$COLOR_TAG}'>&lt;/{$tag}&gt;<br></span></div>";
         }
         return;
     }
     // Handle other node types
     if ($component instanceof DocumentFragment) {
         self::inspectViewModel($component);
     }
     if ($component->supportsProperties()) {
         /** @var ComponentProperties $propsObj */
         $propsObj = $component->props;
         if ($propsObj) {
             $props = $propsObj->getAll();
         } else {
             $props = null;
         }
         if ($props) {
             ksort($props);
         }
         if ($props) {
             $type = typeOf($propsObj);
             $tid = Debug::objectId($propsObj);
             echo "<span class='icon hint--rounded hint--right' data-hint='Properties: #{$tid}\n{$type}'><i class='fa fa-list'></i></span>";
             echo "<table class='__console-table' style='color:{$COLOR_VALUE}'>";
             // Display all scalar properties.
             foreach ($props as $k => $v) {
                 $t = $component->props->getTypeOf($k);
                 $isModified = $component->props->isModified($k);
                 $modifStyle = $isModified ? ' class=__modified' : ' class=__original';
                 if ($t != type::content && $t != type::collection && $t != type::metadata) {
                     $tn = $component->props->getTypeNameOf($k);
                     echo "<tr{$modifStyle}><td style='color:{$COLOR_PROP}'>{$k}<td><i style='color:{$COLOR_TYPE}'>{$tn}</i><td>";
                     // Display data-binding
                     if ($component->isBound($k)) {
                         /** @var Expression $exp */
                         $exp = $component->getBinding($k);
                         $exp = self::inspectString((string) $exp);
                         echo "<span style='color:{$COLOR_BIND}'>{$exp}</span> = ";
                         $v = self::getBindingValue($k, $component, $error);
                         if ($error) {
                             break;
                         }
                     }
                     if (is_null($v)) {
                         echo "<i style='color:{$COLOR_INFO}'>null</i>";
                     } else {
                         switch ($t) {
                             case type::bool:
                                 echo "<i style='color:{$COLOR_CONST}'>" . ($v ? 'true' : 'false') . '</i>';
                                 break;
                             case type::id:
                                 echo "{$Q}{$v}{$Q}";
                                 break;
                             case type::number:
                                 echo $v;
                                 break;
                             case type::string:
                                 echo "{$Q}<span style='white-space: pre-wrap'>" . self::inspectString(strval($v)) . "</span>{$Q}";
                                 break;
                             default:
                                 if (is_object($v)) {
                                     echo sprintf("<i style='color:{$COLOR_CONST}'>%s</i>", Debug::typeInfoOf($v));
                                 } elseif (is_array($v)) {
                                     echo sprintf("<i style='color:{$COLOR_CONST}'>array(%d)</i>", count($v));
                                 } else {
                                     $v = _e($v);
                                     echo "{$Q}{$v}{$Q}";
                                 }
                         }
                     }
                 }
             }
             // Display all slot properties.
             foreach ($props as $k => $v) {
                 $t = $component->props->getTypeOf($k);
                 if ($t == type::content || $t == type::collection || $t == type::metadata) {
                     $tn = $component->props->getTypeNameOf($k);
                     $isModified = $component->props->isModified($k);
                     $modifStyle = $isModified ? ' style="background:#FFE"' : ' style="opacity:0.5"';
                     echo "<tr{$modifStyle}><td style='color:{$COLOR_PROP}'>{$k}<td><i style='color:{$COLOR_TYPE}'>{$tn}</i><td>";
                     /** @var Expression $exp */
                     $exp = $component->getBinding($k);
                     if (isset($exp)) {
                         $exp = self::inspectString((string) $exp);
                         echo "<span style='color:{$COLOR_BIND}'>{$exp}</span> = ";
                         $v = self::getBindingValue($k, $component, $error);
                         if ($error) {
                             echo $v;
                             break;
                         }
                     }
                     if ($v && ($v instanceof Component || is_array($v))) {
                         switch ($t) {
                             case type::content:
                                 if ($v) {
                                     echo "<tr><td><td colspan=2>";
                                     self::_inspect($v, $deep);
                                 } else {
                                     echo "<i style='color:{$COLOR_INFO}'>null</i>";
                                 }
                                 break;
                             case type::metadata:
                                 if ($v) {
                                     echo "<tr><td><td colspan=2>";
                                     self::_inspect($v, $deep);
                                 } else {
                                     echo "<i style='color:{$COLOR_INFO}'>null</i>";
                                 }
                                 break;
                             case type::collection:
                                 echo "of <i style='color:{$COLOR_TYPE}'>", $component->props->getRelatedTypeNameOf($k), '</i>';
                                 if ($v) {
                                     echo "<tr><td><td colspan=2>";
                                     self::_inspectSet($v, true);
                                 } else {
                                     echo " = <i style='color:{$COLOR_INFO}'>[]</i>";
                                 }
                                 break;
                         }
                     } else {
                         if (is_array($v)) {
                             echo "<i style='color:{$COLOR_INFO}'>[]</i>";
                         } else {
                             if (isset($v)) {
                                 printf("<b style='color:red'>WRONG TYPE: %s</b>", Debug::typeInfoOf($v));
                             } else {
                                 echo "<i style='color:{$COLOR_INFO}'>null</i>";
                             }
                         }
                     }
                     echo '</tr>';
                 }
             }
             echo "</table>";
         }
     }
     // If deep inspection is enabled, recursively inspect all children components.
     if ($deep) {
         $content = $shadowDOM = null;
         if ($component->hasChildren()) {
             $content = $component->getChildren();
         }
         if ($component instanceof CompositeComponent) {
             $shadowDOM = $component->provideShadowDOM();
         }
         if ($content || $shadowDOM) {
             echo "<span style='color:{$COLOR_TAG}'>&gt;</span><div style=\"margin:0 0 0 15px\">";
             if ($content) {
                 self::_inspectSet($content, $deep);
             }
             if ($shadowDOM) {
                 echo "<span style='color:{$COLOR_SHADOW_DOM}'>&lt;Shadow DOM&gt;</span><div style=\"margin:0 0 0 15px\">";
                 self::_inspect($shadowDOM, $deep);
                 echo "</div><span style='color:{$COLOR_SHADOW_DOM}'>&lt;/Shadow DOM&gt;</span>";
             }
             echo '</div>';
             $hasContent = true;
         }
     }
     echo "<span style='color:{$COLOR_TAG}'>" . ($hasContent ? "&lt;/{$tag}&gt;<br>" : "/&gt;<br>") . "</span></div>";
 }
Beispiel #20
0
 function esc_sql($value, $colType = null) {
   if (is_number($value)) return $value;
   if (typeOf($value) === 'NULL') return 'NULL';
   return app('db')->getPdo()->quote($value);
 }
Beispiel #21
0
 /**
  * @brief Return the type of the request object
  * 
  * @return string The type of request object
  */
 function getType()
 {
     return typeOf($this);
 }
Beispiel #22
0
    public function __construct($label, $key, Array $items = null, Array $options = null) {
        
        $this->label = $label;
        $this->setKey($key);
        // Here we will do a little check to see if the array we are passed is
        // indexed with a key ( $k => $v ), or if it's simply an array of arrays
        // i.e. a recordset from a database query. If this is the case, we will
        // go over the list and massage it to be indexed with a key.

        if (count($items)>0) {
            if (typeOf($items[0]) == 'array') {
                $newarr = array();
                // Repopulate the list with keys properly assigned
                foreach($items as $item) {
                    $newarr[$item[0]] = $item[1];
                }
                // And update the item list with our newly populated one
                $items = $newarr;
            }
            // Now we update the main list
            $this->items = $items;
        }
        $this->options = arr::defaults($options, array(
            'class' => 'wf-row'
        ));
        
    }
Beispiel #23
0
 public function decomposeArray($x = null)
 {
     $type = typeOf($x);
     //pkdebug("TYPE: $type");
     if (!$x) {
         return '';
     }
     if (!is_array($x)) {
         if (is_scalar($x) || is_object($x) && method_exists($x, '__toString')) {
             return $x . $this->separator;
         }
         return '';
     }
     $str = $this->separator;
     foreach ($x as $y) {
         $str .= $this->decomposeArray($y) . $this->separator;
     }
     return $str;
 }
Beispiel #24
0
 public static function like($pattern, $string)
 {
     if (typeOf($pattern) == 'array') {
         foreach ($pattern as $pat) {
             if (fnmatch($pat, $string, FNM_CASEFOLD)) {
                 return true;
             }
         }
         return false;
     } else {
         return fnmatch($pattern, $string, FNM_CASEFOLD);
     }
 }
  /** Return an Eloquent Query Builder Instance
   * Builds a basic chained "AND WHERE..." query from the instance 'querySets" array.
   * The query set is an associative array of <tt>what=>[crit, val]</tt>, where
   * 'what' is either a field/column name, OR the root of a custom query method,
   * which has to be defined in the implementing classes, presumably a trait
   * shared by the Controller/SearchModel. Looks first for field name, then
   * method name, defined as <tt>$this->customQuery{What}($crit,$val)</tt>
   * 
   * One advantage to searching on a model instance - you can also use
   * and specify model methods as comparison criteria for stuff that's hard in 
   * DB. Can also take parameters. The Query will first execute the query it
   * can on the DB - then from the return, filter on the instances using
   * the methods.
   * 
   * (Ex: <tt>$this->customQueryAsset_debt_ratio($query,$crit, $val)</tt>:
   * <pre> 
   * [
   *   'fieldName1'=>['crit'=>$crit1, 'val'=>$val1],
   *   'fieldName2'=>['crit'=>$crit2, 'val'=>$val2],
   *   'methodName1'=>['crit'=>$crit3, 'val'=>$val3],
   *   'methodName2'=>['crit'=>$crit4, 'val'=>$val4, 'param'=>$param],
   * ....]
   * </pre>
   * 
   * @param $targetModel - A PkModel CLASS, NOT instance.
   * @return Eloquent Builder
   * */
  public function buildQueryOnModel($targetModel = null, $querySets=null) {
    if (!$targetModel) $targetModel = static::getTargetModel();
    if (empty($targetModel)) throw new \Exception("No model to build query on");
    $targetFieldNames = $targetModel::getStaticAttributeNames();
    //pkdebug("TargetFieldNames:", $targetFieldNames);
    if ($querySets === null) {
      if (!empty($this->querySets)) $querySets = $this->querySets;
      else $querySets = $this->buildQuerySets();
    }
    #Sets are keyed by 'root' or 'baseName', with a definition array. If the
    #root key matches an attribute name on the model, that's what we search 
    #against. If not, try to figure out what the query is on/for/to.
    #
    #The definition array might contain a sub-definition array - 
    #$sets[$root]['def']['attribute'] - which could be : 'property',
    #'target_method' (a method to call on the target Model), or 'self_method'
    #(a method defined in this model/trait.) - with $baseName the method or property
    #name. It could also contain other fields, like as parameters to methods
    #
    #In fact, it's totally appropriate for a persistent query to consist entirely
    #of methods and NO model/table fields.
    //pkdebug("Query Sets:", $sets);
    $query = $targetModel::query();
    if (empty($querySets)) return $query;
    //pkdebug("NOT empty SETS!");
    //pkdebug("QuerySets:", $querySets);

    //pkdebug("My PkMatchObjs:", $this->matchObjs);
    foreach ($querySets as $root => $critset) {
      $toq = typeOf($query);
      //pkdebug("ROOT: [$root] SET:", $critset, "queryT: $toq");
      if ($root == '0') continue;
      //if ($root==='assetdebtratio') pkdebug("ADR: QT: ".typeOf($query)."..");
      //pkdebug("ROOT: [ $root ] ADR: QT: ".typeOf($query)."..");
      //if (!$critset['crit'] || ($critset['crit'] == '0') || static::emptyVal($critset['val'])) continue;
      if (static::emptyCrit($critset['crit']) || static::emptyVal($critset['val']))
          continue;
      //pkdebug("ROOT: [ $root ] ADR: QT: ".typeOf($query)."..");
      //pkdebug("root is:", $root, "critset:", $critset);
      if (in_array($root, $targetFieldNames)) {
        if (is_array($critset['val'])) {
          if ($critset['crit'] === 'IN') {
            $query = $query->whereIn($root, array_values($critset['val']));
            continue;
          } else if ($critset['crit'] === 'NOTIN') {
            $query = $query->whereNotIn($root, array_values($critset['val']));
            continue;
          } else if ($critset['crit'] === 'BETWEEN') {
            //  $max = is_int(keyVal('max',$critset['val'])) ? keyVal('max',$critset['val']) : PHP_INT_MAX;
     // pkdebug("ROOT: [ $root ] ADR: QT: ".typeOf($query)."..");
            //  $min = is_int(keyVal('min',$critset['val'])) ? keyVal('min',$critset['val']) : -PHP_INT_MAX;
            $min = to_int(keyVal('minval', $critset['val']), -PHP_INT_MAX);
            $max = to_int(keyVal('maxval', $critset['val']), PHP_INT_MAX);
            //pkdebug('Orig Val Arr:', $critset['val'], "MIN:", $min, "MAX", $max);
            $query = $query->whereBetween($root, [$min, $max]);
            continue;
          } else {
            continue;
          }
        }
        //pkdebug("QT: ".typeOf($query)."..");
        $query = $query->where($root, $critset['crit'], $critset['val']);
      } else if (method_exists($this, 'customQuery' . $root)) {
        $customQueryMethod = 'customQuery' . $root;
        $query = $this->$customQueryMethod($query, $critset['crit'], $critset['val'], $critset['param']);
      }
    }
    return $query;
  }
Beispiel #26
0
 public function content($content = '', $raw = false)
 {
     if ($content === null) {
         $this[] = null;
         return $this;
     }
     if (is_array($content)) {
         foreach ($content as $item) {
             $this->content($item);
         }
         return $this;
     }
     if ($content instanceof self || $content instanceof PkHtmlRenderer || $content instanceof \Illuminate\Support\HtmlString) {
         $this[] = $content;
         return $this;
     }
     if (is_string($content)) {
         if (!$raw) {
             $content = hpure($content);
         }
         $this[] = $content;
         return $this;
     } else {
         $type = typeOf($content);
         throw new \Exception("Unhandled Content Type: [{$type}], val: " . print_r($content, 1));
     }
     return $this;
 }
 /**
  * Returns the value converted to a the data type required by the specified property.
  *
  * @param string $name
  * @param mixed  $v
  * @return bool|float|int|null|string|\Traversable
  * @throws ComponentException
  */
 function typecastPropertyValue($name, $v)
 {
     if ($this->isScalar($name) && $this->isEnum($name)) {
         $this->validateEnum($name, $v);
     }
     $type = $this->getTypeOf($name);
     if ($type && !type::validate($type, $v)) {
         throw new ComponentException($this->component, sprintf("%s is not a valid value for the <kbd>{$name}</kbd> property, which is of type <kbd>%s</kbd>", is_scalar($v) ? sprintf("The %s<kbd>%s</kbd>", typeOf($v), var_export($v, true)) : sprintf("A value of PHP type <kbd>%s</kbd>", typeOf($v)), type::getNameOf($type)));
     }
     // A special case for content type properties:
     // Convert a content property specified as attribute=string to a format equivalent to the one generated by
     // <subtag>string</subtag>
     if ($type == type::content && is_string($v)) {
         $content = new Metadata($this->component->context, $name, type::metadata);
         $content->setChildren([Text::from($this->component->context, $v)]);
         return $content;
     }
     return type::typecast($type, $v);
 }
Beispiel #28
0
 /**
  * @brief Retrieve the access matrix for the subject.
  *
  * The matrix will contain all the roles as well as effective modifiers
  * applied including groups as well as the default roles.
  *
  * @param IAclObject $object The object to for which the access is queried
  * @param IAclSubject $subject The subject whos access is being queried
  * @return Array The access matrix
  */
 static function getAccessMatrix(IAclObject $object, IAclSubject $subject)
 {
     // Get the object uuids
     $ouuid = $object->getObjectUuid();
     $roles = $object->getObjectRoles();
     // Get the uuid and groups from the subject
     $sgroups = $subject->getSubjectGroups();
     $suuid = $subject->getSubjectUuid();
     // Create database connection
     $db = new DatabaseConnection();
     $matrix = array();
     // Determine and label the default roles for the object
     $matrix[] = array('label' => sprintf('%s <%s>', typeOf($object), $ouuid), 'type' => self::TYP_OBJECT, 'roles' => $roles);
     // Compile a role list and save the effective roles
     $rlist = array();
     foreach ($roles as $role => $def) {
         $rlist[] = $role;
     }
     $effective = $roles;
     // Determine and label the roles for the subjects groups
     foreach ($sgroups as $group) {
         $guuid = $group->getSubjectUuid();
         $groles = acl::getExplicitAccessRecord($guuid, $ouuid, $rlist);
         $matrix[] = array('label' => sprintf('%s <%s>', (string) $group, $guuid), 'type' => self::TYP_GROUP, 'roles' => $groles);
         foreach ($effective as $role => $val) {
             if ($groles[$role] === self::ACL_DENY) {
                 $effective[$role] = self::ACL_DENY;
             } elseif ($groles[$role] === self::ACL_ALLOW) {
                 $effective[$role] = self::ACL_ALLOW;
             }
         }
     }
     // Determine and label the roles for the subject
     $sroles = acl::getExplicitAccessRecord($suuid, $ouuid, $rlist);
     $matrix[] = array('label' => sprintf('%s <%s>', (string) $subject, $suuid), 'type' => self::TYP_SUBJECT, 'roles' => $sroles);
     foreach ($effective as $role => $val) {
         if ($sroles[$role] === self::ACL_DENY) {
             $effective[$role] = self::ACL_DENY;
         } elseif ($sroles[$role] === self::ACL_ALLOW) {
             $effective[$role] = self::ACL_ALLOW;
         }
     }
     // Finally assemble the effective permissions
     $matrix[] = array('label' => sprintf('%s <%s>', (string) $subject, $suuid), 'type' => self::TYP_EFFECTIVE, 'roles' => $effective);
     // Return result
     return $matrix;
 }
 /**
  * Generate HTML CONTENT element of type $tag
  * Change to allow $content to be assoc array with same params as args
  * EXPERIMENT: Try Using Raw Count to prevent filtering of input els.
  * @param string $tag - the HTML tag - required
  * @param scalar|array|null $content
  * @param string|array|null $attributes
  * @param boolean $raw - default true
  * @return html string
  */
 public function tagged($tag, $content = null, $attributes = null, $raw = false)
 {
     $ctype = typeOf($content);
     //if (! is_simple($content)) pkdebug("Type of Content: [$ctype]");
     $attributes = $this->cleanAttributes($attributes);
     if ($content === true || $content === $this) {
         #That's RENDEROPEN === TRUE
         $spaces = $this->spaceDepth();
         $size = $this->addTagStack([$tag => ['raw' => $raw]]);
         return $this->rawcontent("{$spaces}<{$tag} " . PkHtml::attributes($attributes) . ">\n");
     } else {
         if ($content === false) {
             ##Nest the elements
             $spaces = $this->spaceDepth();
             $size = $this->addDepthTagStack($tag);
             return $this->rawcontent("{$spaces}<{$tag} " . $this->attributes($attributes) . ">\n");
         } else {
             #Trust that text already wrapped in PhHtmlRenderer has already been filtered
             //if (!$raw && !static::getRawCount() && !($content instanceOf PkHtmlRenderer)) {
             //$this[]=$this->spaceDepth()."<$tag ".PkHtml::attributes($attributes).">
             $this->rawcontent($this->spaceDepth() . "<{$tag} " . PkHtml::attributes($attributes) . ">\n");
             if (is_array($content)) {
                 foreach ($content as $citem) {
                     $this->content($citem, $raw);
                 }
             } else {
                 $this->content($content, $raw);
             }
             $this->rawcontent($this->spaceDepth() . "</{$tag}>\n");
             return $this;
         }
     }
 }
 /**
  * @param mixed $v
  * @return string
  */
 function filter_type($v)
 {
     return typeOf($v);
 }