Example #1
0
 public function last()
 {
     if (empty($this->elements)) {
         return None::create();
     }
     return new Some(end($this->elements));
 }
Example #2
0
 /**
  * Get "fields" value
  *
  * @return \PhpOption\Option of type RpbPair[]
  */
 public function getFields($idx = null)
 {
     if (null == $idx || !array_key_exists($idx, $this->fields)) {
         return \PhpOption\None::create();
     }
     return new \PhpOption\Some($this->fields[$idx]);
 }
 /**
  * Returns the value of the node if it is static, and the node has a value.
  *
  * @param \PHPParser_Node $node
  *
  * @return Option<string>
  */
 public static function getValue(\PHPParser_Node $node = null)
 {
     if ($node instanceof \PHPParser_Node_Scalar_String) {
         return new Some($node->value);
     }
     if ($node instanceof \PHPParser_Node_Scalar_LNumber) {
         return new Some($node->value);
     }
     if ($node instanceof \PHPParser_Node_Scalar_DNumber) {
         return new Some($node->value);
     }
     if ($node instanceof \PHPParser_Node_Expr_UnaryMinus) {
         return self::getValue($node->expr)->map(function ($v) {
             return $v * -1;
         });
     }
     if ($node instanceof \PHPParser_Node_Expr_UnaryPlus) {
         return self::getValue($node->expr);
     }
     if ($node instanceof \PHPParser_Node_Expr_ConstFetch) {
         switch (strtolower(implode("\\", $node->name->parts))) {
             case 'false':
                 return new Some(false);
             case 'true':
                 return new Some(true);
             case 'null':
                 return new Some(null);
         }
     }
     return None::create();
 }
Example #4
0
 /**
  * Get "content" value
  *
  * @return \PhpOption\Option of type RpbContent[]
  */
 public function getContent($idx = null)
 {
     if (null == $idx || !array_key_exists($idx, $this->content)) {
         return \PhpOption\None::create();
     }
     return new \PhpOption\Some($this->content[$idx]);
 }
 public function getItemType($key)
 {
     if (isset($this->itemTypes[$key])) {
         return new \PhpOption\Some($this->itemTypes[$key]);
     }
     return \PhpOption\None::create();
 }
Example #6
0
 /**
  * @param string $name
  * @return Option
  */
 protected function getConditionByName($name)
 {
     if (isset($this->conditions[$name])) {
         return new Some($this->conditions[$name]);
     }
     return None::create();
 }
Example #7
0
 public function findMaybe($success)
 {
     if ($success) {
         return new \PhpOption\Some(new \stdClass());
     }
     return \PhpOption\None::create();
 }
 /**
  * Creates appropriate option object
  *
  * @param $entity
  * @return PhpOption\Option
  */
 protected function createOption($entity)
 {
     if ($entity === null) {
         return PhpOption\None::create();
     }
     return PhpOption\Some::create($entity);
 }
 /**
  * @param string $id
  * @param string $key
  *
  * @return \PhpOption\Option
  */
 public function getRegistrationByIdAndKey($id, $key)
 {
     $qb = $this->createQueryBuilder('r');
     $qb->andWhere('r.id = :id')->setParameter('id', $id);
     $qb->andWhere('r.confirmationKey = :key')->setParameter('key', $key);
     $subscription = $qb->getQuery()->getOneOrNullResult();
     return $subscription === null ? None::create() : new Some($subscription);
 }
 public function getMatchers()
 {
     return ['beAnEmptyOption' => function ($subject) {
         return $subject === None::create();
     }, 'beAnOptionOf' => function ($subject, $value) {
         return is_object($subject) && $subject instanceof Some && $subject->get() === $value;
     }];
 }
Example #11
0
 public function find($class, $id)
 {
     try {
         $events = $this->store->findBy($class, $id);
         return new PhpOption\Some($this->player->replay($events, $class));
     } catch (NoResult $e) {
         return PhpOption\None::create();
     }
 }
Example #12
0
 /**
  * Creates a lazy-option with the given callback.
  *
  * This is also a helper constructor for lazy-consuming existing APIs where
  * the return value is not yet an option. By default, we treat ``null`` as
  * None case, and everything else as Some.
  *
  * @param callable $callback The callback to evaluate.
  * @param array $arguments
  * @param mixed $noneValue The value which should be considered "None"; null
  *                         by default.
  *
  * @return Option
  */
 public static function fromReturn($callback, array $arguments = array(), $noneValue = null)
 {
     return new LazyOption(function () use($callback, $arguments, $noneValue) {
         $return = call_user_func_array($callback, $arguments);
         if ($return === $noneValue) {
             return None::create();
         }
         return new Some($return);
     });
 }
 /**
  * @return Option
  */
 public function getNextEvent()
 {
     $qb = $this->createQueryBuilder('e');
     $qb->andWhere('e.registrationStart <= :now');
     $qb->setParameter('now', new \DateTime());
     $qb->setMaxResults(1);
     $qb->orderBy('e.start', 'ASC');
     $event = $qb->getQuery()->getOneOrNullResult();
     return $event == null ? None::create() : new Some($event);
 }
 /**
  * @param array $cases
  * @param array $arguments
  *
  * @return Option
  */
 protected function doMatch(array $cases, array $arguments)
 {
     foreach ($cases as $case) {
         list($matcher, $action) = $case;
         if (call_user_func_array($matcher, $arguments)) {
             return new Some(call_user_func_array($action, $arguments));
         }
     }
     return None::create();
 }
Example #15
0
 /**
  * Flexible getter
  *
  * ```php
  * // Get value or throw
  * $data->attribute('key.sub')->get();
  * // Get value or throw custom exception
  * $data->attribute('m.s.k')->getOrThrow(new \LogicException('does not exists'));
  * // Or call some closure
  * $data->attribute('my.sub.key')->getOrCall(function() { return 'fallBackValue';});
  * // Or use default value
  * $data->attribute('my.sub.key')->getOrElse(2);
  * // Check if it exists
  * $data->attribute('m.s.k')->isDefined();
  * // Value is an array convert to observable
  * $data->attribute('my.array')
  *  ->map([Observable, 'fromArray')
  *  ->get()
  *  ->subscribeCallback(...);
  * ```
  *
  * @see https://github.com/schmittjoh/php-option
  * @param string $key
  * @return None|Option
  */
 public function attribute($key)
 {
     $object = $this->payload;
     foreach (explode('.', $key) as $segment) {
         if (!is_object($object) || !isset($object->{$segment})) {
             return None::create();
         }
         $object = $object->{$segment};
     }
     return Option::fromValue($object);
 }
Example #16
0
 public function testOrElseWithMultipleAlternatives()
 {
     $throws = new \PhpOption\LazyOption(function () {
         throw new \LogicException('Should never be called.');
     });
     $returns = new \PhpOption\LazyOption(function () {
         return new \PhpOption\Some('foo');
     });
     $a = \PhpOption\None::create();
     $this->assertEquals('foo', $a->orElse($returns)->orElse($throws)->get());
 }
 public function find(callable $callable)
 {
     $self = $this;
     return new LazyOption(function () use($callable, $self) {
         foreach ($self as $elem) {
             if (call_user_func($callable, $elem) === true) {
                 return new Some($elem);
             }
         }
         return None::create();
     });
 }
Example #18
0
 public function testOptionReturnedFromClosure()
 {
     $option = $this->ensure(function () {
         return Some::create(1);
     });
     $this->assertTrue($option->isDefined());
     $this->assertSame(1, $option->get());
     $option = $this->ensure(function () {
         return None::create();
     });
     $this->assertFalse($option->isDefined());
 }
 protected function processEntityConfig(array $entity)
 {
     $processedEntity = [];
     if (isset($entity['properties'])) {
         $properties = $entity['properties'];
         $processedProperties = [];
         foreach ($properties as $name => $property) {
             $processedProperties[$name] = Some::create(['candidates' => Some::fromArraysValue($property, 'candidates'), 'key' => Some::fromArraysValue($property, 'key'), 'mandatory' => Some::fromArraysValue($property, 'mandatory'), 'persistent' => Some::fromArraysValue($property, 'persistent'), 'validators' => Some::fromArraysValue($property, 'validators'), 'converters' => Some::fromArraysValue($property, 'converters'), 'filters' => Some::fromArraysValue($property, 'filters')]);
         }
         $processedEntity['properties'] = Some::create($processedProperties);
     } else {
         $processedEntity['properties'] = None::create();
     }
     $processedEntity['decorators'] = Some::fromArraysValue($entity, 'decorators');
     $processedEntity['filters'] = Some::fromArraysValue($entity, 'filters');
     $processedEntity['validators'] = Some::fromArraysValue($entity, 'validators');
     return $processedEntity;
 }
