Use this class to build expressions:ons: php $expr = Expr::greaterThan(20)->orLessThan(10); You can evaluate the expression with another value {@link Expression::evaluate()}: php if ($expr->evaluate($value)) { do something... } You can also evaluate expressions by arrays by passing the array keys as second argument: php $expr = Expr::greaterThan(20, 'age') ->andStartsWith('Thomas', 'name'); $values = array( 'age' => 35, 'name' => 'Thomas Edison', ); if ($expr->evaluate($values)) { do something... }
Since: 1.0
Author: Bernhard Schussek (bschussek@gmail.com)
 public function testDomainExpressions()
 {
     $c1 = new Customer();
     $c1->setPremium(true);
     $c2 = new Customer();
     $c2->setBookings(array('booking1', 'booking2'));
     $c3 = new Customer();
     $c3->setPremium(true);
     $c3->setBookings(array('booking1'));
     $customers = array($c1, $c2, $c3);
     $this->assertEquals(array($c1, 2 => $c3), Expr::filter($customers, new IsPremium()));
     $this->assertEquals(array(1 => $c2, 2 => $c3), Expr::filter($customers, new HasPreviousBookings()));
     $this->assertEquals(array(2 => $c3), Expr::filter($customers, Expr::andX(array(new HasPreviousBookings(), new IsPremium()))));
 }
 public function testRemoveBindingsWithTypeAndParameterWorksOnLoadedDiscovery()
 {
     $binding1 = new StringBinding('string1', Foo::clazz, array('param2' => 'bar'));
     $binding2 = new StringBinding('string2', Foo::clazz);
     $binding3 = new StringBinding('string3', Foo::clazz, array('param1' => 'bar'));
     $discovery = $this->createDiscovery();
     $discovery->addBindingType(new BindingType(Foo::clazz, self::STRING_BINDING, array(new BindingParameter('param1', BindingParameter::OPTIONAL, 'foo'), new BindingParameter('param2'))));
     $discovery->addBinding($binding1);
     $discovery->addBinding($binding2);
     $discovery->addBinding($binding3);
     $discovery = $this->loadDiscoveryFromStorage($discovery);
     // Bindings need to be initialized for this to work
     $discovery->removeBindings(Foo::clazz, Expr::method('getParameterValue', 'param1', Expr::same('foo')));
     $this->assertEquals(array($binding3), $discovery->findBindings(Foo::clazz));
     $this->assertEquals(array($binding3), $discovery->getBindings());
 }
 /**
  * Handles the "puli type --list" command.
  *
  * @param Args $args The console arguments.
  * @param IO   $io   The I/O.
  *
  * @return int The status code.
  */
 public function handleList(Args $args, IO $io)
 {
     $packageNames = ArgsUtil::getPackageNames($args, $this->packages);
     $states = $this->getBindingTypeStates($args);
     $printStates = count($states) > 1;
     $printPackageName = count($packageNames) > 1;
     $printHeaders = $printStates || $printPackageName;
     $printTypeAdvice = true;
     $printBindAdvice = false;
     $indentation = $printStates && $printPackageName ? 8 : ($printStates || $printPackageName ? 4 : 0);
     foreach ($states as $state) {
         $statePrinted = !$printStates;
         foreach ($packageNames as $packageName) {
             $expr = Expr::method('getContainingPackage', Expr::method('getName', Expr::same($packageName)))->andMethod('getState', Expr::same($state));
             $bindingTypes = $this->discoveryManager->findTypeDescriptors($expr);
             if (!$bindingTypes) {
                 continue;
             }
             $printTypeAdvice = false;
             if (!$statePrinted) {
                 $this->printBindingTypeState($io, $state);
                 $statePrinted = true;
                 // Only print the advice if at least one type was printed
                 $printBindAdvice = true;
             }
             if ($printPackageName) {
                 $prefix = $printStates ? '    ' : '';
                 $io->writeLine("{$prefix}Package: {$packageName}");
                 $io->writeLine('');
             }
             $styleTag = BindingTypeState::ENABLED === $state ? null : 'bad';
             $this->printTypeTable($io, $bindingTypes, $styleTag, $indentation);
             if ($printHeaders) {
                 $io->writeLine('');
             }
         }
     }
     if ($printTypeAdvice) {
         $io->writeLine('No types defined. Use "puli type --define <name>" to define a type.');
     }
     if ($printBindAdvice) {
         $io->writeLine('Use "puli bind <resource> <type>" to bind a resource to a type.');
     }
     return 0;
 }
 /**
  * {@inheritdoc}
  */
 public function clearPluginClasses()
 {
     $this->removePluginClasses(Expr::true());
 }
 public function testAppendDefaultQuerySuffixForEndsWith()
 {
     $expr1 = Expr::endsWith('.css', AssetMapping::GLOB);
     $expr2 = Expr::same(BindingState::ENABLED, BindingDescriptor::STATE)->andSame(DiscoveryUrlGenerator::BINDING_TYPE, BindingDescriptor::TYPE_NAME)->andEndsWith('{,/**/*}', BindingDescriptor::QUERY)->andEndsWith('.css{,/**/*}', BindingDescriptor::QUERY);
     $this->assertEquals($expr2, $this->builder->buildExpression($expr1));
 }
 public function testHasBindings()
 {
     $this->initDefaultManager();
     $this->rootPackageFile->addTypeDescriptor(new BindingTypeDescriptor('my/type1'));
     $this->rootPackageFile->addBindingDescriptor($binding1 = new BindingDescriptor('/path1', 'my/type1'));
     $this->packageFile1->addBindingDescriptor($binding2 = new BindingDescriptor('/path2', 'my/type2'));
     $expr1 = Expr::same('vendor/package1', BindingDescriptor::CONTAINING_PACKAGE);
     $expr2 = Expr::same(BindingState::ENABLED, BindingDescriptor::STATE);
     $expr3 = $expr1->andX($expr2);
     $this->assertTrue($this->manager->hasBindings());
     $this->assertTrue($this->manager->hasBindings($expr1));
     $this->assertTrue($this->manager->hasBindings($expr2));
     $this->assertFalse($this->manager->hasBindings($expr3));
 }
