/**
  * Register transport implementation for a specific scheme
  *
  * @param   string scheme
  * @param   lang.XPClass<peer.http.HttpTransport> class
  */
 public static function register($scheme, XPClass $class)
 {
     if (!$class->isSubclassOf('peer.http.HttpTransport')) {
         throw new \lang\IllegalArgumentException(sprintf('Given argument must be lang.XPClass<peer.http.HttpTransport>, %s given', $class->toString()));
     }
     self::$transports[$scheme] = $class;
 }
 /**
  * Register an algorithm
  *
  * @param   string name
  * @param   lang.XPClass<security.password.Algorithm> impl
  * @throws  lang.IllegalArgumentException in case the given class is not an Algorithm 
  */
 public static function setAlgorithm($name, \lang\XPClass $impl)
 {
     if (!$impl->isSubclassOf('security.password.Algorithm')) {
         throw new \lang\IllegalArgumentException('Given argument is not an Algorithm class (' . \xp::stringOf($impl) . ')');
     }
     self::$algorithms[$name] = $impl;
 }
 /**
  * Fetch a qname for a class.
  *
  * @param   lang.XPClass class
  * @return  var xml.QName or NULL if no mapping exists
  */
 public function qnameFor(\lang\XPClass $class)
 {
     if (!isset($this->_c2q[$class->getName()])) {
         return null;
     }
     return $this->_qnames[$this->_c2q[$class->getName()]];
 }
 /**
  * Register an implementation
  *
  * @param   string algorithm
  * @param   lang.XPClass<security.checksum.MessageDigestImpl> class
  * @throws  lang.IllegalArgumentException
  */
 public static function register($algorithm, \lang\XPClass $impl)
 {
     if (!$impl->isSubclassOf('security.checksum.MessageDigestImpl')) {
         throw new \lang\IllegalArgumentException('Implementation class must be a security.checksum.MessageDigestImpl');
     }
     self::$implementations[$algorithm] = $impl;
 }
 /**
  * Tries to get method start line
  *
  * @param lang.XPClass $class
  * @param string $methodname
  * @return int
  */
 private function lineFor(XPClass $class, $methodname)
 {
     try {
         return $class->reflect()->getMethod($methodname)->getStartLine();
     } catch (\Exception $ignored) {
         return 0;
     }
 }
Example #6
0
 /**
  * Creates a new collector gathering the elements in a collection class
  *
  * @param  lang.XPClass $class
  * @return util.data.ICollector
  */
 public static function toCollection(XPClass $class)
 {
     return new Collector(function () use($class) {
         return $class->newInstance();
     }, function ($result, $arg) {
         $result->add($arg);
     });
 }
 /**
  * Locate interface by a given name
  *
  * @param  lang.XPClass $class
  * @param  string $name
  * @return lang.XPClass
  * @throws lang.ElementNotFoundException
  */
 private function interfaceNamed($class, $name)
 {
     foreach ($class->getInterfaces() as $iface) {
         if (strstr($iface->getName(), $name)) {
             return $iface;
         }
     }
     throw new ElementNotFoundException('Class ' . $class->getName() . ' does not implement ' . $name);
 }
 /**
  * Returns methods annotated with a given annotatoons
  *
  * @param  lang.XPClass $self
  * @param  string $annotation
  * @return lang.reflect.Method[]
  */
 public static function methodsAnnotatedWith(\lang\XPClass $self, $annotation)
 {
     $name = substr($annotation, 1);
     $r = array();
     foreach ($self->getMethods() as $method) {
         if ($method->hasAnnotation($name)) {
             $r[] = $method;
         }
     }
     return $r;
 }
