PHP Closure Code Examples

This page contains top rated real world PHP examples of Closure extracted from open source projects. You can rate examples to help us improve the quality of examples
Example #1
Show file File: ServiceLocatorService.php Project: roman-kulish/newscorp-servicelocator
0
 /**
  * Get service instance
  *
  * @param ServiceLocatorInterface $serviceLocator Service Locator instance
  * @return mixed
  */
 public function getServiceInstance(ServiceLocatorInterface $serviceLocator)
 {
     if ($this->instance === null) {
         /**
          * Instance must be created using factory
          */
         if ($this->factory instanceof \Closure) {
             $instance = call_user_func($this->factory, $serviceLocator);
         } else {
             $instance = $this->factory->factory($serviceLocator);
         }
         if (!$this->isShared()) {
             return $instance;
             // new instance must be returned
         } else {
             $this->instance = $instance;
             // cache instance
             return $this->instance;
             // same instance must be returned
         }
     } else {
         /**
          * Instance either was passed directly or has been created earlier
          */
         if (!$this->isShared()) {
             return $this->instance;
             // new instance must be returned
         } else {
             return clone $this->instance;
             // same instance must be returned
         }
     }
 }
Example #2
Show file File: ImageValidatorTest.php Project: esperecyan/dictionary-php
0
 /**
  * @param string $type
  * @param \Closure $generateImage
  * @param \Closure $checkOutput
  * @param array $logLevels
  * @dataProvider imageProvider
  */
 public function testCorrect(string $type, \Closure $generateImage, \Closure $checkOutput, array $logLevels = [])
 {
     $validator = new ImageValidator($type, '');
     $validator->setLogger($this);
     $checkOutput->call($this, $validator->correct($generateImage()));
     $this->assertEquals($logLevels, $this->logLevels);
 }
Example #3
Show file File: websocket.php Project: cyan-framework/library
0
 public function on($event, \Closure $callback)
 {
     if (is_string($event)) {
         $this->events[$event] = $callback->bindTo($this, $this);
     }
     return $this;
 }
Example #4
Show file File: BinaryClosure.php Project: peekandpoke/psi
0
 /**
  * {@inheritdoc}
  */
 public function __invoke($input, $index)
 {
     /** @noinspection PhpMethodParametersCountMismatchInspection */
     /** @noinspection PhpMethodParametersCountMismatchInspection */
     /** @noinspection PhpVoidFunctionResultUsedInspection */
     return $this->function->__invoke($input, $index);
 }
Example #5
Show file File: Entity.php Project: elfchat/elfchat
0
 public static final function entityManager()
 {
     if (self::$entityManager === null) {
         self::$entityManager = self::$entityManagerFactory->__invoke();
     }
     return self::$entityManager;
 }
Example #6
Show file File: ClosureDynamicProceedTrait.php Project: williamamed/Raptor2
0
 /**
  * Invokes original method and return result from it
  *
  * @return mixed
  */
 public function proceed()
 {
     if (isset($this->advices[$this->current])) {
         /** @var $currentInterceptor \Go\Aop\Intercept\Interceptor */
         $currentInterceptor = $this->advices[$this->current++];
         return $currentInterceptor->invoke($this);
     }
     // Fill the closure only once if it's empty
     if (!$this->closureToCall) {
         $this->closureToCall = $this->reflectionMethod->getClosure($this->instance);
     }
     // Rebind the closure if instance was changed since last time
     if ($this->previousInstance !== $this->instance) {
         $this->closureToCall = $this->closureToCall->bindTo($this->instance, $this->reflectionMethod->class);
         $this->previousInstance = $this->instance;
     }
     $closureToCall = $this->closureToCall;
     $args = $this->arguments;
     switch (count($args)) {
         case 0:
             return $closureToCall();
         case 1:
             return $closureToCall($args[0]);
         case 2:
             return $closureToCall($args[0], $args[1]);
         case 3:
             return $closureToCall($args[0], $args[1], $args[2]);
         case 4:
             return $closureToCall($args[0], $args[1], $args[2], $args[3]);
         case 5:
             return $closureToCall($args[0], $args[1], $args[2], $args[3], $args[4]);
         default:
             return forward_static_call_array($closureToCall, $args);
     }
 }
Example #7
Show file File: Key.php Project: jimbojsb/cacheback
0
 public function get()
 {
     if (!$this->closure instanceof \Closure) {
         throw new \RuntimeException("Cannot get a key with an undefined closure");
     }
     if ($this->enabled) {
         $data = $this->predis->get($this->getKeyName($this->key));
     }
     if ($data === null) {
         $boundCallback = $this->closure->bindTo($this);
         $data = $boundCallback();
         if ($this->enabled) {
             $this->predis->setex($this->getKeyName($this->key), $this->ttl, serialize($data));
         }
         if ($this->onMiss instanceof \Closure) {
             call_user_func_array($this->onMiss, [$this, $data]);
         }
         return $data;
     } else {
         $value = unserialize($data);
         if ($this->onHit instanceof \Closure) {
             call_user_func_array($this->onHit, [$this, $value]);
         }
         return $value;
     }
 }
Example #8
Show file File: LazyOption.php Project: laubosslink/lab
0
 /**
  * Evaluates the underyling closure and returns its result.
  *
  * The given Options instance is passed to the closure as first argument.
  * The previous default value set in the constructor is passed as second
  * argument.
  *
  * @param Options $options The container with all concrete options.
  *
  * @return mixed The result of the closure.
  */
 public function evaluate(Options $options)
 {
     if ($this->previousValue instanceof self) {
         $this->previousValue = $this->previousValue->evaluate($options);
     }
     return $this->closure->__invoke($options, $this->previousValue);
 }
Example #9
Show file File: Spec.php Project: gsouf/pho
0
 /**
  * Constructs a Spec, to be associated with a particular suite, and ran
  * by the test runner. The closure is bound to the suite.
  *
  * @param string   $title   A title to be associated with the spec
  * @param \Closure $closure The closure to invoke when the spec is called
  * @param Suite    $suite   The suite within which this spec was defined
  */
 public function __construct($title, \Closure $closure = null, Suite $suite)
 {
     $this->title = $title;
     $this->suite = $suite;
     if ($closure) {
         $this->closure = $closure->bindTo($suite);
     }
 }
Example #10
Show file File: phpunit.php Project: serendip811/patio42
0
function myCapture(Closure $closure)
{
    ob_start();
    $closure->__invoke();
    $contents = ob_get_contents();
    ob_end_clean();
    return $contents;
}
Example #11
Show file File: GenericCallback.php Project: dlundgren/watchtower
0
 /**
  * Handles the event
  *
  * @param Event $event
  * @return mixed|void
  */
 public function discern(Event $event)
 {
     if ($this->eventInstance && !$event instanceof $this->eventInstance) {
         return;
     }
     $callback = $this->callback->bindTo($this, $this);
     $callback($event);
 }
Example #12
Show file File: Session.php Project: jacksleight/coast
0
 public function fingerprint(\Closure $fingerprint = null)
 {
     if (func_num_args() > 0) {
         $this->_fingerprint = $fingerprint->bindTo($this);
         return $this;
     }
     return $this->_fingerprint;
 }
Example #13
Show file File: Router.php Project: domynation/domynation-framework
0
 /**
  * Registers a route.
  *
  * @param  string $name
  * @param  \Closure $handler
  *
  * @return Route
  */
 public function add($name, \Closure $handler)
 {
     // Bind the handler to the Router class
     $route = new Route($name, $handler->bindTo($this, $this));
     // Insert the route
     $this->routes[$name] = $route;
     return $route;
 }
Example #14
Show file File: DependencyProxy.php Project: robertlemke/flow-development-collection
0
 /**
  * Activate the dependency and set it in the object.
  *
  * @return object The real dependency object
  * @api
  */
 public function _activateDependency()
 {
     $realDependency = $this->builder->__invoke();
     foreach ($this->propertyVariables as &$propertyVariable) {
         $propertyVariable = $realDependency;
     }
     return $realDependency;
 }
Example #15
Show file File: Router.php Project: pkdevboxy/tez
0
 /**
  * @param string $prefix
  * @param \Closure $closure
  */
 public function group($prefix, \Closure $closure)
 {
     $original = $this->prefix;
     $this->prefix = sprintf('/%s/%s', trim($original, '/'), trim($prefix, '/'));
     $callback = $closure->bindTo($this);
     $callback();
     $this->prefix = $original;
 }