Beispiel #7
0
 /**
  * Finds the resources for a given binding type.
  *
  * @param string $typeName The type name.
  *
  * @return string[] An array of short resource class names indexed by
  *                  the resource path.
  */
 private function findByBindingType($typeName)
 {
     $matches = array();
     $expr = Expr::isInstanceOf('Puli\\Discovery\\Binding\\ResourceBinding');
     foreach ($this->discovery->findBindings($typeName, $expr) as $binding) {
         /** @var ResourceBinding $binding */
         foreach ($binding->getResources() as $resource) {
             $matches[$resource->getPath()] = StringUtil::getShortClassName(get_class($resource));
         }
     }
     ksort($matches);
     return $matches;
 }
 /**
  * {@inheritdoc}
  */
 public function hasRootPathMappings(Expression $expr = null)
 {
     $expr2 = Expr::same($this->rootPackage->getName(), PathMapping::CONTAINING_PACKAGE);
     if ($expr) {
         $expr2 = $expr2->andX($expr);
     }
     return $this->hasPathMappings($expr2);
 }
 /**
  * {@inheritdoc}
  */
 public function clearServers()
 {
     $this->removeServers(Expr::true());
 }
Beispiel #10
0
 /**
  * Returns the resource discovery manager.
  *
  * @return DiscoveryManager The discovery manager.
  */
 public function getDiscoveryManager()
 {
     if (!$this->started) {
         throw new LogicException('Puli was not started');
     }
     if (!$this->discoveryManager && $this->context instanceof ProjectContext) {
         $this->discoveryManager = new DiscoveryManagerImpl($this->context, $this->getDiscovery(), $this->getPackageManager()->findPackages(Expr::method('isEnabled', Expr::same(true))), $this->getPackageFileStorage(), $this->logger);
     }
     return $this->discoveryManager;
 }
 public function testRemoveConfigKeysRevertsIfSavingNotPossible()
 {
     $this->configFile->getConfig()->set(Config::PULI_DIR, 'my-puli-dir');
     $this->configFileStorage->expects($this->once())->method('saveConfigFile')->willThrowException(new TestException());
     try {
         $this->manager->removeConfigKeys(Expr::in(array(Config::PULI_DIR, Config::FACTORY_IN_FILE)));
         $this->fail('Expected a TestException');
     } catch (TestException $e) {
     }
     $this->assertTrue($this->configFile->getConfig()->contains(Config::PULI_DIR));
     $this->assertFalse($this->configFile->getConfig()->contains(Config::FACTORY_IN_FILE));
     $this->assertSame('my-puli-dir', $this->configFile->getConfig()->get(Config::PULI_DIR));
 }
 /**
  * {@inheritdoc}
  */
 public function clearModules()
 {
     $this->removeModules(Expr::true());
 }