Example #9
0
 /**
  * Add a measurable class
  *
  * @param  lang.XPClass $class
  * @param  lang.reflect.Method $method
  * @param  var $source
  * @return util.data.Sequence
  */
 private function permutationOf($class, $method, $source)
 {
     if (is_array($source)) {
         $seq = Sequence::of($source);
     } else {
         $seq = Sequence::of($class->getMethod($source)->setAccessible(true)->invoke(null));
     }
     return $seq->map(function ($args) use($class, $method) {
         return $class->newInstance($method, (array) $args);
     });
 }
 /**
  * Constructor
  *
  * @param   lang.XPClass $scriptlet
  * @param   string[] args
  * @param   [:string] env
  */
 public function __construct(XPClass $scriptlet, $args, $env = [], $filters = [])
 {
     if ($scriptlet->hasConstructor()) {
         $this->scriptlet = $scriptlet->getConstructor()->newInstance((array) $args);
     } else {
         $this->scriptlet = $scriptlet->newInstance();
     }
     foreach ($filters as $filter) {
         $this->scriptlet->filter($filter);
     }
     $this->scriptlet->init();
     $this->env = $env;
 }
Example #11
0
 /**
  * Show usage
  *
  * @param  lang.XPClass class
  * @return void
  */
 protected function commandUsage(XPClass $class)
 {
     // Description
     if (null !== ($comment = $class->getComment())) {
         self::$err->writeLine(self::textOf($comment));
         self::$err->writeLine(str_repeat('=', 72));
     }
     $extra = $details = $positional = [];
     foreach ($class->getMethods() as $method) {
         if (!$method->hasAnnotation('arg')) {
             continue;
         }
         $arg = $method->getAnnotation('arg');
         $name = strtolower(preg_replace('/^set/', '', $method->getName()));
         $comment = self::textOf($method->getComment());
         if (0 == $method->numParameters()) {
             $optional = true;
         } else {
             list($first, ) = $method->getParameters();
             $optional = $first->isOptional();
         }
         if (isset($arg['position'])) {
             $details['#' . ($arg['position'] + 1)] = $comment;
             $positional[$arg['position']] = $name;
         } else {
             if (isset($arg['name'])) {
                 $details['--' . $arg['name'] . ' | -' . (isset($arg['short']) ? $arg['short'] : $arg['name'][0])] = $comment;
                 $extra[$arg['name']] = $optional;
             } else {
                 $details['--' . $name . ' | -' . (isset($arg['short']) ? $arg['short'] : $name[0])] = $comment;
                 $extra[$name] = $optional;
             }
         }
     }
     // Usage
     asort($positional);
     self::$err->write('Usage: $ xpcli ', Commands::nameOf($class), ' ');
     foreach ($positional as $name) {
         self::$err->write('<', $name, '> ');
     }
     foreach ($extra as $name => $optional) {
         self::$err->write($optional ? '[' : '', '--', $name, $optional ? '] ' : ' ');
     }
     self::$err->writeLine();
     // Argument details
     self::$err->writeLine('Arguments:');
     foreach ($details as $which => $comment) {
         self::$err->writeLine('* ', $which, "\n  ", str_replace("\n", "\n  ", $comment), "\n");
     }
 }