Example #16
Show file File: RunnableSpec.php Project: ciarand/pho
0
 public function __construct(\Closure $closure, Suite $suite)
 {
     $this->suite = $suite;
     if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
         $this->closure = $closure->bindTo($suite);
     } else {
         $this->closure = $closure;
     }
 }
Example #17
Show file File: Context.php Project: warmans/pipeline
0
 /**
  * @param string $msg
  * @param bool $writeln
  */
 public function log($msg, $writeln = true)
 {
     $prefixed = '';
     foreach ($this->logPrefixes as $prefix) {
         $prefixed .= $prefixed ? ' ' . $prefix : $prefix;
     }
     $msg = $prefixed ? $prefixed . ' ' . $msg : $msg;
     $this->logger->__invoke($msg, $writeln);
 }
Example #18
Show file File: Cache.php Project: raymondjavaxx/roxphp
0
 /**
  * Retrieves data by key or executes $callback in case of cache miss. Data returned
  * by $callback is then cached.
  *
  *     \rox\Cache::fetch('my_key', '+1 hour', function(){
  *         // some expensive operation
  *         return $results;
  *     });
  *
  * @param string $key 
  * @param string $expires expiration time in seconds or strtotime() compatible string
  * @param \Closure $callback closure to be executed on cache miss
  * @return mixed
  */
 public static function fetch($key, $expires, \Closure $callback)
 {
     $data = static::read($key);
     if ($data === false) {
         $data = $callback->__invoke();
         static::write($key, $data, $expires);
     }
     return $data;
 }
Example #19
Show file File: AuthorizationService.php Project: coolms/acl
0
 /**
  * {@inheritDoc}
  */
 public function isAllowed($resource, $privilege = null, $role = null)
 {
     $this->loaded && $this->loaded->__invoke();
     try {
         return $this->acl->isAllowed($role ?: $this->identity, $resource, $privilege);
     } catch (InvalidArgumentException $e) {
         return false;
     }
 }
Example #20
Show file File: Handler.php Project: new-inventor/form
0
 /**
  * @inheritdoc
  */
 public function process()
 {
     if ($this->processType == self::PROCESS_TYPE_CLOSURE) {
         return $this->process->__invoke($this->getParent());
     } elseif ($this->processType == self::PROCESS_TYPE_CALLABLE) {
         return call_user_func($this->process, $this->getParent());
     }
     return true;
 }
Example #21
Show file File: AbstractLegacySlot.php Project: CG77/ezpublish-kernel
0
 /**
  * Executes a legacy kernel callback
  *
  * Does the callback with both post-reinitialize and formtoken checks disabled.
  *
  * @param callable $callback
  *
  * @return mixed
  */
 protected function runLegacyKernelCallback($callback)
 {
     // Initialize legacy kernel if not already done
     if ($this->legacyKernel instanceof Closure) {
         $legacyKernelClosure = $this->legacyKernel;
         $this->legacyKernel = $legacyKernelClosure();
     }
     return $this->legacyKernel->runCallback($callback, false, false);
 }
Example #22
Show file File: ValidatesUserTest.php Project: salpakan/salpakan
0
 /**
  * Build where clause response.
  *
  * @param  Closure|bool  $expectation
  * @return mixed
  */
 private function mockFindUserResponse($expectation)
 {
     if (!$expectation instanceof Closure) {
         return $expectation;
     }
     $user = Mockery::mock(User::class);
     // Run the expectations for the returned user mock.
     $expectation->__invoke($user);
     return $user;
 }
Example #23
Show file File: AbstractAdvice.php Project: kszyma/flow-development-collection
0
 /**
  * Invokes the advice method
  *
  * @param \TYPO3\Flow\Aop\JoinPointInterface $joinPoint The current join point which is passed to the advice method
  * @return mixed Result of the advice method
  */
 public function invoke(\TYPO3\Flow\Aop\JoinPointInterface $joinPoint)
 {
     if ($this->runtimeEvaluator !== null && $this->runtimeEvaluator->__invoke($joinPoint, $this->objectManager) === false) {
         return;
     }
     $adviceObject = $this->objectManager->get($this->aspectObjectName);
     $methodName = $this->adviceMethodName;
     $adviceObject->{$methodName}($joinPoint);
     $this->emitAdviceInvoked($adviceObject, $methodName, $joinPoint);
 }