Beispiel #13
0
 /**
  * @param string $uuidPrefix
  *
  * @return AssetMapping
  */
 private function getMappingByUuidPrefix($uuidPrefix)
 {
     $expr = Expr::startsWith($uuidPrefix, AssetMapping::UUID);
     $mappings = $this->assetManager->findAssetMappings($expr);
     if (!$mappings) {
         throw new RuntimeException(sprintf('The mapping with the UUID prefix "%s" does not exist.', $uuidPrefix));
     }
     if (count($mappings) > 1) {
         throw new RuntimeException(sprintf('More than one mapping matches the UUID prefix "%s".', $uuidPrefix));
     }
     return reset($mappings);
 }
 /**
  * {@inheritdoc}
  */
 public function hasAssetMapping(Uuid $uuid)
 {
     $expr = Expr::method('getUuid', Expr::method('toString', Expr::same($uuid->toString())))->andX($this->exprBuilder->buildExpression());
     return $this->discoveryManager->hasBindingDescriptors($expr);
 }
Beispiel #15
0
 /**
  * Returns the packages that should be displayed for the given console
  * arguments.
  *
  * @param Args $args The console arguments.
  *
  * @return PackageCollection The packages.
  */
 private function getSelectedPackages(Args $args)
 {
     $states = $this->getSelectedStates($args);
     $expr = Expr::true();
     if ($states != PackageState::all()) {
         $expr = $expr->andIn($states, Package::STATE);
     }
     if ($args->isOptionSet('installer')) {
         $expr = $expr->andSame($args->getOption('installer'), Package::INSTALLER);
     }
     return $this->packageManager->findPackages($expr);
 }
Beispiel #16
0
 private function packageAndState($packageName, $state)
 {
     return Expr::same($packageName, BindingTypeDescriptor::CONTAINING_PACKAGE)->andSame($state, BindingTypeDescriptor::STATE);
 }
Beispiel #17
0
 /**
  * Returns the packages that should be displayed for the given console
  * arguments.
  *
  * @param Args $args The console arguments.
  *
  * @return PackageCollection The packages.
  */
 private function getSelectedPackages(Args $args)
 {
     $states = $this->getSelectedStates($args);
     $expr = Expr::true();
     $envs = array();
     if ($states !== PackageState::all()) {
         $expr = $expr->andMethod('getState', Expr::in($states));
     }
     if ($args->isOptionSet('installer')) {
         $expr = $expr->andMethod('getInstallInfo', Expr::method('getInstallerName', Expr::same($args->getOption('installer'))));
     }
     if ($args->isOptionSet('prod')) {
         $envs[] = Environment::PROD;
     }
     if ($args->isOptionSet('dev')) {
         $envs[] = Environment::DEV;
     }
     if (count($envs) > 0) {
         $expr = $expr->andMethod('getInstallInfo', Expr::method('getEnvironment', Expr::in($envs)));
     }
     return $this->packageManager->findPackages($expr);
 }
 private function installerAndState($installer, $state)
 {
     return Expr::same($installer, Package::INSTALLER)->andSame($state, Package::STATE);
 }
 public function testRemoveServersRevertsIfSavingFails()
 {
     $this->packageFileManager->expects($this->any())->method('getExtraKey')->with(PackageFileServerManager::SERVERS_KEY)->willReturn((object) array('localhost' => (object) array('installer' => 'symlink', 'document-root' => 'web', 'url-format' => '/public/%s'), 'cdn' => (object) array('installer' => 'rsync', 'document-root' => 'ssh://my.cdn.com', 'parameters' => (object) array('param' => 'value'))));
     $this->packageFileManager->expects($this->once())->method('setExtraKey')->willThrowException(new TestException());
     try {
         $this->serverManager->removeServers(Expr::startsWith('localhost', Server::NAME));
         $this->fail('Expected a TestException');
     } catch (TestException $e) {
     }
     $this->assertTrue($this->serverManager->hasServer('localhost'));
     $this->assertTrue($this->serverManager->hasServer('cdn'));
 }
 public function testMatch()
 {
     $type = new BindingTypeDescriptor('vendor/type');
     $type->load($this->package);
     $this->assertFalse($type->match(Expr::same('foobar', BindingTypeDescriptor::NAME)));
     $this->assertTrue($type->match(Expr::same('vendor/type', BindingTypeDescriptor::NAME)));
     $this->assertFalse($type->match(Expr::same('foobar', BindingTypeDescriptor::CONTAINING_PACKAGE)));
     $this->assertTrue($type->match(Expr::same($this->package->getName(), BindingTypeDescriptor::CONTAINING_PACKAGE)));
     $this->assertFalse($type->match(Expr::same(BindingTypeState::DUPLICATE, BindingTypeDescriptor::STATE)));
     $this->assertTrue($type->match(Expr::same(BindingTypeState::ENABLED, BindingTypeDescriptor::STATE)));
 }
 /**
  * {@inheritdoc}
  */
 public function leaveExpression(Expression $expr)
 {
     if ($expr instanceof Method) {
         switch ($expr->getMethodName()) {
             case 'getUuid':
                 return Expr::method('getUuid', $expr->getExpression());
             case 'getGlob':
                 $queryExpr = $expr->getExpression();
                 if ($queryExpr instanceof Same) {
                     $queryExpr = Expr::same($queryExpr->getComparedValue() . '{,/**/*}');
                 } elseif ($queryExpr instanceof Equals) {
                     $queryExpr = Expr::equals($queryExpr->getComparedValue() . '{,/**/*}');
                 } elseif ($queryExpr instanceof NotSame) {
                     $queryExpr = Expr::notSame($queryExpr->getComparedValue() . '{,/**/*}');
                 } elseif ($queryExpr instanceof NotEquals) {
                     $queryExpr = Expr::notEquals($queryExpr->getComparedValue() . '{,/**/*}');
                 } elseif ($queryExpr instanceof EndsWith) {
                     $queryExpr = Expr::endsWith($queryExpr->getAcceptedSuffix() . '{,/**/*}');
                 }
                 return Expr::method('getBinding', Expr::method('getQuery', $queryExpr));
             case 'getServerName':
                 return Expr::method('getParameterValue', DiscoveryUrlGenerator::SERVER_PARAMETER, $expr->getExpression());
             case 'getServerPath':
                 return Expr::method('getParameterValue', DiscoveryUrlGenerator::PATH_PARAMETER, $expr->getExpression());
         }
     }
     return $expr;
 }
Beispiel #22
0
 /**
  * {@inheritdoc}
  */
 public function hasRootBindingDescriptors(Expression $expr = null)
 {
     $expr2 = Expr::method('getContainingModule', Expr::same($this->rootModule));
     if ($expr) {
         $expr2 = $expr2->andX($expr);
     }
     return $this->hasBindingDescriptors($expr2);
 }
 public function testAndXReturnsFalse()
 {
     $conjunction1 = new AndX(array($notNull = new Same('10')));
     $conjunction2 = $conjunction1->andX($false = Expr::false());
     $this->assertSame($false, $conjunction2);
 }
 /**
  * {@inheritdoc}
  */
 public function clearRootInstallerDescriptors()
 {
     $this->removeRootInstallerDescriptors(Expr::true());
 }
    public function testInstallWithServer()
    {
        $mapping1 = new AssetMapping('/app/public', 'localhost', '/');
        $mapping2 = new AssetMapping('/acme/blog/public/{css,js}', 'localhost', '/blog');
        $symlinkInstaller = $this->getMock('Puli\\Manager\\Api\\Installer\\ResourceInstaller');
        $symlinkInstallerDescriptor = new InstallerDescriptor('symlink', get_class($symlinkInstaller));
        $localServer = new Server('localhost', 'symlink', 'public_html');
        $resource1 = new GenericResource('/app/public');
        $resource2 = new GenericResource('/acme/blog/public/css');
        $resource3 = new GenericResource('/acme/blog/public/js');
        $params1 = new InstallationParams($symlinkInstaller, $symlinkInstallerDescriptor, new ArrayResourceCollection(array($resource1)), $mapping1, $localServer, __DIR__);
        $params2 = new InstallationParams($symlinkInstaller, $symlinkInstallerDescriptor, new ArrayResourceCollection(array($resource2, $resource3)), $mapping2, $localServer, __DIR__);
        $this->assetManager->expects($this->once())->method('findAssetMappings')->with(Expr::same('localhost', AssetMapping::SERVER_NAME))->willReturn(array($mapping1, $mapping2));
        $this->installationManager->expects($this->at(0))->method('prepareInstallation')->with($mapping1)->willReturn($params1);
        $this->installationManager->expects($this->at(1))->method('prepareInstallation')->with($mapping2)->willReturn($params2);
        $this->installationManager->expects($this->at(2))->method('installResource')->with($resource1, $params1);
        $this->installationManager->expects($this->at(3))->method('installResource')->with($resource2, $params2);
        $this->installationManager->expects($this->at(4))->method('installResource')->with($resource3, $params2);
        $args = self::$installCommand->parseArgs(new StringArgs('localhost'));
        $expected = <<<EOF
Installing /app/public into public_html via symlink...
Installing /acme/blog/public/css into public_html/blog/css via symlink...
Installing /acme/blog/public/js into public_html/blog/js via symlink...

EOF;
        $this->assertSame(0, $this->handler->handleInstall($args, $this->io));
        $this->assertSame($expected, $this->io->fetchOutput());
        $this->assertEmpty($this->io->fetchErrors());
    }