Example #12
0
 /**
  * Shows usage
  *
  * @param  lang.XPClass $class
  * @return void
  */
 protected function commandUsage(XPClass $class)
 {
     $comment = $class->getComment();
     if ('' === (string) $comment) {
         $markdown = '# ' . $class->getSimpleName() . "\n\n";
         $text = '';
     } else {
         @(list($headline, $text) = explode("\n", $comment, 2));
         $markdown = '# ' . ltrim($headline, ' #') . "\n\n";
     }
     $markdown .= "- Usage\n  ```sh\n\$ xp cmd " . Commands::nameOf($class);
     $extra = $details = $positional = [];
     foreach ($class->getMethods() as $method) {
         if (!$method->hasAnnotation('arg')) {
             continue;
         }
         $arg = $method->getAnnotation('arg');
         $name = strtolower(preg_replace('/^set/', '', $method->getName()));
         $optional = 0 === $method->numParameters() || $method->getParameters()[0]->isOptional();
         $comment = $method->getComment();
         if (isset($arg['position'])) {
             $details[$name] = [$comment, null];
             $positional[$arg['position']] = $name;
         } else {
             if (isset($arg['name'])) {
                 $details['--' . $arg['name']] = [$comment, isset($arg['short']) ? $arg['short'] : $arg['name'][0]];
                 $extra[$arg['name']] = $optional;
             } else {
                 $details['--' . $name] = [$comment, isset($arg['short']) ? $arg['short'] : $name[0]];
                 $extra[$name] = $optional;
             }
         }
     }
     // Usage
     asort($positional);
     foreach ($positional as $name) {
         $markdown .= ' ' . $name;
     }
     foreach ($extra as $name => $optional) {
         $markdown .= ' ' . (($optional ? '[' : '') . '--' . $name . ($optional ? '] ' : ' '));
     }
     $markdown .= "\n  ```\n";
     // Argument details
     foreach ($details as $which => $detail) {
         $markdown .= sprintf("  **%s**: %s%s\n\n", $which, str_replace("\n", "\n  ", $detail[0]), $detail[1] ? ' *(also: -' . $detail[1] . ')*' : '');
     }
     Help::render(self::$err, substr($markdown, 0, -1) . $text, $class->getClassLoader());
 }
 public function putParameters()
 {
     $params = $this->fixture->getClass()->getMethod('put')->getParameters();
     $this->assertEquals(2, sizeof($params));
     $this->assertEquals(Primitive::$STRING, $params[0]->getType());
     $this->assertEquals(XPClass::forName('unittest.TestCase'), $params[1]->getType());
 }
Example #14
0
 public function object_return_type()
 {
     $fixture = $this->define('{
   public function fixture(): \\lang\\Object { return new \\lang\\Object(); }
 }');
     $this->assertEquals(XPClass::forName('lang.Object'), $this->newFixture($fixture)->methods()->named('fixture')->returns());
 }
Example #15
0
 /**
  * Creates a new instance
  *
  * @param  string $source
  * @param  xp.scriptlet.Config $config
  * @throws lang.IllegalArgumentException
  */
 public function __construct($source, Config $config = null)
 {
     if ('-' === $source) {
         $this->layout = new ServeDocumentRootStatically();
     } else {
         if (is_file($source)) {
             $this->layout = new WebConfiguration(new Properties($source), $config);
         } else {
             if (is_dir($source)) {
                 $this->layout = new BasedOnWebroot($source, $config);
             } else {
                 $name = ltrim($source, ':');
                 try {
                     $class = XPClass::forName($name);
                 } catch (ClassLoadingException $e) {
                     throw new IllegalArgumentException('Cannot load ' . $name, $e);
                 }
                 if ($class->isSubclassOf('xp.scriptlet.WebLayout')) {
                     if ($class->hasConstructor()) {
                         $this->layout = $class->getConstructor()->newInstance([$config]);
                     } else {
                         $this->layout = $class->newInstance();
                     }
                 } else {
                     if ($class->isSubclassOf('scriptlet.HttpScriptlet')) {
                         $this->layout = new SingleScriptlet($class->getName(), $config);
                     } else {
                         throw new IllegalArgumentException('Expecting either a scriptlet or a weblayout, ' . $class->getName() . ' given');
                     }
                 }
             }
         }
     }
 }
Example #16
0
 /**
  * Main
  *
  * @param   string[] args
  */
 public static function main(array $args)
 {
     $way = array_shift($args);
     $argc = sizeof($args);
     // Read sourcecode from STDIN if no further argument is given
     if (0 === $argc) {
         $code = new Code(file_get_contents('php://stdin'));
     } else {
         if ('--' === $args[0]) {
             $code = new Code(file_get_contents('php://stdin'));
         } else {
             $code = new Code($args[0]);
         }
     }
     // Perform
     $argv = [XPClass::nameOf(self::class)] + $args;
     $return = eval($code->head() . $code->expression());
     switch ($way) {
         case '-w':
             Console::writeLine($return);
             break;
         case '-d':
             var_dump($return);
             break;
     }
 }
 public function genericInterface()
 {
     $interfaces = \lang\XPClass::forName('lang.Object')->getInterfaces();
     $this->assertEquals(1, sizeof($interfaces));
     $this->assertInstanceOf('lang.XPClass', $interfaces[0]);
     $this->assertEquals('lang.Generic', $interfaces[0]->getName());
 }