Example #24
Show file File: ValidatorChain.php Project: bradley-holt/zf2
0
 /**
  * Attach a handler to the session validator chain
  * 
  * @param  string $topic 
  * @param  string|object|Closure $context 
  * @param  null|string $handler 
  * @return Zend\Stdlib\SignalHandler
  */
 public function connect($topic, $context, $handler = null)
 {
     if ($context instanceof Validator) {
         $data = $context->getData();
         $name = $context->getName();
         $this->getStorage()->setMetadata('_VALID', array($name => $data));
     }
     $handle = parent::connect($topic, $context, $handler);
     return $handle;
 }
Example #25
Show file File: ClosureTest.php Project: ruian/KnpBundles
0
 public function testRepoIsPassedToTheClosureAsFirstParameter()
 {
     $repo = $this->getRepo('foobar');
     $self = $this;
     $criterion = new Closure(function ($param) use($repo, $self) {
         $self->assertEquals($repo, $param);
         return $param === $repo;
     });
     $this->assertTrue($criterion->matches($repo));
 }
Example #26
Show file File: CalendarEventList.php Project: thijsw/ics-large
0
 public function valid()
 {
     if (count($this->batch) < 1) {
         $this->batch = $this->provider->__invoke($this->key, $this->batch_size);
         if ($this->batch && $this->batch instanceof \Traversable) {
             $this->batch = iterator_to_array($this->batch);
         }
     }
     return count($this->batch) > 0;
 }
Example #27
Show file File: Suite.php Project: gsouf/pho
0
 /**
  * Constructs a test suite, which may contain nested suites and specs. The
  * anonymous function passed to the constructor contains the body of the
  * suite to be ran, and it is bound to the suite.
  *
  * @param string   $title   A title to be associated with the suite
  * @param \Closure $closure The closure to invoke when the suite is ran
  * @param Suite    $parent  An optional parent suite
  */
 public function __construct($title, \Closure $closure, Suite $parent = null)
 {
     $this->title = $title;
     $this->closure = $closure->bindTo($this);
     $this->specs = [];
     $this->suites = [];
     $this->store = [];
     $this->parent = $parent;
     $this->pending = false;
 }
Example #28
Show file File: ClosureCommand.php Project: narrowspark/framework
0
 /**
  * Execute the console command.
  *
  * @param \Symfony\Component\Console\Input\InputInterface   $input
  * @param \Symfony\Component\Console\Output\OutputInterface $output
  *
  * @return mixed
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $inputs = array_merge($input->getArguments(), $input->getOptions());
     $parameters = [];
     foreach ((new ReflectionFunction($this->callback))->getParameters() as $parameter) {
         if (isset($inputs[$parameter->name])) {
             $parameters[$parameter->name] = $inputs[$parameter->name];
         }
     }
     return $this->getInvoker()->call($this->callback->bindTo($this, $this), $parameters);
 }
Example #29
Show file File: Spec.php Project: ciarand/pho
0
 /**
  * Constructs a Spec, to be associated with a particular suite, and ran
  * by the test runner. The closure is bound to the suite.
  *
  * @param string   $title   A title to be associated with the spec
  * @param \Closure $closure The closure to invoke when the spec is called
  * @param Suite    $suite   The suite within which this spec was defined
  */
 public function __construct($title, \Closure $closure = null, Suite $suite)
 {
     $this->title = $title;
     $this->suite = $suite;
     if ($closure && version_compare(PHP_VERSION, '5.4.0', '>=')) {
         $this->closure = $closure->bindTo($suite);
     } else {
         if ($closure) {
             $this->closure = $closure;
         }
     }
 }
Example #30
Show file File: AbstractValidator.php Project: new-inventor/form
0
 /** @inheritdoc */
 public function isValid($value)
 {
     $this->lastValidated = $value;
     try {
         if (isset($this->customValidateMethod)) {
             $this->customValidateMethod->__invoke($this->objectName, $value);
         }
         return $this->validateValue($value);
     } catch (\Exception $e) {
         $this->error = $e->getMessage();
         return false;
     }
 }