Beispiel #26
0
 /**
  * {@inheritdoc}
  */
 public function hasRootPathMappings(Expression $expr = null)
 {
     $expr2 = Expr::method('getContainingModule', Expr::same($this->rootModule));
     if ($expr) {
         $expr2 = $expr2->andX($expr);
     }
     return $this->hasPathMappings($expr2);
 }
 /**
  * {@inheritdoc}
  */
 public function hasRootBindings(Expression $expr = null)
 {
     $expr2 = Expr::same($this->rootPackage->getName(), BindingDescriptor::CONTAINING_PACKAGE);
     if ($expr) {
         $expr2 = $expr2->andX($expr);
     }
     return $this->hasBindings($expr2);
 }
 /**
  * {@inheritdoc}
  */
 public function leaveExpression(Expression $expr)
 {
     if ($expr instanceof Key) {
         switch ($expr->getKey()) {
             case AssetMapping::UUID:
                 return Expr::key(BindingDescriptor::UUID, $expr->getExpression());
             case AssetMapping::GLOB:
                 $queryExpr = $expr->getExpression();
                 if ($queryExpr instanceof Same) {
                     $queryExpr = Expr::same($queryExpr->getComparedValue() . '{,/**/*}');
                 } elseif ($queryExpr instanceof Equals) {
                     $queryExpr = Expr::equals($queryExpr->getComparedValue() . '{,/**/*}');
                 } elseif ($queryExpr instanceof NotSame) {
                     $queryExpr = Expr::notSame($queryExpr->getComparedValue() . '{,/**/*}');
                 } elseif ($queryExpr instanceof NotEquals) {
                     $queryExpr = Expr::notEquals($queryExpr->getComparedValue() . '{,/**/*}');
                 } elseif ($queryExpr instanceof EndsWith) {
                     $queryExpr = Expr::endsWith($queryExpr->getAcceptedSuffix() . '{,/**/*}');
                 }
                 return Expr::key(BindingDescriptor::QUERY, $queryExpr);
             case AssetMapping::SERVER_NAME:
                 return Expr::key(BindingDescriptor::PARAMETER_VALUES, Expr::key(DiscoveryUrlGenerator::SERVER_PARAMETER, $expr->getExpression()));
             case AssetMapping::SERVER_PATH:
                 return Expr::key(BindingDescriptor::PARAMETER_VALUES, Expr::key(DiscoveryUrlGenerator::PATH_PARAMETER, $expr->getExpression()));
         }
     }
     return $expr;
 }
Beispiel #29
0
 public function orKeyNotExists($keyName)
 {
     return $this->orX(Expr::keyNotExists($keyName));
 }
 private function webPath($path)
 {
     return $this->defaultExpr()->andKey(BindingDescriptor::PARAMETER_VALUES, Expr::key(DiscoveryUrlGenerator::PATH_PARAMETER, Expr::same($path)));
 }