Example #18
0
 /**
  * Main
  *
  * Exitcodes used:
  * <ul>
  *   <li>127: Archive referenced in -xar [...] does not exist</li>
  *   <li>126: No manifest or manifest does not have a main-class</li>
  * </ul>
  *
  * @see     http://tldp.org/LDP/abs/html/exitcodes.html
  * @param   string[] args
  * @return  int
  */
 public static function main(array $args)
 {
     // Open archive
     $f = new File(array_shift($args));
     if (!$f->exists()) {
         Console::$err->writeLine('*** Cannot find archive ' . $f->getURI());
         return 127;
     }
     // Register class loader
     $cl = \lang\ClassLoader::registerLoader(new \lang\archive\ArchiveClassLoader(new Archive($f)));
     if (!$cl->providesResource(self::MANIFEST)) {
         Console::$err->writeLine('*** Archive ' . $f->getURI() . ' does not have a manifest');
         return 126;
     }
     // Load manifest
     $pr = Properties::fromString($cl->getResource(self::MANIFEST));
     if (null === ($class = $pr->readString('archive', 'main-class', null))) {
         Console::$err->writeLine('*** Archive ' . $f->getURI() . '\'s manifest does not have a main class');
         return 126;
     }
     // Run main()
     try {
         return \lang\XPClass::forName($class, $cl)->getMethod('main')->invoke(null, [$args]);
     } catch (\lang\reflect\TargetInvocationException $e) {
         throw $e->getCause();
     }
 }
Example #19
0
 /**
  * Constructor
  *
  * @param   rdbms.DSN dsn
  */
 public function __construct($dsn)
 {
     $this->dsn = $dsn;
     $this->flags = $dsn->getFlags();
     if (!$this->dsn->url->hasParam('autoconnect')) {
         $this->flags |= DB_AUTOCONNECT;
     }
     $this->setTimeout($dsn->getProperty('timeout', 0));
     // 0 means no timeout
     // Keep this for BC reasons
     $observers = $dsn->getProperty('observer', []);
     if (null !== ($cat = $dsn->getProperty('log'))) {
         $observers['util.log.LogObserver'] = $cat;
     }
     // Add observers
     foreach ($observers as $observer => $param) {
         $class = XPClass::forName($observer);
         // Check if class implements BoundLogObserver: in that case use factory method to acquire
         // instance. Otherwise, just use the constructor
         if (XPClass::forName('util.log.BoundLogObserver')->isAssignableFrom($class)) {
             $this->addObserver($class->getMethod('instanceFor')->invoke(null, [$param]));
         } else {
             $this->addObserver($class->newInstance($param));
         }
     }
     // Time zone handling
     if ($tz = $dsn->getProperty('timezone', false)) {
         $this->tz = new TimeZone($tz);
     }
 }
 static function __static()
 {
     self::$byName['if'] = XPClass::forName('com.handlebarsjs.IfBlockHelper');
     self::$byName['unless'] = XPClass::forName('com.handlebarsjs.UnlessBlockHelper');
     self::$byName['with'] = XPClass::forName('com.handlebarsjs.WithBlockHelper');
     self::$byName['each'] = XPClass::forName('com.handlebarsjs.EachBlockHelper');
 }
