Created
October 29, 2018 16:06
-
-
Save bbars/aa0bb2402d1919bb1833f71a3302041c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php // I don't know why anybody may need it | |
class Promise { | |
protected $resolvers = []; | |
protected $catchers = []; | |
protected $value = null; | |
protected $error = null; | |
protected $status = 'idle'; | |
public function __construct($run, $manualStart = false) { | |
try { | |
$this->status = 'pending'; | |
$run([$this, 'resolve'], [$this, 'reject']); | |
} | |
catch (\Exception $e) { | |
$this->reject($e); | |
} | |
} | |
public function resolve($value) { | |
try { | |
if (is_a($value, __CLASS__)) { | |
if ($value->status === 'rejected') { | |
$this->reject($value->value); | |
} | |
else if ($value->status === 'resolved') { | |
$this->resolve($value->value); | |
} | |
else { | |
$value->then([$this, 'resolve'], [$this, 'reject']); | |
} | |
return $this; | |
} | |
$this->value = $value; | |
$this->status = 'resolved'; | |
$resolver = array_shift($this->resolvers); | |
if ($resolver) { | |
$value = $resolver($this->value); | |
$this->resolve($value); | |
} | |
} | |
catch (\Exception $e) { | |
$this->reject($e); | |
} | |
return $this; | |
} | |
public function reject($error) { | |
$catcher = array_shift($this->catchers); | |
if (!$catcher) | |
throw $error; | |
try { | |
$this->status = 'rejected'; | |
$value = $catcher($error); | |
if (is_a($value, __CLASS__)) { | |
return $value->then([$this, 'resolve'], [$this, 'reject']); | |
} | |
else { | |
return $this->resolve($value); | |
} | |
} | |
catch (\Exception $e) { | |
$this->reject($e); | |
} | |
return $this; | |
} | |
public function check() { | |
if ($this->status === 'resolved') { | |
$this->resolve($this->value); | |
return true; | |
} | |
else if ($this->status === 'rejected') { | |
$this->reject($this->error); | |
return true; | |
} | |
return false; | |
} | |
public function then($resolver, $catcher = null) { | |
$this->resolvers[] = $resolver; | |
if ($catcher) { | |
$this->catchers[] = $catcher; | |
} | |
$this->check(); | |
return $this; | |
} | |
public function catch($catcher) { | |
$this->catchers[] = $catcher; | |
$this->check(); | |
return $this; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment