/** * Covert File to HTML string */ function getString() { $input = new Generator(); $name = $this->getNameAttributeString(); $value = $this->getValue(); return $input->newInput('file', $name, $value, $this->getAttributes())->getString(); }
private function execute(\Generator $generator) { $stack = []; //This is basically a simple iterative in-order tree traversal algorithm $yielded = $generator->current(); //This is a depth-first traversal while ($yielded instanceof \Generator) { //... push it to the stack $stack[] = $generator; $generator = $yielded; $yielded = $generator->current(); } while (!empty($stack)) { //We've reached the end of the branch, let's step back on the stack $generator = array_pop($stack); //step the generator $yielded = $generator->send($yielded); //Depth-first traversal while ($yielded instanceof \Generator) { //... push it to the stack $stack[] = $generator; $generator = $yielded; $yielded = $generator->current(); } } return $yielded; }
/** * Create user with generated password. * * @param $username * * @return User */ public function createUserWithGeneratedPassword($username, $hashCost = 10, $salt = '') { $randomPassword = $this->generator->generateRandomPassword($this->minPasswordLength, $this->maxPasswordLength); $hashedPassword = $this->hashPassword($randomPassword, PASSWORD_DEFAULT, $hashCost, $salt); $user = new User($username, $randomPassword, $hashedPassword); return $user; }
/** * @param Generator $generator * @param $addPid */ public function __construct(Generator $generator, $addPid) { $this->requestId = $generator->getRequestId(); if ($addPid) { $this->pid = getmypid(); } }
public function testSetData() { /** * ['merchantID'] string This is the merchantID assigned by PayCo. * ['storeID'] string This is the store ID of a merchant. * ['logEnabled'] string Should logging be enabled * ['logLevel'] int Log level * ['logLocationMain'] string Main log Location * ['logLocationRequest'] string Log location for API requests * ['logLocationMNS'] string Log for MNS asynchronous callbacks * ['logLocationCallbacks'] string Log location for synchronous callbacks * ['defaultRiskClass'] string Default risk class */ $config = array('merchantID' => $this->faker->randomNumber(8), 'storeID' => $this->faker->word, 'logEnabled' => $this->faker->boolean, 'logLevel' => Config::LOG_LEVEL_ERROR, 'logLocationMain' => $this->faker->word, 'logLocationRequest' => $this->faker->word, 'logLocationMNS' => $this->faker->word, 'logLocationCallbacks' => $this->faker->word, 'defaultRiskClass' => 2, 'defaultLocale' => strtoupper($this->faker->languageCode)); $configObject = new Config(); $configObject->setData($config); $this->assertEquals($config['merchantID'], $configObject->getMerchantID(), "Merchant ID was set incorrectly"); $this->assertEquals($config['storeID'], $configObject->getStoreID(), "Store ID was set incorrectly"); $this->assertEquals($config['logEnabled'], $configObject->getLogEnabled(), "Log Enabled was set incorrectly"); $this->assertEquals($config['logLevel'], $configObject->getLogLevel(), "Log Level was set incorrectly"); $this->assertEquals($config['logLocationMain'], $configObject->getLogLocationMain(), "Main Log location was set incorrectly"); $this->assertEquals($config['logLocationRequest'], $configObject->getLogLocationRequest(), "Request Log location was set incorrectly"); $this->assertEquals($config['logLocationMNS'], $configObject->getLogLocationMNS(), "MNS Log location was set incorrectly"); $this->assertEquals($config['logLocationCallbacks'], $configObject->getLogLocationCallbacks(), "Callback Log location was set incorrectly"); $this->assertEquals($config['defaultRiskClass'], $configObject->getDefaultRiskClass(), "Default Risk was set incorrectly"); $this->assertEquals($config['defaultLocale'], $configObject->getDefaultLocale(), "Default was set incorrectly"); }
/** * @param string $className */ public function loadClass(string $className) { if ($filename = $this->generator->checkClass($className)) { includeFile($filename); return true; } }
public function generateSql() { $namespace = \Zule\Tools\Config::zc()->framework->application_namespace; $system = 'Zule'; $tables = $this->settings->getTables(); foreach ($tables as $table) { $s = new \Smarty(); $tableName = $table->getName(); // generate model $s->assign('model_name', $_POST["class_{$tableName}"]); $s->assign('namespace', $namespace); $s->assign('system', $system); $s->assign('class_name', $_POST["class_{$tableName}"]); $s->assign('extend_path', '\\Zule\\Models\\Model'); $s->assign('impl_date', date('Y-m-d H:i:s')); $s->assign('use_unsafe_setters', 0); $s->assign('table_name', $tableName); $columns = $table->getColumns(); $s->assign('columns', $columns); $s->assign('primary_key', $table->getPrimaryKey()); $gen = new Generator("../models/" . $_POST["class_{$tableName}"] . '.php'); $gen->generate($s, 'model_sql'); $gen = new Generator("../models/Data/" . $_POST["class_{$tableName}"] . '.php'); $gen->generate($s, 'gateway_sql'); } }
/** * Resolves yield calls tree * and gives a return value if outcome of yield is CoroutineReturnValue instance * * @param \Generator $coroutine nested coroutine tree * @return \Generator */ private static function stackedCoroutine(\Generator $coroutine) { $stack = new \SplStack(); while (true) { $value = $coroutine->current(); // nested generator/coroutine if ($value instanceof \Generator) { $stack->push($coroutine); $coroutine = $value; continue; } // coroutine end or value is a value object instance if (!$coroutine->valid() || $value instanceof CoroutineReturnValue) { // if till this point, there are no coroutines in a stack thatn stop here if ($stack->isEmpty()) { return; } $coroutine = $stack->pop(); $value = $value instanceof CoroutineReturnValue ? $value->getValue() : null; $coroutine->send($value); continue; } $coroutine->send((yield $coroutine->key() => $value)); } }
/** * Run ZMQ interface for generator * * Req-rep pattern; msgs are commands: * * GEN = Generate ID * STATUS = Get status string */ public function run() { $context = new \ZMQContext(); $receiver = new \ZMQSocket($context, \ZMQ::SOCKET_REP); $bindTo = 'tcp://*:' . $this->port; echo "Binding to {$bindTo}\n"; $receiver->bind($bindTo); while (TRUE) { $msg = $receiver->recv(); switch ($msg) { case 'GEN': try { $response = $this->generator->generate(); } catch (\Exception $e) { $response = "ERROR"; } break; case 'STATUS': $response = json_encode($this->generator->status()); break; default: $response = 'UNKNOWN COMMAND'; break; } $receiver->send($response); } }
public function test() { for ($i = 0; $i < 10; $i++) { $sentence = $this->faker->sentence(30); $encrypted = $this->encrypter->encryptToString($sentence); $planString = $this->encrypter->decryptFromString($encrypted); $this->assertEquals($sentence, $planString); } }
public function buildUser(Request $request, Generator $generator) { if (empty($request->userName)) { throw new \InvalidArgumentException(); } $password = $request->password ?: $generator->generatePassword(); $hashedPassword = md5(self::SALT . $password); return new User($request->userName, $password, $hashedPassword); }
/** * Generating UUID should return different results every time * * @covers Mixpanel\Uuid\Generator::generate * @covers Mixpanel\Uuid\Generator::ticksEntropy * @covers Mixpanel\Uuid\Generator::uaEntropy * @covers Mixpanel\Uuid\Generator::randomEntropy * @covers Mixpanel\Uuid\Generator::ipEntropy */ public function testGeneratingUuidShouldReturnDifferentResultEveryTime() { $uuids = array(); for ($i = 0; $i < 100; $i++) { $uuid = $this->generator->generate('user-agent', '127.0.0.1'); $this->assertNotContains($uuid, $uuids); $uuids[] = $uuid; } }
public static function create($locale = self::DEFAULT_LOCALE) { $generator = new Generator(); foreach (static::$defaultProviders as $provider) { $providerClassName = self::getProviderClassname($provider, $locale); $generator->addProvider(new $providerClassName($generator)); } return $generator; }
/** * [run 协程调度] * @param \Generator $gen * @throws \Exception */ public function run(\Generator $gen) { while (true) { try { /* 异常处理 */ if ($this->exception) { $gen->throw($this->exception); $this->exception = null; continue; } $value = $gen->current(); // Logger::write(__METHOD__ . " value === " . var_export($value, true), Logger::INFO); /* 中断内嵌 继续入栈 */ if ($value instanceof \Generator) { $this->corStack->push($gen); // Logger::write(__METHOD__ . " corStack push ", Logger::INFO); $gen = $value; continue; } /* if value is null and stack is not empty pop and send continue */ if (is_null($value) && !$this->corStack->isEmpty()) { // Logger::write(__METHOD__ . " values is null stack pop and send ", Logger::INFO); $gen = $this->corStack->pop(); $gen->send($this->callbackData); continue; } if ($value instanceof ReturnValue) { $gen = $this->corStack->pop(); $gen->send($value->getValue()); // end yeild // Logger::write(__METHOD__ . " yield end words == " . var_export($value, true), Logger::INFO); continue; } /* 中断内容为异步IO 发包 返回 */ if ($value instanceof \Swoole\Client\IBase) { //async send push gen to stack $this->corStack->push($gen); $value->send(array($this, 'callback')); return; } /* 出栈,回射数据 */ if ($this->corStack->isEmpty()) { return; } // Logger::write(__METHOD__ . " corStack pop ", Logger::INFO); $gen = $this->corStack->pop(); $gen->send($value); } catch (EasyWorkException $e) { if ($this->corStack->isEmpty()) { throw $e; } $gen = $this->corStack->pop(); $this->exception = $e; } } }
public function run() { if (!$this->generator) { throw new Exception(""); } elseif (!$this->closed) { throw new Exception(""); } $this->closed = false; $this->generator->rewind(); return $this->generator->current(); }
private function checkResult(\Generator $generator, Channel $channel) { if (!$generator->valid()) { foreach ($this->actions as list(, $gen, , $undo)) { if ($gen && $gen !== $generator) { $undo($gen->current()); } } return [$generator->getReturn(), $channel]; } return false; }
public function testPersonTestValidationDescription() { $hostedPagesText = new HostedPagesText(); $hostedPagesText->setPaymentMethodType(HostedPagesText::PAYMENT_METHOD_TYPE_CC)->setFee(500)->setDescription('')->setLocale(Codes::LOCALE_EN); $validation = new Validation(); $validation->getValidator($hostedPagesText); $data = $validation->performValidation(); $this->assertValidationReturned('Upg\\Library\\Request\\Objects\\HostedPagesText', 'description', 'Description is required', $data, "Description is required did not trigger"); $hostedPagesText->setDescription($this->faker->sentence(90)); $validation->getValidator($hostedPagesText); $data = $validation->performValidation(); $this->assertValidationReturned('Upg\\Library\\Request\\Objects\\HostedPagesText', 'description', 'Description must be no more than 255 characters long', $data, "Description must be no more than 255 characters long did not trigger"); }
/** * Creates accessor for instances of given class. * @param string $class * @return Accessor */ public function create($class) { $name = $this->naming->deriveClassName($class); $namespaced = $this->naming->getNamespace() . '\\' . $name; if (class_exists($namespaced) || $this->cache && $this->cache->load($name)) { return new $namespaced(); } $definition = $this->generator->generate($class); if ($this->cache) { $this->cache->save($name, $definition); } eval($definition); return new $namespaced(); }
/** * executes the current middleware * * @param ServerRequestInterface $request * @param ResponseInterface $response * @return ResponseInterface */ private function call(ServerRequestInterface $request, ResponseInterface $response) { if ($this->atStart) { $middleware = $this->generator->current(); $this->atStart = false; } else { $middleware = $this->generator->send(null); } if (!$middleware) { return $response; } $callable = $this->app->getMiddlewareCallable($middleware); return call_user_func($callable, $request, $response, $this->next); }
/** * When you need to return Result from your function, and it also depends on another * functions returning Results, you can make it a generator function and yield * values from dependant functions, this pattern makes code less bloated with * statements like this: * $res = something(); * if ($res instanceof Ok) { * $something = $res->unwrap(); * } else { * return $res; * } * * Instead you can write: * $something = (yield something()); * * @see /example.php * * @param \Generator $resultsGenerator Generator that produces Result instances * @return Result */ public static function reduce(\Generator $resultsGenerator) { /** @var Result $result */ $result = $resultsGenerator->current(); while ($resultsGenerator->valid()) { if ($result instanceof Err) { return $result; } $tmpResult = $resultsGenerator->send($result->unwrap()); if ($resultsGenerator->valid()) { $result = $tmpResult; } } return $result; }
/** * @param \Generator $generator * @param string $prefix */ public function __construct(\Generator $generator, string $prefix) { $yielded = $generator->current(); $prefix .= \sprintf("; %s yielded at key %s", \is_object($yielded) ? \get_class($yielded) : \gettype($yielded), $generator->key()); if (!$generator->valid()) { parent::__construct($prefix); return; } $reflGen = new \ReflectionGenerator($generator); $exeGen = $reflGen->getExecutingGenerator(); if ($isSubgenerator = $exeGen !== $generator) { $reflGen = new \ReflectionGenerator($exeGen); } parent::__construct(\sprintf("%s on line %s in %s", $prefix, $reflGen->getExecutingLine(), $reflGen->getExecutingFile())); }
/** * Store url to db * * @param $url */ protected function save($url) { $shortLink = Generator::getRandomString(); $item = array('created' => new \MongoDate(), 'key' => $shortLink, 'target' => $url); $this->getCollection(self::MONGO_COLLECTION)->insert($item); $this->set("link", 'http://' . $_SERVER['SERVER_NAME'] . '/' . $shortLink); }
/** * Get array replacements. * * @return array */ public function getReplacements() { $modelGenerator = new ModelGenerator(['name' => $this->name]); $model = $modelGenerator->getRootNamespace() . '\\' . $modelGenerator->getName(); $model = str_replace(["\\", '/'], '\\', $model); return array_merge(parent::getReplacements(), ['model' => $model]); }
public static function uniqueRid() { do { $rid = Generator::rid(); } while (Db::isRidExist($rid)); return $rid; }
/** * Ensure generator is creating string with the correct length */ public function testLengthGenerator() { $lengthDefault = Generator::getRandomString(); $lengthTwenty = Generator::getRandomString(20); $this->assertEquals(10, strlen($lengthDefault)); $this->assertEquals(20, strlen($lengthTwenty)); }
/** * Generador de Reportes * * @category Kumbia * @package Report * @copyright Copyright (c) 2005-2007 Andres Felipe Gutierrez (andresfelipe at vagoogle.net) * @license http://www.kumbia.org/license.txt GNU/GPL * */ function htm($result, $sumArray, $title, $weighArray, $headerArray) { $config = Config::read('config'); $active_app = Router::get_application(); $file = md5(uniqid()); $content = "\n<html>\n <head>\n <title>REPORTE DE " . strtoupper($title) . "</title>\n </head>\n <body bgcolor='white'>\n <div style='font-size:20px;font-family:Verdana;color:#000000'>" . strtoupper($config->{$active_app}->name) . "</div>\n\n <div style='font-size:18px;font-family:Verdana;color:#000000'>REPORTE DE " . strtoupper($title) . "</div>\n\n <div style='font-size:18px;font-family:Verdana;color:#000000'>" . date("Y-m-d") . "</div>\n\n <br/>\n <table cellspacing='0' border=1 style='border:1px solid #969696'>\n "; $content .= "<tr bgcolor='#F2F2F2'>\n"; for ($i = 0; $i <= count($headerArray) - 1; $i++) { $content .= "<th style='font-family:Verdana;font-size:12px'>" . $headerArray[$i] . "</th>\n"; } $content .= "</tr>\n"; $l = 5; foreach ($result as $row) { $content .= "<tr bgcolor='white'>\n"; for ($i = 0; $i <= count($row) - 1; $i++) { if (is_numeric($row[$i])) { $content .= "<td style='font-family:Verdana;font-size:12px' align='center'>{$row[$i]}</td>"; } else { $content .= "<td style='font-family:Verdana;font-size:12px'>{$row[$i]} </td>"; } } $content .= "</tr>\n"; $l++; } file_put_contents("public/temp/{$file}.html", $content); if (isset($raw_output)) { print "<script type='text/javascript'> window.open('" . KUMBIA_PATH . "temp/" . $file . ".html', null); </script>"; } else { Generator::forms_print("<script type='text/javascript'> window.open('" . KUMBIA_PATH . "temp/" . $file . ".html', null); </script>"); } }
/** * Generates XML code * @throws FeedGeneratorException */ public function generate() { if (!$this->_generator instanceof Generator) { throw new FeedGeneratorException('There has been no generator strategy set.'); } $this->generated = $this->_generator->generate($this->_channel); }
public function __construct(ReportInterface $reportIfc, $repositoryName, $entityName, $service) { parent::__construct($reportIfc); $this->repositoryName = $repositoryName; $this->entityName = $entityName; $this->service = $service; }
/** * Implements the loading of the class object * @throws Exception if the class is already generated(not null) */ protected function generateClass() { if ($this->class != null) { throw new Exception("The class has already been generated"); } $config = Generator::getInstance()->getConfig(); $this->class = new PhpClass($this->phpIdentifier, $config->getClassExists()); $first = true; foreach ($this->values as $value) { try { $name = Validator::validateNamingConvention($value); } catch (ValidationException $e) { $name = 'constant' . $name; } try { $name = Validator::validateType($name); } catch (ValidationException $e) { $name .= 'Custom'; } if ($first) { $this->class->addConstant($name, '__default'); $first = false; } $this->class->addConstant($value, $name); } }
/** * Examines the value yielded from the generator and prepares the next step in interation. * * @param mixed $yielded */ private function next($yielded) { if (!$this->generator->valid()) { $result = $this->generator->getReturn(); if ($result instanceof Awaitable) { $this->reject(new AwaitableReturnedError($result)); return; } if ($result instanceof Generator) { $this->reject(new GeneratorReturnedError($result)); return; } $this->resolve($result); return; } $this->busy = true; if ($yielded instanceof Generator) { $yielded = new self($yielded); } $this->current = $yielded; if ($yielded instanceof Awaitable) { $yielded->done($this->send, $this->capture); } else { Loop\queue($this->send, $yielded); } $this->busy = false; }