Example #21
0
 public function type_bound_to_type_provider()
 {
     $inject = new Injector();
     $provider = new TypeProvider(XPClass::forName(FileSystem::class), $inject);
     $inject->bind(Storage::class, $provider);
     $this->assertInstanceOf(FileSystem::class, $inject->get(Storage::class));
 }
 /**
  * Add Portlets
  *
  * @param   string classname
  * @param   string layout
  * @return  xml.portlet.Portlet
  */
 public function addPortlet($classname, $layout = null)
 {
     with($portlet = \lang\XPClass::forName($classname)->newInstance());
     $portlet->setLayout($layout);
     $this->portlets[] = $portlet;
     return $portlet;
 }
 public function given_interface_class_is_implemented()
 {
     $class = $this->define(['interfaces' => [XPClass::forName(Runnable::class)]], '{
   public function run() { } 
 }');
     $this->assertTrue($class->isSubclassOf(Runnable::class));
 }
Example #24
0
 /**
  * Matches implementation
  * 
  * @param   var value
  * @return  bool
  */
 public function matches($value)
 {
     if (null === $value && $this->matchNull) {
         return true;
     }
     return \xp::typeof($value) == \lang\XPClass::forName($this->type)->getName();
 }
Example #25
0
 /**
  * Compile class from source and return compiled type
  *
  * @param   string src
  * @return  xp.compiler.types.TypeReflection
  */
 protected function compile($src)
 {
     $unique = 'FixtureClassFor' . $this->getClass()->getSimpleName() . ucfirst($this->name);
     $r = $this->emitter->emit(Syntax::forName('xp')->parse(new MemoryInputStream(sprintf($src, $unique))), $this->scope);
     $r->executeWith([]);
     return new TypeReflection(\lang\XPClass::forName($r->type()->name()));
 }
 public function putParameters()
 {
     $params = $this->fixture->getClass()->getMethod('put')->getParameters();
     $this->assertEquals(2, sizeof($params));
     $this->assertEquals(\lang\XPClass::forName('lang.types.String'), $params[0]->getType());
     $this->assertEquals(\lang\XPClass::forName('unittest.TestCase'), $params[1]->getType());
 }
Example #27
0
 /**
  * Get all test cases
  *
  * @param   lang.XPClass class
  * @param   var[] arguments
  * @return  unittest.TestCase[]
  */
 public function testCasesInClass(\lang\XPClass $class, $arguments = null)
 {
     // Verify we were actually given a testcase class
     if (!$class->isSubclassOf('unittest.TestCase')) {
         throw new \lang\IllegalArgumentException('Given argument is not a TestCase class (' . \xp::stringOf($class) . ')');
     }
     // Add all tests cases
     $r = [];
     foreach ($class->getMethods() as $m) {
         $m->hasAnnotation('test') && ($r[] = $class->getConstructor()->newInstance(array_merge((array) $m->getName(true), (array) $arguments)));
     }
     // Verify we actually added tests by doing this.
     if (empty($r)) {
         throw new \util\NoSuchElementException('No tests found in ' . $class->getName());
     }
     return $r;
 }
 public function returnNewObjectViaMethodInvoke()
 {
     $class = \lang\XPClass::forName('net.xp_framework.unittest.core.AnonymousFactory');
     $factory = $class->getMethod('factory');
     $object = $factory->invoke($instance = NULL);
     $value = ReferencesTest::registry('list', $r = NULL);
     $this->assertReference($object, $value);
 }
 /**
  * Creates a segment instance
  *
  * @param  string $marker
  * @param  string $bytes
  * @return self
  */
 public static function read($marker, $bytes)
 {
     if (is_array($iptc = iptcparse($bytes))) {
         return \lang\XPClass::forName('img.io.IptcSegment')->newInstance($marker, $iptc);
     } else {
         return new self($marker, $bytes);
     }
 }
Example #30
0
 /**
  * Returns the implementation for the given operating system.
  *
  * @param   string os operating system name, e.g. PHP_OS
  * @param   string socket default NULL
  * @return  rdbms.mysqlx.LocalSocket
  */
 public static function forName($os, $socket = null)
 {
     if (0 === strncasecmp($os, 'Win', 3)) {
         return \lang\XPClass::forName('rdbms.mysqlx.NamedPipe')->newInstance($socket);
     } else {
         return \lang\XPClass::forName('rdbms.mysqlx.UnixSocket')->newInstance($socket);
     }
 }