Example #20
0
 /**
  * Implements {@link Pipeable::reduceOption}.
  * @param callable $binaryFunction
  * @param mixed $initial
  * @return Option
  */
 public function reduceOption(callable $binaryFunction, $initial = null)
 {
     if (func_num_args() == 1) {
         if ($this->isEmpty()) {
             return None::create();
         } else {
             return Some::create($this->reduce($binaryFunction));
         }
     } else {
         return Some::create($this->reduce($binaryFunction, $initial));
     }
 }
Example #21
0
 public function testFlatten()
 {
     $seq = new Sequence();
     $seq->addAll([new Some('a'), new Some('b'), None::create(), new Some('c')]);
     $this->assertEquals(['a', 'b', 'c'], iterator_to_array($seq->flatten()));
     $seq = new Sequence();
     $seq->addAll([[1, 2, 3, 4], [5, 6], [7]]);
     $this->assertEquals([1, 2, 3, 4, 5, 6, 7], iterator_to_array($seq->flatten()));
 }
Example #22
0
 /**
  * Get "map_value" value
  *
  * @return \PhpOption\Option of type MapEntry[]
  */
 public function getMapValue($idx = null)
 {
     if (null == $idx || !array_key_exists($idx, $this->map_value)) {
         return \PhpOption\None::create();
     }
     return new \PhpOption\Some($this->map_value[$idx]);
 }
Example #23
0
 /**
  * Checks TestScribe (test generator) to determine whether the real or mock class is required.
  * If a mock class is needed, it is returned by this method (wrapped in Some), otherwise None is returned.
  * @param $className
  * @param $arguments
  * @return Option
  */
 private static function checkTestScribe($className, $arguments)
 {
     /** @noinspection PhpUndefinedNamespaceInspection */
     /** @noinspection PhpUndefinedClassInspection */
     if (self::isTestGeneratorRun() && \Box\TestScribe\App::$shouldInjectMockObjects) {
         // This code block is to support PHPUnit test generator.
         // @see https://github.com/box/TestScribe
         // The class 'Box\TestScribe\App' should only be loaded
         // when this method is executed by the test generator.
         // It allows the test generator to substitute the real class instance with a
         // mock object controlled by the test generator so that the test
         // generator can monitor the creation and execution of the class
         // being resolved.
         /** @noinspection PhpUndefinedNamespaceInspection */
         return Option::fromValue(\Box\TestScribe\App::createMockedInstance($className, $arguments));
     }
     return None::create();
 }
Example #24
0
 protected function setUp()
 {
     $this->none = None::create();
 }
Example #25
0
 public function find($callable)
 {
     foreach ($this->elements as $k => $v) {
         if (call_user_func($callable, $k, $v) === true) {
             return new Some(array($k, $v));
         }
     }
     return None::create();
 }
Example #26
0
 public function testGetConditionByNameReturnsNoneOptionIfConditionDoesNotExist()
 {
     $this->assertEquals(None::create(), $this->object->getConditionByName(self::CONDITION_NAME));
 }
Example #27
0
 public function testOrElse()
 {
     $some = \PhpOption\Some::create('foo');
     $lazy = \PhpOption\LazyOption::create(function() use ($some) {return $some;});
     $this->assertSame($some, $lazy->orElse(\PhpOption\None::create()));
     $this->assertSame($some, $lazy->orElse(\PhpOption\Some::create('bar')));
 }
Example #28
0
 public function findFirst()
 {
     foreach ($this as $el) {
         return new Some($el);
     }
     return None::create();
 }
 public function first()
 {
     if (empty($this->elements)) {
         return None::create();
     }
     return new Some(reset($this->elements));
 }
Example #30
0
 public function getUser($name)
 {
     if (in_array($name, $this->users, true)) {
         return new Some(array('name' => $name));
     }
     return \PhpOption\None::create();
 }