repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6 values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1 value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
sonata-project/SonataNotificationBundle | src/Command/ListQueuesCommand.php | ListQueuesCommand.execute | public function execute(InputInterface $input, OutputInterface $output)
{
$backend = $this->getContainer()->get('sonata.notification.backend');
if (!$backend instanceof QueueDispatcherInterface) {
$output->writeln(
'The backend class <info>'.\get_class($backend).'</info> does not provide multiple queues.'
);
return;
}
$output->writeln('<info>List of queues available</info>');
foreach ($backend->getQueues() as $queue) {
$output->writeln(sprintf(
'queue: <info>%s</info> - routing_key: <info>%s</info>',
$queue['queue'],
$queue['routing_key']
));
}
} | php | public function execute(InputInterface $input, OutputInterface $output)
{
$backend = $this->getContainer()->get('sonata.notification.backend');
if (!$backend instanceof QueueDispatcherInterface) {
$output->writeln(
'The backend class <info>'.\get_class($backend).'</info> does not provide multiple queues.'
);
return;
}
$output->writeln('<info>List of queues available</info>');
foreach ($backend->getQueues() as $queue) {
$output->writeln(sprintf(
'queue: <info>%s</info> - routing_key: <info>%s</info>',
$queue['queue'],
$queue['routing_key']
));
}
} | [
"public",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"backend",
"=",
"$",
"this",
"->",
"getContainer",
"(",
")",
"->",
"get",
"(",
"'sonata.notification.backend'",
")",
";",
"if",
"(",
"!",
"$",
"backend",
"instanceof",
"QueueDispatcherInterface",
")",
"{",
"$",
"output",
"->",
"writeln",
"(",
"'The backend class <info>'",
".",
"\\",
"get_class",
"(",
"$",
"backend",
")",
".",
"'</info> does not provide multiple queues.'",
")",
";",
"return",
";",
"}",
"$",
"output",
"->",
"writeln",
"(",
"'<info>List of queues available</info>'",
")",
";",
"foreach",
"(",
"$",
"backend",
"->",
"getQueues",
"(",
")",
"as",
"$",
"queue",
")",
"{",
"$",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'queue: <info>%s</info> - routing_key: <info>%s</info>'",
",",
"$",
"queue",
"[",
"'queue'",
"]",
",",
"$",
"queue",
"[",
"'routing_key'",
"]",
")",
")",
";",
"}",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Command/ListQueuesCommand.php#L35-L55 |
sonata-project/SonataNotificationBundle | src/Backend/RuntimeBackend.php | RuntimeBackend.create | public function create($type, array $body)
{
$message = new Message();
$message->setType($type);
$message->setBody($body);
$message->setState(MessageInterface::STATE_OPEN);
return $message;
} | php | public function create($type, array $body)
{
$message = new Message();
$message->setType($type);
$message->setBody($body);
$message->setState(MessageInterface::STATE_OPEN);
return $message;
} | [
"public",
"function",
"create",
"(",
"$",
"type",
",",
"array",
"$",
"body",
")",
"{",
"$",
"message",
"=",
"new",
"Message",
"(",
")",
";",
"$",
"message",
"->",
"setType",
"(",
"$",
"type",
")",
";",
"$",
"message",
"->",
"setBody",
"(",
"$",
"body",
")",
";",
"$",
"message",
"->",
"setState",
"(",
"MessageInterface",
"::",
"STATE_OPEN",
")",
";",
"return",
"$",
"message",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Backend/RuntimeBackend.php#L51-L59 |
sonata-project/SonataNotificationBundle | src/Backend/RuntimeBackend.php | RuntimeBackend.handle | public function handle(MessageInterface $message, EventDispatcherInterface $dispatcher)
{
$event = new ConsumerEvent($message);
try {
$dispatcher->dispatch($message->getType(), $event);
$message->setCompletedAt(new \DateTime());
$message->setState(MessageInterface::STATE_DONE);
} catch (\Exception $e) {
$message->setCompletedAt(new \DateTime());
$message->setState(MessageInterface::STATE_ERROR);
throw new HandlingException('Error while handling a message: '.$e->getMessage(), 0, $e);
}
} | php | public function handle(MessageInterface $message, EventDispatcherInterface $dispatcher)
{
$event = new ConsumerEvent($message);
try {
$dispatcher->dispatch($message->getType(), $event);
$message->setCompletedAt(new \DateTime());
$message->setState(MessageInterface::STATE_DONE);
} catch (\Exception $e) {
$message->setCompletedAt(new \DateTime());
$message->setState(MessageInterface::STATE_ERROR);
throw new HandlingException('Error while handling a message: '.$e->getMessage(), 0, $e);
}
} | [
"public",
"function",
"handle",
"(",
"MessageInterface",
"$",
"message",
",",
"EventDispatcherInterface",
"$",
"dispatcher",
")",
"{",
"$",
"event",
"=",
"new",
"ConsumerEvent",
"(",
"$",
"message",
")",
";",
"try",
"{",
"$",
"dispatcher",
"->",
"dispatch",
"(",
"$",
"message",
"->",
"getType",
"(",
")",
",",
"$",
"event",
")",
";",
"$",
"message",
"->",
"setCompletedAt",
"(",
"new",
"\\",
"DateTime",
"(",
")",
")",
";",
"$",
"message",
"->",
"setState",
"(",
"MessageInterface",
"::",
"STATE_DONE",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"$",
"message",
"->",
"setCompletedAt",
"(",
"new",
"\\",
"DateTime",
"(",
")",
")",
";",
"$",
"message",
"->",
"setState",
"(",
"MessageInterface",
"::",
"STATE_ERROR",
")",
";",
"throw",
"new",
"HandlingException",
"(",
"'Error while handling a message: '",
".",
"$",
"e",
"->",
"getMessage",
"(",
")",
",",
"0",
",",
"$",
"e",
")",
";",
"}",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Backend/RuntimeBackend.php#L94-L109 |
sonata-project/SonataNotificationBundle | src/Iterator/AMQPMessageIterator.php | AMQPMessageIterator.next | public function next()
{
$this->isValid = false;
if ($amqpMessage = $this->consumer->receive($this->timeout)) {
$this->AMQMessage = $this->convertToAmqpLibMessage($amqpMessage);
$data = json_decode($amqpMessage->getBody(), true);
$data['body']['interopMessage'] = $amqpMessage;
// @deprecated
$data['body']['AMQMessage'] = $this->AMQMessage;
$message = new Message();
$message->setBody($data['body']);
$message->setType($data['type']);
$message->setState($data['state']);
$this->message = $message;
++$this->counter;
$this->isValid = true;
}
} | php | public function next()
{
$this->isValid = false;
if ($amqpMessage = $this->consumer->receive($this->timeout)) {
$this->AMQMessage = $this->convertToAmqpLibMessage($amqpMessage);
$data = json_decode($amqpMessage->getBody(), true);
$data['body']['interopMessage'] = $amqpMessage;
// @deprecated
$data['body']['AMQMessage'] = $this->AMQMessage;
$message = new Message();
$message->setBody($data['body']);
$message->setType($data['type']);
$message->setState($data['state']);
$this->message = $message;
++$this->counter;
$this->isValid = true;
}
} | [
"public",
"function",
"next",
"(",
")",
"{",
"$",
"this",
"->",
"isValid",
"=",
"false",
";",
"if",
"(",
"$",
"amqpMessage",
"=",
"$",
"this",
"->",
"consumer",
"->",
"receive",
"(",
"$",
"this",
"->",
"timeout",
")",
")",
"{",
"$",
"this",
"->",
"AMQMessage",
"=",
"$",
"this",
"->",
"convertToAmqpLibMessage",
"(",
"$",
"amqpMessage",
")",
";",
"$",
"data",
"=",
"json_decode",
"(",
"$",
"amqpMessage",
"->",
"getBody",
"(",
")",
",",
"true",
")",
";",
"$",
"data",
"[",
"'body'",
"]",
"[",
"'interopMessage'",
"]",
"=",
"$",
"amqpMessage",
";",
"// @deprecated",
"$",
"data",
"[",
"'body'",
"]",
"[",
"'AMQMessage'",
"]",
"=",
"$",
"this",
"->",
"AMQMessage",
";",
"$",
"message",
"=",
"new",
"Message",
"(",
")",
";",
"$",
"message",
"->",
"setBody",
"(",
"$",
"data",
"[",
"'body'",
"]",
")",
";",
"$",
"message",
"->",
"setType",
"(",
"$",
"data",
"[",
"'type'",
"]",
")",
";",
"$",
"message",
"->",
"setState",
"(",
"$",
"data",
"[",
"'state'",
"]",
")",
";",
"$",
"this",
"->",
"message",
"=",
"$",
"message",
";",
"++",
"$",
"this",
"->",
"counter",
";",
"$",
"this",
"->",
"isValid",
"=",
"true",
";",
"}",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Iterator/AMQPMessageIterator.php#L96-L118 |
sonata-project/SonataNotificationBundle | src/Iterator/AMQPMessageIterator.php | AMQPMessageIterator.convertToAmqpLibMessage | private function convertToAmqpLibMessage(\Interop\Amqp\AmqpMessage $amqpMessage)
{
$amqpLibProperties = $amqpMessage->getHeaders();
$amqpLibProperties['application_headers'] = $amqpMessage->getProperties();
$amqpLibMessage = new AMQPMessage($amqpMessage->getBody(), $amqpLibProperties);
$amqpLibMessage->delivery_info = [
'consumer_tag' => $this->consumer->getConsumerTag(),
'delivery_tag' => $amqpMessage->getDeliveryTag(),
'redelivered' => $amqpMessage->isRedelivered(),
'routing_key' => $amqpMessage->getRoutingKey(),
'channel' => $this->channel,
];
return $amqpLibMessage;
} | php | private function convertToAmqpLibMessage(\Interop\Amqp\AmqpMessage $amqpMessage)
{
$amqpLibProperties = $amqpMessage->getHeaders();
$amqpLibProperties['application_headers'] = $amqpMessage->getProperties();
$amqpLibMessage = new AMQPMessage($amqpMessage->getBody(), $amqpLibProperties);
$amqpLibMessage->delivery_info = [
'consumer_tag' => $this->consumer->getConsumerTag(),
'delivery_tag' => $amqpMessage->getDeliveryTag(),
'redelivered' => $amqpMessage->isRedelivered(),
'routing_key' => $amqpMessage->getRoutingKey(),
'channel' => $this->channel,
];
return $amqpLibMessage;
} | [
"private",
"function",
"convertToAmqpLibMessage",
"(",
"\\",
"Interop",
"\\",
"Amqp",
"\\",
"AmqpMessage",
"$",
"amqpMessage",
")",
"{",
"$",
"amqpLibProperties",
"=",
"$",
"amqpMessage",
"->",
"getHeaders",
"(",
")",
";",
"$",
"amqpLibProperties",
"[",
"'application_headers'",
"]",
"=",
"$",
"amqpMessage",
"->",
"getProperties",
"(",
")",
";",
"$",
"amqpLibMessage",
"=",
"new",
"AMQPMessage",
"(",
"$",
"amqpMessage",
"->",
"getBody",
"(",
")",
",",
"$",
"amqpLibProperties",
")",
";",
"$",
"amqpLibMessage",
"->",
"delivery_info",
"=",
"[",
"'consumer_tag'",
"=>",
"$",
"this",
"->",
"consumer",
"->",
"getConsumerTag",
"(",
")",
",",
"'delivery_tag'",
"=>",
"$",
"amqpMessage",
"->",
"getDeliveryTag",
"(",
")",
",",
"'redelivered'",
"=>",
"$",
"amqpMessage",
"->",
"isRedelivered",
"(",
")",
",",
"'routing_key'",
"=>",
"$",
"amqpMessage",
"->",
"getRoutingKey",
"(",
")",
",",
"'channel'",
"=>",
"$",
"this",
"->",
"channel",
",",
"]",
";",
"return",
"$",
"amqpLibMessage",
";",
"}"
] | @deprecated since 3.2, will be removed in 4.x
@param \Interop\Amqp\AmqpMessage $amqpMessage
@return AMQPMessage | [
"@deprecated",
"since",
"3",
".",
"2",
"will",
"be",
"removed",
"in",
"4",
".",
"x"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Iterator/AMQPMessageIterator.php#L152-L167 |
sonata-project/SonataNotificationBundle | src/Backend/MessageManagerBackend.php | MessageManagerBackend.create | public function create($type, array $body)
{
$message = $this->messageManager->create();
$message->setType($type);
$message->setBody($body);
$message->setState(MessageInterface::STATE_OPEN);
return $message;
} | php | public function create($type, array $body)
{
$message = $this->messageManager->create();
$message->setType($type);
$message->setBody($body);
$message->setState(MessageInterface::STATE_OPEN);
return $message;
} | [
"public",
"function",
"create",
"(",
"$",
"type",
",",
"array",
"$",
"body",
")",
"{",
"$",
"message",
"=",
"$",
"this",
"->",
"messageManager",
"->",
"create",
"(",
")",
";",
"$",
"message",
"->",
"setType",
"(",
"$",
"type",
")",
";",
"$",
"message",
"->",
"setBody",
"(",
"$",
"body",
")",
";",
"$",
"message",
"->",
"setState",
"(",
"MessageInterface",
"::",
"STATE_OPEN",
")",
";",
"return",
"$",
"message",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Backend/MessageManagerBackend.php#L102-L110 |
sonata-project/SonataNotificationBundle | src/Backend/MessageManagerBackend.php | MessageManagerBackend.getIterator | public function getIterator()
{
return new MessageManagerMessageIterator($this->messageManager, $this->types, $this->pause, $this->batchSize);
} | php | public function getIterator()
{
return new MessageManagerMessageIterator($this->messageManager, $this->types, $this->pause, $this->batchSize);
} | [
"public",
"function",
"getIterator",
"(",
")",
"{",
"return",
"new",
"MessageManagerMessageIterator",
"(",
"$",
"this",
"->",
"messageManager",
",",
"$",
"this",
"->",
"types",
",",
"$",
"this",
"->",
"pause",
",",
"$",
"this",
"->",
"batchSize",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Backend/MessageManagerBackend.php#L123-L126 |
sonata-project/SonataNotificationBundle | src/Backend/MessageManagerBackend.php | MessageManagerBackend.handle | public function handle(MessageInterface $message, EventDispatcherInterface $dispatcher)
{
$event = new ConsumerEvent($message);
try {
$message->setStartedAt(new \DateTime());
$message->setState(MessageInterface::STATE_IN_PROGRESS);
$this->messageManager->save($message);
$dispatcher->dispatch($message->getType(), $event);
$message->setCompletedAt(new \DateTime());
$message->setState(MessageInterface::STATE_DONE);
$this->messageManager->save($message);
return $event->getReturnInfo();
} catch (\Exception $e) {
$message->setCompletedAt(new \DateTime());
$message->setState(MessageInterface::STATE_ERROR);
$this->messageManager->save($message);
throw new HandlingException('Error while handling a message', 0, $e);
}
} | php | public function handle(MessageInterface $message, EventDispatcherInterface $dispatcher)
{
$event = new ConsumerEvent($message);
try {
$message->setStartedAt(new \DateTime());
$message->setState(MessageInterface::STATE_IN_PROGRESS);
$this->messageManager->save($message);
$dispatcher->dispatch($message->getType(), $event);
$message->setCompletedAt(new \DateTime());
$message->setState(MessageInterface::STATE_DONE);
$this->messageManager->save($message);
return $event->getReturnInfo();
} catch (\Exception $e) {
$message->setCompletedAt(new \DateTime());
$message->setState(MessageInterface::STATE_ERROR);
$this->messageManager->save($message);
throw new HandlingException('Error while handling a message', 0, $e);
}
} | [
"public",
"function",
"handle",
"(",
"MessageInterface",
"$",
"message",
",",
"EventDispatcherInterface",
"$",
"dispatcher",
")",
"{",
"$",
"event",
"=",
"new",
"ConsumerEvent",
"(",
"$",
"message",
")",
";",
"try",
"{",
"$",
"message",
"->",
"setStartedAt",
"(",
"new",
"\\",
"DateTime",
"(",
")",
")",
";",
"$",
"message",
"->",
"setState",
"(",
"MessageInterface",
"::",
"STATE_IN_PROGRESS",
")",
";",
"$",
"this",
"->",
"messageManager",
"->",
"save",
"(",
"$",
"message",
")",
";",
"$",
"dispatcher",
"->",
"dispatch",
"(",
"$",
"message",
"->",
"getType",
"(",
")",
",",
"$",
"event",
")",
";",
"$",
"message",
"->",
"setCompletedAt",
"(",
"new",
"\\",
"DateTime",
"(",
")",
")",
";",
"$",
"message",
"->",
"setState",
"(",
"MessageInterface",
"::",
"STATE_DONE",
")",
";",
"$",
"this",
"->",
"messageManager",
"->",
"save",
"(",
"$",
"message",
")",
";",
"return",
"$",
"event",
"->",
"getReturnInfo",
"(",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"$",
"message",
"->",
"setCompletedAt",
"(",
"new",
"\\",
"DateTime",
"(",
")",
")",
";",
"$",
"message",
"->",
"setState",
"(",
"MessageInterface",
"::",
"STATE_ERROR",
")",
";",
"$",
"this",
"->",
"messageManager",
"->",
"save",
"(",
"$",
"message",
")",
";",
"throw",
"new",
"HandlingException",
"(",
"'Error while handling a message'",
",",
"0",
",",
"$",
"e",
")",
";",
"}",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Backend/MessageManagerBackend.php#L146-L170 |
sonata-project/SonataNotificationBundle | src/Backend/MessageManagerBackend.php | MessageManagerBackend.getStatus | public function getStatus()
{
try {
$states = $this->messageManager->countStates();
} catch (\Exception $e) {
return new Failure(sprintf('Unable to retrieve message information - %s (Database)', $e->getMessage()));
}
if ($states[MessageInterface::STATE_IN_PROGRESS] > $this->checkLevel[MessageInterface::STATE_IN_PROGRESS]) {
return new Failure('Too many messages processed at the same time (Database)');
}
if ($states[MessageInterface::STATE_ERROR] > $this->checkLevel[MessageInterface::STATE_ERROR]) {
return new Failure('Too many errors (Database)');
}
if ($states[MessageInterface::STATE_OPEN] > $this->checkLevel[MessageInterface::STATE_OPEN]) {
return new Warning('Too many messages waiting to be processed (Database)');
}
if ($states[MessageInterface::STATE_DONE] > $this->checkLevel[MessageInterface::STATE_DONE]) {
return new Warning('Too many processed messages, please clean the database (Database)');
}
return new Success('Ok (Database)');
} | php | public function getStatus()
{
try {
$states = $this->messageManager->countStates();
} catch (\Exception $e) {
return new Failure(sprintf('Unable to retrieve message information - %s (Database)', $e->getMessage()));
}
if ($states[MessageInterface::STATE_IN_PROGRESS] > $this->checkLevel[MessageInterface::STATE_IN_PROGRESS]) {
return new Failure('Too many messages processed at the same time (Database)');
}
if ($states[MessageInterface::STATE_ERROR] > $this->checkLevel[MessageInterface::STATE_ERROR]) {
return new Failure('Too many errors (Database)');
}
if ($states[MessageInterface::STATE_OPEN] > $this->checkLevel[MessageInterface::STATE_OPEN]) {
return new Warning('Too many messages waiting to be processed (Database)');
}
if ($states[MessageInterface::STATE_DONE] > $this->checkLevel[MessageInterface::STATE_DONE]) {
return new Warning('Too many processed messages, please clean the database (Database)');
}
return new Success('Ok (Database)');
} | [
"public",
"function",
"getStatus",
"(",
")",
"{",
"try",
"{",
"$",
"states",
"=",
"$",
"this",
"->",
"messageManager",
"->",
"countStates",
"(",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"return",
"new",
"Failure",
"(",
"sprintf",
"(",
"'Unable to retrieve message information - %s (Database)'",
",",
"$",
"e",
"->",
"getMessage",
"(",
")",
")",
")",
";",
"}",
"if",
"(",
"$",
"states",
"[",
"MessageInterface",
"::",
"STATE_IN_PROGRESS",
"]",
">",
"$",
"this",
"->",
"checkLevel",
"[",
"MessageInterface",
"::",
"STATE_IN_PROGRESS",
"]",
")",
"{",
"return",
"new",
"Failure",
"(",
"'Too many messages processed at the same time (Database)'",
")",
";",
"}",
"if",
"(",
"$",
"states",
"[",
"MessageInterface",
"::",
"STATE_ERROR",
"]",
">",
"$",
"this",
"->",
"checkLevel",
"[",
"MessageInterface",
"::",
"STATE_ERROR",
"]",
")",
"{",
"return",
"new",
"Failure",
"(",
"'Too many errors (Database)'",
")",
";",
"}",
"if",
"(",
"$",
"states",
"[",
"MessageInterface",
"::",
"STATE_OPEN",
"]",
">",
"$",
"this",
"->",
"checkLevel",
"[",
"MessageInterface",
"::",
"STATE_OPEN",
"]",
")",
"{",
"return",
"new",
"Warning",
"(",
"'Too many messages waiting to be processed (Database)'",
")",
";",
"}",
"if",
"(",
"$",
"states",
"[",
"MessageInterface",
"::",
"STATE_DONE",
"]",
">",
"$",
"this",
"->",
"checkLevel",
"[",
"MessageInterface",
"::",
"STATE_DONE",
"]",
")",
"{",
"return",
"new",
"Warning",
"(",
"'Too many processed messages, please clean the database (Database)'",
")",
";",
"}",
"return",
"new",
"Success",
"(",
"'Ok (Database)'",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Backend/MessageManagerBackend.php#L175-L200 |
sonata-project/SonataNotificationBundle | src/Backend/AMQPBackend.php | AMQPBackend.initialize | public function initialize()
{
$args = [];
if (null !== $this->deadLetterExchange) {
$args['x-dead-letter-exchange'] = $this->deadLetterExchange;
if (null !== $this->deadLetterRoutingKey) {
$args['x-dead-letter-routing-key'] = $this->deadLetterRoutingKey;
}
}
if (null !== $this->ttl) {
$args['x-message-ttl'] = $this->ttl;
}
$queue = $this->getContext()->createQueue($this->queue);
$queue->addFlag(AmqpQueue::FLAG_DURABLE);
$queue->setArguments($args);
$this->getContext()->declareQueue($queue);
$topic = $this->getContext()->createTopic($this->exchange);
$topic->setType(AmqpTopic::TYPE_DIRECT);
$topic->addFlag(AmqpTopic::FLAG_DURABLE);
$this->getContext()->declareTopic($topic);
$this->getContext()->bind(new AmqpBind($queue, $topic, $this->key));
if (null !== $this->deadLetterExchange && null === $this->deadLetterRoutingKey) {
$deadLetterTopic = $this->getContext()->createTopic($this->deadLetterExchange);
$deadLetterTopic->setType(AmqpTopic::TYPE_DIRECT);
$deadLetterTopic->addFlag(AmqpTopic::FLAG_DURABLE);
$this->getContext()->declareTopic($deadLetterTopic);
$this->getContext()->bind(new AmqpBind($queue, $deadLetterTopic, $this->key));
}
} | php | public function initialize()
{
$args = [];
if (null !== $this->deadLetterExchange) {
$args['x-dead-letter-exchange'] = $this->deadLetterExchange;
if (null !== $this->deadLetterRoutingKey) {
$args['x-dead-letter-routing-key'] = $this->deadLetterRoutingKey;
}
}
if (null !== $this->ttl) {
$args['x-message-ttl'] = $this->ttl;
}
$queue = $this->getContext()->createQueue($this->queue);
$queue->addFlag(AmqpQueue::FLAG_DURABLE);
$queue->setArguments($args);
$this->getContext()->declareQueue($queue);
$topic = $this->getContext()->createTopic($this->exchange);
$topic->setType(AmqpTopic::TYPE_DIRECT);
$topic->addFlag(AmqpTopic::FLAG_DURABLE);
$this->getContext()->declareTopic($topic);
$this->getContext()->bind(new AmqpBind($queue, $topic, $this->key));
if (null !== $this->deadLetterExchange && null === $this->deadLetterRoutingKey) {
$deadLetterTopic = $this->getContext()->createTopic($this->deadLetterExchange);
$deadLetterTopic->setType(AmqpTopic::TYPE_DIRECT);
$deadLetterTopic->addFlag(AmqpTopic::FLAG_DURABLE);
$this->getContext()->declareTopic($deadLetterTopic);
$this->getContext()->bind(new AmqpBind($queue, $deadLetterTopic, $this->key));
}
} | [
"public",
"function",
"initialize",
"(",
")",
"{",
"$",
"args",
"=",
"[",
"]",
";",
"if",
"(",
"null",
"!==",
"$",
"this",
"->",
"deadLetterExchange",
")",
"{",
"$",
"args",
"[",
"'x-dead-letter-exchange'",
"]",
"=",
"$",
"this",
"->",
"deadLetterExchange",
";",
"if",
"(",
"null",
"!==",
"$",
"this",
"->",
"deadLetterRoutingKey",
")",
"{",
"$",
"args",
"[",
"'x-dead-letter-routing-key'",
"]",
"=",
"$",
"this",
"->",
"deadLetterRoutingKey",
";",
"}",
"}",
"if",
"(",
"null",
"!==",
"$",
"this",
"->",
"ttl",
")",
"{",
"$",
"args",
"[",
"'x-message-ttl'",
"]",
"=",
"$",
"this",
"->",
"ttl",
";",
"}",
"$",
"queue",
"=",
"$",
"this",
"->",
"getContext",
"(",
")",
"->",
"createQueue",
"(",
"$",
"this",
"->",
"queue",
")",
";",
"$",
"queue",
"->",
"addFlag",
"(",
"AmqpQueue",
"::",
"FLAG_DURABLE",
")",
";",
"$",
"queue",
"->",
"setArguments",
"(",
"$",
"args",
")",
";",
"$",
"this",
"->",
"getContext",
"(",
")",
"->",
"declareQueue",
"(",
"$",
"queue",
")",
";",
"$",
"topic",
"=",
"$",
"this",
"->",
"getContext",
"(",
")",
"->",
"createTopic",
"(",
"$",
"this",
"->",
"exchange",
")",
";",
"$",
"topic",
"->",
"setType",
"(",
"AmqpTopic",
"::",
"TYPE_DIRECT",
")",
";",
"$",
"topic",
"->",
"addFlag",
"(",
"AmqpTopic",
"::",
"FLAG_DURABLE",
")",
";",
"$",
"this",
"->",
"getContext",
"(",
")",
"->",
"declareTopic",
"(",
"$",
"topic",
")",
";",
"$",
"this",
"->",
"getContext",
"(",
")",
"->",
"bind",
"(",
"new",
"AmqpBind",
"(",
"$",
"queue",
",",
"$",
"topic",
",",
"$",
"this",
"->",
"key",
")",
")",
";",
"if",
"(",
"null",
"!==",
"$",
"this",
"->",
"deadLetterExchange",
"&&",
"null",
"===",
"$",
"this",
"->",
"deadLetterRoutingKey",
")",
"{",
"$",
"deadLetterTopic",
"=",
"$",
"this",
"->",
"getContext",
"(",
")",
"->",
"createTopic",
"(",
"$",
"this",
"->",
"deadLetterExchange",
")",
";",
"$",
"deadLetterTopic",
"->",
"setType",
"(",
"AmqpTopic",
"::",
"TYPE_DIRECT",
")",
";",
"$",
"deadLetterTopic",
"->",
"addFlag",
"(",
"AmqpTopic",
"::",
"FLAG_DURABLE",
")",
";",
"$",
"this",
"->",
"getContext",
"(",
")",
"->",
"declareTopic",
"(",
"$",
"deadLetterTopic",
")",
";",
"$",
"this",
"->",
"getContext",
"(",
")",
"->",
"bind",
"(",
"new",
"AmqpBind",
"(",
"$",
"queue",
",",
"$",
"deadLetterTopic",
",",
"$",
"this",
"->",
"key",
")",
")",
";",
"}",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Backend/AMQPBackend.php#L119-L154 |
sonata-project/SonataNotificationBundle | src/Backend/AMQPBackend.php | AMQPBackend.publish | public function publish(MessageInterface $message)
{
$body = json_encode([
'type' => $message->getType(),
'body' => $message->getBody(),
'createdAt' => $message->getCreatedAt()->format('U'),
'state' => $message->getState(),
]);
$amqpMessage = $this->getContext()->createMessage($body);
$amqpMessage->setContentType('text/plain'); // application/json ?
$amqpMessage->setTimestamp($message->getCreatedAt()->getTimestamp());
$amqpMessage->setDeliveryMode(AmqpMessage::DELIVERY_MODE_PERSISTENT);
$amqpMessage->setRoutingKey($this->key);
$topic = $this->getContext()->createTopic($this->exchange);
$this->getContext()->createProducer()->send($topic, $amqpMessage);
} | php | public function publish(MessageInterface $message)
{
$body = json_encode([
'type' => $message->getType(),
'body' => $message->getBody(),
'createdAt' => $message->getCreatedAt()->format('U'),
'state' => $message->getState(),
]);
$amqpMessage = $this->getContext()->createMessage($body);
$amqpMessage->setContentType('text/plain'); // application/json ?
$amqpMessage->setTimestamp($message->getCreatedAt()->getTimestamp());
$amqpMessage->setDeliveryMode(AmqpMessage::DELIVERY_MODE_PERSISTENT);
$amqpMessage->setRoutingKey($this->key);
$topic = $this->getContext()->createTopic($this->exchange);
$this->getContext()->createProducer()->send($topic, $amqpMessage);
} | [
"public",
"function",
"publish",
"(",
"MessageInterface",
"$",
"message",
")",
"{",
"$",
"body",
"=",
"json_encode",
"(",
"[",
"'type'",
"=>",
"$",
"message",
"->",
"getType",
"(",
")",
",",
"'body'",
"=>",
"$",
"message",
"->",
"getBody",
"(",
")",
",",
"'createdAt'",
"=>",
"$",
"message",
"->",
"getCreatedAt",
"(",
")",
"->",
"format",
"(",
"'U'",
")",
",",
"'state'",
"=>",
"$",
"message",
"->",
"getState",
"(",
")",
",",
"]",
")",
";",
"$",
"amqpMessage",
"=",
"$",
"this",
"->",
"getContext",
"(",
")",
"->",
"createMessage",
"(",
"$",
"body",
")",
";",
"$",
"amqpMessage",
"->",
"setContentType",
"(",
"'text/plain'",
")",
";",
"// application/json ?",
"$",
"amqpMessage",
"->",
"setTimestamp",
"(",
"$",
"message",
"->",
"getCreatedAt",
"(",
")",
"->",
"getTimestamp",
"(",
")",
")",
";",
"$",
"amqpMessage",
"->",
"setDeliveryMode",
"(",
"AmqpMessage",
"::",
"DELIVERY_MODE_PERSISTENT",
")",
";",
"$",
"amqpMessage",
"->",
"setRoutingKey",
"(",
"$",
"this",
"->",
"key",
")",
";",
"$",
"topic",
"=",
"$",
"this",
"->",
"getContext",
"(",
")",
"->",
"createTopic",
"(",
"$",
"this",
"->",
"exchange",
")",
";",
"$",
"this",
"->",
"getContext",
"(",
")",
"->",
"createProducer",
"(",
")",
"->",
"send",
"(",
"$",
"topic",
",",
"$",
"amqpMessage",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Backend/AMQPBackend.php#L159-L177 |
sonata-project/SonataNotificationBundle | src/Backend/AMQPBackend.php | AMQPBackend.getIterator | public function getIterator()
{
$context = $this->getContext();
if (null !== $this->prefetchCount) {
$context->setQos(null, $this->prefetchCount, false);
}
$this->consumer = $this->getContext()->createConsumer($this->getContext()->createQueue($this->queue));
$this->consumer->setConsumerTag('sonata_notification_'.uniqid());
if (!$context instanceof \Enqueue\AmqpLib\AmqpContext) {
throw new \LogicException('The BC layer works only if enqueue/amqp-lib lib is being used.');
}
return new AMQPMessageIterator($context->getLibChannel(), $this->consumer);
} | php | public function getIterator()
{
$context = $this->getContext();
if (null !== $this->prefetchCount) {
$context->setQos(null, $this->prefetchCount, false);
}
$this->consumer = $this->getContext()->createConsumer($this->getContext()->createQueue($this->queue));
$this->consumer->setConsumerTag('sonata_notification_'.uniqid());
if (!$context instanceof \Enqueue\AmqpLib\AmqpContext) {
throw new \LogicException('The BC layer works only if enqueue/amqp-lib lib is being used.');
}
return new AMQPMessageIterator($context->getLibChannel(), $this->consumer);
} | [
"public",
"function",
"getIterator",
"(",
")",
"{",
"$",
"context",
"=",
"$",
"this",
"->",
"getContext",
"(",
")",
";",
"if",
"(",
"null",
"!==",
"$",
"this",
"->",
"prefetchCount",
")",
"{",
"$",
"context",
"->",
"setQos",
"(",
"null",
",",
"$",
"this",
"->",
"prefetchCount",
",",
"false",
")",
";",
"}",
"$",
"this",
"->",
"consumer",
"=",
"$",
"this",
"->",
"getContext",
"(",
")",
"->",
"createConsumer",
"(",
"$",
"this",
"->",
"getContext",
"(",
")",
"->",
"createQueue",
"(",
"$",
"this",
"->",
"queue",
")",
")",
";",
"$",
"this",
"->",
"consumer",
"->",
"setConsumerTag",
"(",
"'sonata_notification_'",
".",
"uniqid",
"(",
")",
")",
";",
"if",
"(",
"!",
"$",
"context",
"instanceof",
"\\",
"Enqueue",
"\\",
"AmqpLib",
"\\",
"AmqpContext",
")",
"{",
"throw",
"new",
"\\",
"LogicException",
"(",
"'The BC layer works only if enqueue/amqp-lib lib is being used.'",
")",
";",
"}",
"return",
"new",
"AMQPMessageIterator",
"(",
"$",
"context",
"->",
"getLibChannel",
"(",
")",
",",
"$",
"this",
"->",
"consumer",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Backend/AMQPBackend.php#L203-L219 |
sonata-project/SonataNotificationBundle | src/Backend/AMQPBackend.php | AMQPBackend.handle | public function handle(MessageInterface $message, EventDispatcherInterface $dispatcher)
{
$event = new ConsumerEvent($message);
/** @var AmqpMessage $amqpMessage */
$amqpMessage = $message->getValue('interopMessage');
try {
$dispatcher->dispatch($message->getType(), $event);
$this->consumer->acknowledge($amqpMessage);
$message->setCompletedAt(new \DateTime());
$message->setState(MessageInterface::STATE_DONE);
} catch (HandlingException $e) {
$message->setCompletedAt(new \DateTime());
$message->setState(MessageInterface::STATE_ERROR);
$this->consumer->acknowledge($amqpMessage);
throw new HandlingException('Error while handling a message', 0, $e);
} catch (\Exception $e) {
$message->setCompletedAt(new \DateTime());
$message->setState(MessageInterface::STATE_ERROR);
$this->consumer->reject($amqpMessage, $this->recover);
throw new HandlingException('Error while handling a message', 0, $e);
}
} | php | public function handle(MessageInterface $message, EventDispatcherInterface $dispatcher)
{
$event = new ConsumerEvent($message);
/** @var AmqpMessage $amqpMessage */
$amqpMessage = $message->getValue('interopMessage');
try {
$dispatcher->dispatch($message->getType(), $event);
$this->consumer->acknowledge($amqpMessage);
$message->setCompletedAt(new \DateTime());
$message->setState(MessageInterface::STATE_DONE);
} catch (HandlingException $e) {
$message->setCompletedAt(new \DateTime());
$message->setState(MessageInterface::STATE_ERROR);
$this->consumer->acknowledge($amqpMessage);
throw new HandlingException('Error while handling a message', 0, $e);
} catch (\Exception $e) {
$message->setCompletedAt(new \DateTime());
$message->setState(MessageInterface::STATE_ERROR);
$this->consumer->reject($amqpMessage, $this->recover);
throw new HandlingException('Error while handling a message', 0, $e);
}
} | [
"public",
"function",
"handle",
"(",
"MessageInterface",
"$",
"message",
",",
"EventDispatcherInterface",
"$",
"dispatcher",
")",
"{",
"$",
"event",
"=",
"new",
"ConsumerEvent",
"(",
"$",
"message",
")",
";",
"/** @var AmqpMessage $amqpMessage */",
"$",
"amqpMessage",
"=",
"$",
"message",
"->",
"getValue",
"(",
"'interopMessage'",
")",
";",
"try",
"{",
"$",
"dispatcher",
"->",
"dispatch",
"(",
"$",
"message",
"->",
"getType",
"(",
")",
",",
"$",
"event",
")",
";",
"$",
"this",
"->",
"consumer",
"->",
"acknowledge",
"(",
"$",
"amqpMessage",
")",
";",
"$",
"message",
"->",
"setCompletedAt",
"(",
"new",
"\\",
"DateTime",
"(",
")",
")",
";",
"$",
"message",
"->",
"setState",
"(",
"MessageInterface",
"::",
"STATE_DONE",
")",
";",
"}",
"catch",
"(",
"HandlingException",
"$",
"e",
")",
"{",
"$",
"message",
"->",
"setCompletedAt",
"(",
"new",
"\\",
"DateTime",
"(",
")",
")",
";",
"$",
"message",
"->",
"setState",
"(",
"MessageInterface",
"::",
"STATE_ERROR",
")",
";",
"$",
"this",
"->",
"consumer",
"->",
"acknowledge",
"(",
"$",
"amqpMessage",
")",
";",
"throw",
"new",
"HandlingException",
"(",
"'Error while handling a message'",
",",
"0",
",",
"$",
"e",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"$",
"message",
"->",
"setCompletedAt",
"(",
"new",
"\\",
"DateTime",
"(",
")",
")",
";",
"$",
"message",
"->",
"setState",
"(",
"MessageInterface",
"::",
"STATE_ERROR",
")",
";",
"$",
"this",
"->",
"consumer",
"->",
"reject",
"(",
"$",
"amqpMessage",
",",
"$",
"this",
"->",
"recover",
")",
";",
"throw",
"new",
"HandlingException",
"(",
"'Error while handling a message'",
",",
"0",
",",
"$",
"e",
")",
";",
"}",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Backend/AMQPBackend.php#L224-L253 |
sonata-project/SonataNotificationBundle | src/Selector/ErroneousMessagesSelector.php | ErroneousMessagesSelector.getMessages | public function getMessages(array $types, $maxAttempts = 5)
{
$query = $this->registry->getManagerForClass($this->class)->getRepository($this->class)
->createQueryBuilder('m')
->where('m.state = :erroneousState')
->andWhere('m.restartCount < :maxAttempts');
$parameters = [
'erroneousState' => MessageInterface::STATE_ERROR,
'maxAttempts' => $maxAttempts,
];
if (\count($types) > 0) {
$query->andWhere('m.type IN (:types)');
$parameters['types'] = $types;
}
$query->setParameters($parameters);
return $query->getQuery()->execute();
} | php | public function getMessages(array $types, $maxAttempts = 5)
{
$query = $this->registry->getManagerForClass($this->class)->getRepository($this->class)
->createQueryBuilder('m')
->where('m.state = :erroneousState')
->andWhere('m.restartCount < :maxAttempts');
$parameters = [
'erroneousState' => MessageInterface::STATE_ERROR,
'maxAttempts' => $maxAttempts,
];
if (\count($types) > 0) {
$query->andWhere('m.type IN (:types)');
$parameters['types'] = $types;
}
$query->setParameters($parameters);
return $query->getQuery()->execute();
} | [
"public",
"function",
"getMessages",
"(",
"array",
"$",
"types",
",",
"$",
"maxAttempts",
"=",
"5",
")",
"{",
"$",
"query",
"=",
"$",
"this",
"->",
"registry",
"->",
"getManagerForClass",
"(",
"$",
"this",
"->",
"class",
")",
"->",
"getRepository",
"(",
"$",
"this",
"->",
"class",
")",
"->",
"createQueryBuilder",
"(",
"'m'",
")",
"->",
"where",
"(",
"'m.state = :erroneousState'",
")",
"->",
"andWhere",
"(",
"'m.restartCount < :maxAttempts'",
")",
";",
"$",
"parameters",
"=",
"[",
"'erroneousState'",
"=>",
"MessageInterface",
"::",
"STATE_ERROR",
",",
"'maxAttempts'",
"=>",
"$",
"maxAttempts",
",",
"]",
";",
"if",
"(",
"\\",
"count",
"(",
"$",
"types",
")",
">",
"0",
")",
"{",
"$",
"query",
"->",
"andWhere",
"(",
"'m.type IN (:types)'",
")",
";",
"$",
"parameters",
"[",
"'types'",
"]",
"=",
"$",
"types",
";",
"}",
"$",
"query",
"->",
"setParameters",
"(",
"$",
"parameters",
")",
";",
"return",
"$",
"query",
"->",
"getQuery",
"(",
")",
"->",
"execute",
"(",
")",
";",
"}"
] | Retrieve messages with given type(s) and restrict to max attempts count.
@param array $types
@param int $maxAttempts
@return array | [
"Retrieve",
"messages",
"with",
"given",
"type",
"(",
"s",
")",
"and",
"restrict",
"to",
"max",
"attempts",
"count",
"."
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Selector/ErroneousMessagesSelector.php#L49-L69 |
sonata-project/SonataNotificationBundle | src/Consumer/LoggerConsumer.php | LoggerConsumer.process | public function process(ConsumerEvent $event)
{
$message = $event->getMessage();
if (!\array_key_exists($message->getValue('level'), $this->types)) {
throw new InvalidParameterException();
}
$level = $this->types[$message->getValue('level')];
$this->logger->{$level}($message->getValue('message'));
} | php | public function process(ConsumerEvent $event)
{
$message = $event->getMessage();
if (!\array_key_exists($message->getValue('level'), $this->types)) {
throw new InvalidParameterException();
}
$level = $this->types[$message->getValue('level')];
$this->logger->{$level}($message->getValue('message'));
} | [
"public",
"function",
"process",
"(",
"ConsumerEvent",
"$",
"event",
")",
"{",
"$",
"message",
"=",
"$",
"event",
"->",
"getMessage",
"(",
")",
";",
"if",
"(",
"!",
"\\",
"array_key_exists",
"(",
"$",
"message",
"->",
"getValue",
"(",
"'level'",
")",
",",
"$",
"this",
"->",
"types",
")",
")",
"{",
"throw",
"new",
"InvalidParameterException",
"(",
")",
";",
"}",
"$",
"level",
"=",
"$",
"this",
"->",
"types",
"[",
"$",
"message",
"->",
"getValue",
"(",
"'level'",
")",
"]",
";",
"$",
"this",
"->",
"logger",
"->",
"{",
"$",
"level",
"}",
"(",
"$",
"message",
"->",
"getValue",
"(",
"'message'",
")",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Consumer/LoggerConsumer.php#L61-L72 |
sonata-project/SonataNotificationBundle | src/DependencyInjection/Compiler/NotificationCompilerPass.php | NotificationCompilerPass.process | public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('sonata.notification.dispatcher')) {
return;
}
$definition = $container->getDefinition('sonata.notification.dispatcher');
$informations = [];
foreach ($container->findTaggedServiceIds('sonata.notification.consumer') as $id => $events) {
$container->getDefinition($id)->setPublic(true);
foreach ($events as $event) {
$priority = $event['priority'] ?? 0;
if (!isset($event['type'])) {
throw new \InvalidArgumentException(sprintf(
'Service "%s" must define the "type" attribute on "sonata.notification" tags.',
$id
));
}
if (!isset($informations[$event['type']])) {
$informations[$event['type']] = [];
}
$informations[$event['type']][] = $id;
/*
* NEXT_MAJOR: Remove check for ServiceClosureArgument and the addListenerService method call.
*/
if (class_exists(ServiceClosureArgument::class)) {
$definition->addMethodCall(
'addListener',
[
$event['type'],
[new ServiceClosureArgument(new Reference($id)), 'process'],
$priority,
]
);
} else {
$definition->addMethodCall(
'addListenerService',
[
$event['type'],
[$id, 'process'],
$priority,
]
);
}
}
}
$container->getDefinition('sonata.notification.consumer.metadata')->replaceArgument(0, $informations);
if ($container->getParameter('sonata.notification.event.iteration_listeners')) {
$ids = $container->getParameter('sonata.notification.event.iteration_listeners');
foreach ($ids as $serviceId) {
$definition = $container->getDefinition($serviceId);
$class = new \ReflectionClass($definition->getClass());
if (!$class->implementsInterface(IterationListener::class)) {
throw new RuntimeException(
'Iteration listeners must implement Sonata\NotificationBundle\Event\IterationListener'
);
}
$definition->addTag(
'kernel.event_listener',
['event' => IterateEvent::EVENT_NAME, 'method' => 'iterate']
);
}
}
} | php | public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('sonata.notification.dispatcher')) {
return;
}
$definition = $container->getDefinition('sonata.notification.dispatcher');
$informations = [];
foreach ($container->findTaggedServiceIds('sonata.notification.consumer') as $id => $events) {
$container->getDefinition($id)->setPublic(true);
foreach ($events as $event) {
$priority = $event['priority'] ?? 0;
if (!isset($event['type'])) {
throw new \InvalidArgumentException(sprintf(
'Service "%s" must define the "type" attribute on "sonata.notification" tags.',
$id
));
}
if (!isset($informations[$event['type']])) {
$informations[$event['type']] = [];
}
$informations[$event['type']][] = $id;
/*
* NEXT_MAJOR: Remove check for ServiceClosureArgument and the addListenerService method call.
*/
if (class_exists(ServiceClosureArgument::class)) {
$definition->addMethodCall(
'addListener',
[
$event['type'],
[new ServiceClosureArgument(new Reference($id)), 'process'],
$priority,
]
);
} else {
$definition->addMethodCall(
'addListenerService',
[
$event['type'],
[$id, 'process'],
$priority,
]
);
}
}
}
$container->getDefinition('sonata.notification.consumer.metadata')->replaceArgument(0, $informations);
if ($container->getParameter('sonata.notification.event.iteration_listeners')) {
$ids = $container->getParameter('sonata.notification.event.iteration_listeners');
foreach ($ids as $serviceId) {
$definition = $container->getDefinition($serviceId);
$class = new \ReflectionClass($definition->getClass());
if (!$class->implementsInterface(IterationListener::class)) {
throw new RuntimeException(
'Iteration listeners must implement Sonata\NotificationBundle\Event\IterationListener'
);
}
$definition->addTag(
'kernel.event_listener',
['event' => IterateEvent::EVENT_NAME, 'method' => 'iterate']
);
}
}
} | [
"public",
"function",
"process",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"if",
"(",
"!",
"$",
"container",
"->",
"hasDefinition",
"(",
"'sonata.notification.dispatcher'",
")",
")",
"{",
"return",
";",
"}",
"$",
"definition",
"=",
"$",
"container",
"->",
"getDefinition",
"(",
"'sonata.notification.dispatcher'",
")",
";",
"$",
"informations",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"container",
"->",
"findTaggedServiceIds",
"(",
"'sonata.notification.consumer'",
")",
"as",
"$",
"id",
"=>",
"$",
"events",
")",
"{",
"$",
"container",
"->",
"getDefinition",
"(",
"$",
"id",
")",
"->",
"setPublic",
"(",
"true",
")",
";",
"foreach",
"(",
"$",
"events",
"as",
"$",
"event",
")",
"{",
"$",
"priority",
"=",
"$",
"event",
"[",
"'priority'",
"]",
"??",
"0",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"event",
"[",
"'type'",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Service \"%s\" must define the \"type\" attribute on \"sonata.notification\" tags.'",
",",
"$",
"id",
")",
")",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"informations",
"[",
"$",
"event",
"[",
"'type'",
"]",
"]",
")",
")",
"{",
"$",
"informations",
"[",
"$",
"event",
"[",
"'type'",
"]",
"]",
"=",
"[",
"]",
";",
"}",
"$",
"informations",
"[",
"$",
"event",
"[",
"'type'",
"]",
"]",
"[",
"]",
"=",
"$",
"id",
";",
"/*\n * NEXT_MAJOR: Remove check for ServiceClosureArgument and the addListenerService method call.\n */",
"if",
"(",
"class_exists",
"(",
"ServiceClosureArgument",
"::",
"class",
")",
")",
"{",
"$",
"definition",
"->",
"addMethodCall",
"(",
"'addListener'",
",",
"[",
"$",
"event",
"[",
"'type'",
"]",
",",
"[",
"new",
"ServiceClosureArgument",
"(",
"new",
"Reference",
"(",
"$",
"id",
")",
")",
",",
"'process'",
"]",
",",
"$",
"priority",
",",
"]",
")",
";",
"}",
"else",
"{",
"$",
"definition",
"->",
"addMethodCall",
"(",
"'addListenerService'",
",",
"[",
"$",
"event",
"[",
"'type'",
"]",
",",
"[",
"$",
"id",
",",
"'process'",
"]",
",",
"$",
"priority",
",",
"]",
")",
";",
"}",
"}",
"}",
"$",
"container",
"->",
"getDefinition",
"(",
"'sonata.notification.consumer.metadata'",
")",
"->",
"replaceArgument",
"(",
"0",
",",
"$",
"informations",
")",
";",
"if",
"(",
"$",
"container",
"->",
"getParameter",
"(",
"'sonata.notification.event.iteration_listeners'",
")",
")",
"{",
"$",
"ids",
"=",
"$",
"container",
"->",
"getParameter",
"(",
"'sonata.notification.event.iteration_listeners'",
")",
";",
"foreach",
"(",
"$",
"ids",
"as",
"$",
"serviceId",
")",
"{",
"$",
"definition",
"=",
"$",
"container",
"->",
"getDefinition",
"(",
"$",
"serviceId",
")",
";",
"$",
"class",
"=",
"new",
"\\",
"ReflectionClass",
"(",
"$",
"definition",
"->",
"getClass",
"(",
")",
")",
";",
"if",
"(",
"!",
"$",
"class",
"->",
"implementsInterface",
"(",
"IterationListener",
"::",
"class",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Iteration listeners must implement Sonata\\NotificationBundle\\Event\\IterationListener'",
")",
";",
"}",
"$",
"definition",
"->",
"addTag",
"(",
"'kernel.event_listener'",
",",
"[",
"'event'",
"=>",
"IterateEvent",
"::",
"EVENT_NAME",
",",
"'method'",
"=>",
"'iterate'",
"]",
")",
";",
"}",
"}",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/DependencyInjection/Compiler/NotificationCompilerPass.php#L29-L104 |
sonata-project/SonataNotificationBundle | src/Controller/Api/MessageController.php | MessageController.postMessageAction | public function postMessageAction(Request $request)
{
$message = null;
$form = $this->formFactory->createNamed(null, 'sonata_notification_api_form_message', $message, [
'csrf_protection' => false,
]);
$form->handleRequest($request);
if ($form->isValid()) {
$message = $form->getData();
$this->messageManager->save($message);
return $message;
}
return $form;
} | php | public function postMessageAction(Request $request)
{
$message = null;
$form = $this->formFactory->createNamed(null, 'sonata_notification_api_form_message', $message, [
'csrf_protection' => false,
]);
$form->handleRequest($request);
if ($form->isValid()) {
$message = $form->getData();
$this->messageManager->save($message);
return $message;
}
return $form;
} | [
"public",
"function",
"postMessageAction",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"message",
"=",
"null",
";",
"$",
"form",
"=",
"$",
"this",
"->",
"formFactory",
"->",
"createNamed",
"(",
"null",
",",
"'sonata_notification_api_form_message'",
",",
"$",
"message",
",",
"[",
"'csrf_protection'",
"=>",
"false",
",",
"]",
")",
";",
"$",
"form",
"->",
"handleRequest",
"(",
"$",
"request",
")",
";",
"if",
"(",
"$",
"form",
"->",
"isValid",
"(",
")",
")",
"{",
"$",
"message",
"=",
"$",
"form",
"->",
"getData",
"(",
")",
";",
"$",
"this",
"->",
"messageManager",
"->",
"save",
"(",
"$",
"message",
")",
";",
"return",
"$",
"message",
";",
"}",
"return",
"$",
"form",
";",
"}"
] | Adds a message.
@ApiDoc(
input={"class"="sonata_notification_api_form_message", "name"="", "groups"={"sonata_api_write"}},
output={"class"="Sonata\NotificationBundle\Model\Message", "groups"={"sonata_api_read"}},
statusCodes={
200="Returned when successful",
400="Returned when an error has occurred while message creation"
}
)
@View(serializerGroups={"sonata_api_read"}, serializerEnableMaxDepthChecks=true)
@Route(requirements={"_format"="json|xml"})
@param Request $request A Symfony request
@return MessageInterface | [
"Adds",
"a",
"message",
"."
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Controller/Api/MessageController.php#L119-L137 |
sonata-project/SonataNotificationBundle | src/Command/ConsumerHandlerCommand.php | ConsumerHandlerCommand.execute | public function execute(InputInterface $input, OutputInterface $output)
{
$startDate = new \DateTime();
$output->writeln(sprintf('[%s] <info>Checking listeners</info>', $startDate->format('r')));
foreach ($this->getNotificationDispatcher()->getListeners() as $type => $listeners) {
$output->writeln(sprintf(' - %s', $type));
foreach ($listeners as $listener) {
if (!$listener[0] instanceof ConsumerInterface) {
throw new \RuntimeException(sprintf(
'The registered service does not implement the ConsumerInterface (class=%s',
\get_class($listener[0])
));
}
$output->writeln(sprintf(' > %s', \get_class($listener[0])));
}
}
$type = $input->getOption('type');
$showDetails = $input->getOption('show-details');
$output->write(sprintf('[%s] <info>Retrieving backend</info> ...', $startDate->format('r')));
$backend = $this->getBackend($type);
$output->writeln('');
$output->write(sprintf('[%s] <info>Initialize backend</info> ...', $startDate->format('r')));
// initialize the backend
$backend->initialize();
$output->writeln(' done!');
if (null === $type) {
$output->writeln(sprintf(
'[%s] <info>Starting the backend handler</info> - %s',
$startDate->format('r'),
\get_class($backend)
));
} else {
$output->writeln(sprintf(
'[%s] <info>Starting the backend handler</info> - %s (type: %s)',
$startDate->format('r'),
\get_class($backend),
$type
));
}
$startMemoryUsage = memory_get_usage(true);
$i = 0;
$iterator = $backend->getIterator();
foreach ($iterator as $message) {
++$i;
if (!$message instanceof MessageInterface) {
throw new \RuntimeException('The iterator must return a MessageInterface instance');
}
if (!$message->getType()) {
$output->write('<error>Skipping : no type defined </error>');
continue;
}
$date = new \DateTime();
$output->write(sprintf('[%s] <info>%s</info> #%s: ', $date->format('r'), $message->getType(), $i));
$memoryUsage = memory_get_usage(true);
try {
$start = microtime(true);
$returnInfos = $backend->handle($message, $this->getNotificationDispatcher());
$currentMemory = memory_get_usage(true);
$output->writeln(sprintf('<comment>OK! </comment> - %0.04fs, %ss, %s, %s - %s = %s, %0.02f%%',
microtime(true) - $start,
$date->format('U') - $message->getCreatedAt()->format('U'),
$this->formatMemory($currentMemory - $memoryUsage),
$this->formatMemory($currentMemory),
$this->formatMemory($startMemoryUsage),
$this->formatMemory($currentMemory - $startMemoryUsage),
($currentMemory - $startMemoryUsage) / $startMemoryUsage * 100
));
if ($showDetails && null !== $returnInfos) {
$output->writeln($returnInfos->getReturnMessage());
}
} catch (HandlingException $e) {
$output->writeln(sprintf('<error>KO! - %s</error>', $e->getPrevious()->getMessage()));
} catch (\Exception $e) {
$output->writeln(sprintf('<error>KO! - %s</error>', $e->getMessage()));
}
$this->getEventDispatcher()->dispatch(
IterateEvent::EVENT_NAME,
new IterateEvent($iterator, $backend, $message)
);
if ($input->getOption('iteration') && $i >= (int) $input->getOption('iteration')) {
$output->writeln('End of iteration cycle');
return;
}
}
} | php | public function execute(InputInterface $input, OutputInterface $output)
{
$startDate = new \DateTime();
$output->writeln(sprintf('[%s] <info>Checking listeners</info>', $startDate->format('r')));
foreach ($this->getNotificationDispatcher()->getListeners() as $type => $listeners) {
$output->writeln(sprintf(' - %s', $type));
foreach ($listeners as $listener) {
if (!$listener[0] instanceof ConsumerInterface) {
throw new \RuntimeException(sprintf(
'The registered service does not implement the ConsumerInterface (class=%s',
\get_class($listener[0])
));
}
$output->writeln(sprintf(' > %s', \get_class($listener[0])));
}
}
$type = $input->getOption('type');
$showDetails = $input->getOption('show-details');
$output->write(sprintf('[%s] <info>Retrieving backend</info> ...', $startDate->format('r')));
$backend = $this->getBackend($type);
$output->writeln('');
$output->write(sprintf('[%s] <info>Initialize backend</info> ...', $startDate->format('r')));
// initialize the backend
$backend->initialize();
$output->writeln(' done!');
if (null === $type) {
$output->writeln(sprintf(
'[%s] <info>Starting the backend handler</info> - %s',
$startDate->format('r'),
\get_class($backend)
));
} else {
$output->writeln(sprintf(
'[%s] <info>Starting the backend handler</info> - %s (type: %s)',
$startDate->format('r'),
\get_class($backend),
$type
));
}
$startMemoryUsage = memory_get_usage(true);
$i = 0;
$iterator = $backend->getIterator();
foreach ($iterator as $message) {
++$i;
if (!$message instanceof MessageInterface) {
throw new \RuntimeException('The iterator must return a MessageInterface instance');
}
if (!$message->getType()) {
$output->write('<error>Skipping : no type defined </error>');
continue;
}
$date = new \DateTime();
$output->write(sprintf('[%s] <info>%s</info> #%s: ', $date->format('r'), $message->getType(), $i));
$memoryUsage = memory_get_usage(true);
try {
$start = microtime(true);
$returnInfos = $backend->handle($message, $this->getNotificationDispatcher());
$currentMemory = memory_get_usage(true);
$output->writeln(sprintf('<comment>OK! </comment> - %0.04fs, %ss, %s, %s - %s = %s, %0.02f%%',
microtime(true) - $start,
$date->format('U') - $message->getCreatedAt()->format('U'),
$this->formatMemory($currentMemory - $memoryUsage),
$this->formatMemory($currentMemory),
$this->formatMemory($startMemoryUsage),
$this->formatMemory($currentMemory - $startMemoryUsage),
($currentMemory - $startMemoryUsage) / $startMemoryUsage * 100
));
if ($showDetails && null !== $returnInfos) {
$output->writeln($returnInfos->getReturnMessage());
}
} catch (HandlingException $e) {
$output->writeln(sprintf('<error>KO! - %s</error>', $e->getPrevious()->getMessage()));
} catch (\Exception $e) {
$output->writeln(sprintf('<error>KO! - %s</error>', $e->getMessage()));
}
$this->getEventDispatcher()->dispatch(
IterateEvent::EVENT_NAME,
new IterateEvent($iterator, $backend, $message)
);
if ($input->getOption('iteration') && $i >= (int) $input->getOption('iteration')) {
$output->writeln('End of iteration cycle');
return;
}
}
} | [
"public",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"startDate",
"=",
"new",
"\\",
"DateTime",
"(",
")",
";",
"$",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'[%s] <info>Checking listeners</info>'",
",",
"$",
"startDate",
"->",
"format",
"(",
"'r'",
")",
")",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"getNotificationDispatcher",
"(",
")",
"->",
"getListeners",
"(",
")",
"as",
"$",
"type",
"=>",
"$",
"listeners",
")",
"{",
"$",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"' - %s'",
",",
"$",
"type",
")",
")",
";",
"foreach",
"(",
"$",
"listeners",
"as",
"$",
"listener",
")",
"{",
"if",
"(",
"!",
"$",
"listener",
"[",
"0",
"]",
"instanceof",
"ConsumerInterface",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"sprintf",
"(",
"'The registered service does not implement the ConsumerInterface (class=%s'",
",",
"\\",
"get_class",
"(",
"$",
"listener",
"[",
"0",
"]",
")",
")",
")",
";",
"}",
"$",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"' > %s'",
",",
"\\",
"get_class",
"(",
"$",
"listener",
"[",
"0",
"]",
")",
")",
")",
";",
"}",
"}",
"$",
"type",
"=",
"$",
"input",
"->",
"getOption",
"(",
"'type'",
")",
";",
"$",
"showDetails",
"=",
"$",
"input",
"->",
"getOption",
"(",
"'show-details'",
")",
";",
"$",
"output",
"->",
"write",
"(",
"sprintf",
"(",
"'[%s] <info>Retrieving backend</info> ...'",
",",
"$",
"startDate",
"->",
"format",
"(",
"'r'",
")",
")",
")",
";",
"$",
"backend",
"=",
"$",
"this",
"->",
"getBackend",
"(",
"$",
"type",
")",
";",
"$",
"output",
"->",
"writeln",
"(",
"''",
")",
";",
"$",
"output",
"->",
"write",
"(",
"sprintf",
"(",
"'[%s] <info>Initialize backend</info> ...'",
",",
"$",
"startDate",
"->",
"format",
"(",
"'r'",
")",
")",
")",
";",
"// initialize the backend",
"$",
"backend",
"->",
"initialize",
"(",
")",
";",
"$",
"output",
"->",
"writeln",
"(",
"' done!'",
")",
";",
"if",
"(",
"null",
"===",
"$",
"type",
")",
"{",
"$",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'[%s] <info>Starting the backend handler</info> - %s'",
",",
"$",
"startDate",
"->",
"format",
"(",
"'r'",
")",
",",
"\\",
"get_class",
"(",
"$",
"backend",
")",
")",
")",
";",
"}",
"else",
"{",
"$",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'[%s] <info>Starting the backend handler</info> - %s (type: %s)'",
",",
"$",
"startDate",
"->",
"format",
"(",
"'r'",
")",
",",
"\\",
"get_class",
"(",
"$",
"backend",
")",
",",
"$",
"type",
")",
")",
";",
"}",
"$",
"startMemoryUsage",
"=",
"memory_get_usage",
"(",
"true",
")",
";",
"$",
"i",
"=",
"0",
";",
"$",
"iterator",
"=",
"$",
"backend",
"->",
"getIterator",
"(",
")",
";",
"foreach",
"(",
"$",
"iterator",
"as",
"$",
"message",
")",
"{",
"++",
"$",
"i",
";",
"if",
"(",
"!",
"$",
"message",
"instanceof",
"MessageInterface",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'The iterator must return a MessageInterface instance'",
")",
";",
"}",
"if",
"(",
"!",
"$",
"message",
"->",
"getType",
"(",
")",
")",
"{",
"$",
"output",
"->",
"write",
"(",
"'<error>Skipping : no type defined </error>'",
")",
";",
"continue",
";",
"}",
"$",
"date",
"=",
"new",
"\\",
"DateTime",
"(",
")",
";",
"$",
"output",
"->",
"write",
"(",
"sprintf",
"(",
"'[%s] <info>%s</info> #%s: '",
",",
"$",
"date",
"->",
"format",
"(",
"'r'",
")",
",",
"$",
"message",
"->",
"getType",
"(",
")",
",",
"$",
"i",
")",
")",
";",
"$",
"memoryUsage",
"=",
"memory_get_usage",
"(",
"true",
")",
";",
"try",
"{",
"$",
"start",
"=",
"microtime",
"(",
"true",
")",
";",
"$",
"returnInfos",
"=",
"$",
"backend",
"->",
"handle",
"(",
"$",
"message",
",",
"$",
"this",
"->",
"getNotificationDispatcher",
"(",
")",
")",
";",
"$",
"currentMemory",
"=",
"memory_get_usage",
"(",
"true",
")",
";",
"$",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'<comment>OK! </comment> - %0.04fs, %ss, %s, %s - %s = %s, %0.02f%%'",
",",
"microtime",
"(",
"true",
")",
"-",
"$",
"start",
",",
"$",
"date",
"->",
"format",
"(",
"'U'",
")",
"-",
"$",
"message",
"->",
"getCreatedAt",
"(",
")",
"->",
"format",
"(",
"'U'",
")",
",",
"$",
"this",
"->",
"formatMemory",
"(",
"$",
"currentMemory",
"-",
"$",
"memoryUsage",
")",
",",
"$",
"this",
"->",
"formatMemory",
"(",
"$",
"currentMemory",
")",
",",
"$",
"this",
"->",
"formatMemory",
"(",
"$",
"startMemoryUsage",
")",
",",
"$",
"this",
"->",
"formatMemory",
"(",
"$",
"currentMemory",
"-",
"$",
"startMemoryUsage",
")",
",",
"(",
"$",
"currentMemory",
"-",
"$",
"startMemoryUsage",
")",
"/",
"$",
"startMemoryUsage",
"*",
"100",
")",
")",
";",
"if",
"(",
"$",
"showDetails",
"&&",
"null",
"!==",
"$",
"returnInfos",
")",
"{",
"$",
"output",
"->",
"writeln",
"(",
"$",
"returnInfos",
"->",
"getReturnMessage",
"(",
")",
")",
";",
"}",
"}",
"catch",
"(",
"HandlingException",
"$",
"e",
")",
"{",
"$",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'<error>KO! - %s</error>'",
",",
"$",
"e",
"->",
"getPrevious",
"(",
")",
"->",
"getMessage",
"(",
")",
")",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"$",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'<error>KO! - %s</error>'",
",",
"$",
"e",
"->",
"getMessage",
"(",
")",
")",
")",
";",
"}",
"$",
"this",
"->",
"getEventDispatcher",
"(",
")",
"->",
"dispatch",
"(",
"IterateEvent",
"::",
"EVENT_NAME",
",",
"new",
"IterateEvent",
"(",
"$",
"iterator",
",",
"$",
"backend",
",",
"$",
"message",
")",
")",
";",
"if",
"(",
"$",
"input",
"->",
"getOption",
"(",
"'iteration'",
")",
"&&",
"$",
"i",
">=",
"(",
"int",
")",
"$",
"input",
"->",
"getOption",
"(",
"'iteration'",
")",
")",
"{",
"$",
"output",
"->",
"writeln",
"(",
"'End of iteration cycle'",
")",
";",
"return",
";",
"}",
"}",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Command/ConsumerHandlerCommand.php#L44-L148 |
sonata-project/SonataNotificationBundle | src/Command/ConsumerHandlerCommand.php | ConsumerHandlerCommand.getBackend | private function getBackend($type = null)
{
$backend = $this->getContainer()->get('sonata.notification.backend');
if ($type && !\array_key_exists($type, $this->getNotificationDispatcher()->getListeners())) {
throw new \RuntimeException(sprintf('The type `%s` does not exist, available types: %s', $type, implode(', ', array_keys($this->getNotificationDispatcher()->getListeners()))));
}
if (null !== $type && !$backend instanceof QueueDispatcherInterface) {
throw new \RuntimeException(sprintf(
'Unable to use the provided type %s with a non QueueDispatcherInterface backend',
$type
));
}
if ($backend instanceof QueueDispatcherInterface) {
return $backend->getBackend($type);
}
return $backend;
} | php | private function getBackend($type = null)
{
$backend = $this->getContainer()->get('sonata.notification.backend');
if ($type && !\array_key_exists($type, $this->getNotificationDispatcher()->getListeners())) {
throw new \RuntimeException(sprintf('The type `%s` does not exist, available types: %s', $type, implode(', ', array_keys($this->getNotificationDispatcher()->getListeners()))));
}
if (null !== $type && !$backend instanceof QueueDispatcherInterface) {
throw new \RuntimeException(sprintf(
'Unable to use the provided type %s with a non QueueDispatcherInterface backend',
$type
));
}
if ($backend instanceof QueueDispatcherInterface) {
return $backend->getBackend($type);
}
return $backend;
} | [
"private",
"function",
"getBackend",
"(",
"$",
"type",
"=",
"null",
")",
"{",
"$",
"backend",
"=",
"$",
"this",
"->",
"getContainer",
"(",
")",
"->",
"get",
"(",
"'sonata.notification.backend'",
")",
";",
"if",
"(",
"$",
"type",
"&&",
"!",
"\\",
"array_key_exists",
"(",
"$",
"type",
",",
"$",
"this",
"->",
"getNotificationDispatcher",
"(",
")",
"->",
"getListeners",
"(",
")",
")",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"sprintf",
"(",
"'The type `%s` does not exist, available types: %s'",
",",
"$",
"type",
",",
"implode",
"(",
"', '",
",",
"array_keys",
"(",
"$",
"this",
"->",
"getNotificationDispatcher",
"(",
")",
"->",
"getListeners",
"(",
")",
")",
")",
")",
")",
";",
"}",
"if",
"(",
"null",
"!==",
"$",
"type",
"&&",
"!",
"$",
"backend",
"instanceof",
"QueueDispatcherInterface",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"sprintf",
"(",
"'Unable to use the provided type %s with a non QueueDispatcherInterface backend'",
",",
"$",
"type",
")",
")",
";",
"}",
"if",
"(",
"$",
"backend",
"instanceof",
"QueueDispatcherInterface",
")",
"{",
"return",
"$",
"backend",
"->",
"getBackend",
"(",
"$",
"type",
")",
";",
"}",
"return",
"$",
"backend",
";",
"}"
] | @param string $type
@return BackendInterface | [
"@param",
"string",
"$type"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Command/ConsumerHandlerCommand.php#L185-L205 |
sonata-project/SonataNotificationBundle | src/Entity/MessageManager.php | MessageManager.save | public function save($message, $andFlush = true)
{
//Hack for ConsumerHandlerCommand->optimize()
if ($message->getId() && !$this->em->getUnitOfWork()->isInIdentityMap($message)) {
$message = $this->getEntityManager()->getUnitOfWork()->merge($message);
}
parent::save($message, $andFlush);
} | php | public function save($message, $andFlush = true)
{
//Hack for ConsumerHandlerCommand->optimize()
if ($message->getId() && !$this->em->getUnitOfWork()->isInIdentityMap($message)) {
$message = $this->getEntityManager()->getUnitOfWork()->merge($message);
}
parent::save($message, $andFlush);
} | [
"public",
"function",
"save",
"(",
"$",
"message",
",",
"$",
"andFlush",
"=",
"true",
")",
"{",
"//Hack for ConsumerHandlerCommand->optimize()",
"if",
"(",
"$",
"message",
"->",
"getId",
"(",
")",
"&&",
"!",
"$",
"this",
"->",
"em",
"->",
"getUnitOfWork",
"(",
")",
"->",
"isInIdentityMap",
"(",
"$",
"message",
")",
")",
"{",
"$",
"message",
"=",
"$",
"this",
"->",
"getEntityManager",
"(",
")",
"->",
"getUnitOfWork",
"(",
")",
"->",
"merge",
"(",
"$",
"message",
")",
";",
"}",
"parent",
"::",
"save",
"(",
"$",
"message",
",",
"$",
"andFlush",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Entity/MessageManager.php#L28-L36 |
sonata-project/SonataNotificationBundle | src/Entity/MessageManager.php | MessageManager.findByTypes | public function findByTypes(array $types, $state, $batchSize)
{
$params = [];
$query = $this->prepareStateQuery($state, $types, $batchSize, $params);
$query->setParameters($params);
return $query->getQuery()->execute();
} | php | public function findByTypes(array $types, $state, $batchSize)
{
$params = [];
$query = $this->prepareStateQuery($state, $types, $batchSize, $params);
$query->setParameters($params);
return $query->getQuery()->execute();
} | [
"public",
"function",
"findByTypes",
"(",
"array",
"$",
"types",
",",
"$",
"state",
",",
"$",
"batchSize",
")",
"{",
"$",
"params",
"=",
"[",
"]",
";",
"$",
"query",
"=",
"$",
"this",
"->",
"prepareStateQuery",
"(",
"$",
"state",
",",
"$",
"types",
",",
"$",
"batchSize",
",",
"$",
"params",
")",
";",
"$",
"query",
"->",
"setParameters",
"(",
"$",
"params",
")",
";",
"return",
"$",
"query",
"->",
"getQuery",
"(",
")",
"->",
"execute",
"(",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Entity/MessageManager.php#L41-L49 |
sonata-project/SonataNotificationBundle | src/Entity/MessageManager.php | MessageManager.findByAttempts | public function findByAttempts(array $types, $state, $batchSize, $maxAttempts = null, $attemptDelay = 10)
{
$params = [];
$query = $this->prepareStateQuery($state, $types, $batchSize, $params);
if ($maxAttempts) {
$query
->andWhere('m.restartCount < :maxAttempts')
->andWhere('m.updatedAt < :delayDate');
$params['maxAttempts'] = $maxAttempts;
$now = new \DateTime();
$params['delayDate'] = $now->add(\DateInterval::createFromDateString(($attemptDelay * -1).' second'));
}
$query->setParameters($params);
return $query->getQuery()->execute();
} | php | public function findByAttempts(array $types, $state, $batchSize, $maxAttempts = null, $attemptDelay = 10)
{
$params = [];
$query = $this->prepareStateQuery($state, $types, $batchSize, $params);
if ($maxAttempts) {
$query
->andWhere('m.restartCount < :maxAttempts')
->andWhere('m.updatedAt < :delayDate');
$params['maxAttempts'] = $maxAttempts;
$now = new \DateTime();
$params['delayDate'] = $now->add(\DateInterval::createFromDateString(($attemptDelay * -1).' second'));
}
$query->setParameters($params);
return $query->getQuery()->execute();
} | [
"public",
"function",
"findByAttempts",
"(",
"array",
"$",
"types",
",",
"$",
"state",
",",
"$",
"batchSize",
",",
"$",
"maxAttempts",
"=",
"null",
",",
"$",
"attemptDelay",
"=",
"10",
")",
"{",
"$",
"params",
"=",
"[",
"]",
";",
"$",
"query",
"=",
"$",
"this",
"->",
"prepareStateQuery",
"(",
"$",
"state",
",",
"$",
"types",
",",
"$",
"batchSize",
",",
"$",
"params",
")",
";",
"if",
"(",
"$",
"maxAttempts",
")",
"{",
"$",
"query",
"->",
"andWhere",
"(",
"'m.restartCount < :maxAttempts'",
")",
"->",
"andWhere",
"(",
"'m.updatedAt < :delayDate'",
")",
";",
"$",
"params",
"[",
"'maxAttempts'",
"]",
"=",
"$",
"maxAttempts",
";",
"$",
"now",
"=",
"new",
"\\",
"DateTime",
"(",
")",
";",
"$",
"params",
"[",
"'delayDate'",
"]",
"=",
"$",
"now",
"->",
"add",
"(",
"\\",
"DateInterval",
"::",
"createFromDateString",
"(",
"(",
"$",
"attemptDelay",
"*",
"-",
"1",
")",
".",
"' second'",
")",
")",
";",
"}",
"$",
"query",
"->",
"setParameters",
"(",
"$",
"params",
")",
";",
"return",
"$",
"query",
"->",
"getQuery",
"(",
")",
"->",
"execute",
"(",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Entity/MessageManager.php#L54-L72 |
sonata-project/SonataNotificationBundle | src/Entity/MessageManager.php | MessageManager.countStates | public function countStates()
{
$tableName = $this->getEntityManager()->getClassMetadata($this->class)->table['name'];
$stm = $this->getConnection()->query(
sprintf('SELECT state, count(state) as cnt FROM %s GROUP BY state', $tableName)
);
$states = [
MessageInterface::STATE_DONE => 0,
MessageInterface::STATE_ERROR => 0,
MessageInterface::STATE_IN_PROGRESS => 0,
MessageInterface::STATE_OPEN => 0,
];
while ($data = $stm->fetch()) {
$states[$data['state']] = $data['cnt'];
}
return $states;
} | php | public function countStates()
{
$tableName = $this->getEntityManager()->getClassMetadata($this->class)->table['name'];
$stm = $this->getConnection()->query(
sprintf('SELECT state, count(state) as cnt FROM %s GROUP BY state', $tableName)
);
$states = [
MessageInterface::STATE_DONE => 0,
MessageInterface::STATE_ERROR => 0,
MessageInterface::STATE_IN_PROGRESS => 0,
MessageInterface::STATE_OPEN => 0,
];
while ($data = $stm->fetch()) {
$states[$data['state']] = $data['cnt'];
}
return $states;
} | [
"public",
"function",
"countStates",
"(",
")",
"{",
"$",
"tableName",
"=",
"$",
"this",
"->",
"getEntityManager",
"(",
")",
"->",
"getClassMetadata",
"(",
"$",
"this",
"->",
"class",
")",
"->",
"table",
"[",
"'name'",
"]",
";",
"$",
"stm",
"=",
"$",
"this",
"->",
"getConnection",
"(",
")",
"->",
"query",
"(",
"sprintf",
"(",
"'SELECT state, count(state) as cnt FROM %s GROUP BY state'",
",",
"$",
"tableName",
")",
")",
";",
"$",
"states",
"=",
"[",
"MessageInterface",
"::",
"STATE_DONE",
"=>",
"0",
",",
"MessageInterface",
"::",
"STATE_ERROR",
"=>",
"0",
",",
"MessageInterface",
"::",
"STATE_IN_PROGRESS",
"=>",
"0",
",",
"MessageInterface",
"::",
"STATE_OPEN",
"=>",
"0",
",",
"]",
";",
"while",
"(",
"$",
"data",
"=",
"$",
"stm",
"->",
"fetch",
"(",
")",
")",
"{",
"$",
"states",
"[",
"$",
"data",
"[",
"'state'",
"]",
"]",
"=",
"$",
"data",
"[",
"'cnt'",
"]",
";",
"}",
"return",
"$",
"states",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Entity/MessageManager.php#L77-L97 |
sonata-project/SonataNotificationBundle | src/Entity/MessageManager.php | MessageManager.cleanup | public function cleanup($maxAge)
{
$tableName = $this->getEntityManager()->getClassMetadata($this->class)->table['name'];
$date = new \DateTime('now');
$date->sub(new \DateInterval(sprintf('PT%sS', $maxAge)));
$qb = $this->getRepository()->createQueryBuilder('message')
->delete()
->where('message.state = :state')
->andWhere('message.completedAt < :date')
->setParameter('state', MessageInterface::STATE_DONE)
->setParameter('date', $date);
$qb->getQuery()->execute();
} | php | public function cleanup($maxAge)
{
$tableName = $this->getEntityManager()->getClassMetadata($this->class)->table['name'];
$date = new \DateTime('now');
$date->sub(new \DateInterval(sprintf('PT%sS', $maxAge)));
$qb = $this->getRepository()->createQueryBuilder('message')
->delete()
->where('message.state = :state')
->andWhere('message.completedAt < :date')
->setParameter('state', MessageInterface::STATE_DONE)
->setParameter('date', $date);
$qb->getQuery()->execute();
} | [
"public",
"function",
"cleanup",
"(",
"$",
"maxAge",
")",
"{",
"$",
"tableName",
"=",
"$",
"this",
"->",
"getEntityManager",
"(",
")",
"->",
"getClassMetadata",
"(",
"$",
"this",
"->",
"class",
")",
"->",
"table",
"[",
"'name'",
"]",
";",
"$",
"date",
"=",
"new",
"\\",
"DateTime",
"(",
"'now'",
")",
";",
"$",
"date",
"->",
"sub",
"(",
"new",
"\\",
"DateInterval",
"(",
"sprintf",
"(",
"'PT%sS'",
",",
"$",
"maxAge",
")",
")",
")",
";",
"$",
"qb",
"=",
"$",
"this",
"->",
"getRepository",
"(",
")",
"->",
"createQueryBuilder",
"(",
"'message'",
")",
"->",
"delete",
"(",
")",
"->",
"where",
"(",
"'message.state = :state'",
")",
"->",
"andWhere",
"(",
"'message.completedAt < :date'",
")",
"->",
"setParameter",
"(",
"'state'",
",",
"MessageInterface",
"::",
"STATE_DONE",
")",
"->",
"setParameter",
"(",
"'date'",
",",
"$",
"date",
")",
";",
"$",
"qb",
"->",
"getQuery",
"(",
")",
"->",
"execute",
"(",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Entity/MessageManager.php#L102-L117 |
sonata-project/SonataNotificationBundle | src/Entity/MessageManager.php | MessageManager.cancel | public function cancel(MessageInterface $message, $force = false)
{
if (($message->isRunning() || $message->isError()) && !$force) {
return;
}
$message->setState(MessageInterface::STATE_CANCELLED);
$this->save($message);
} | php | public function cancel(MessageInterface $message, $force = false)
{
if (($message->isRunning() || $message->isError()) && !$force) {
return;
}
$message->setState(MessageInterface::STATE_CANCELLED);
$this->save($message);
} | [
"public",
"function",
"cancel",
"(",
"MessageInterface",
"$",
"message",
",",
"$",
"force",
"=",
"false",
")",
"{",
"if",
"(",
"(",
"$",
"message",
"->",
"isRunning",
"(",
")",
"||",
"$",
"message",
"->",
"isError",
"(",
")",
")",
"&&",
"!",
"$",
"force",
")",
"{",
"return",
";",
"}",
"$",
"message",
"->",
"setState",
"(",
"MessageInterface",
"::",
"STATE_CANCELLED",
")",
";",
"$",
"this",
"->",
"save",
"(",
"$",
"message",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Entity/MessageManager.php#L122-L131 |
sonata-project/SonataNotificationBundle | src/Entity/MessageManager.php | MessageManager.restart | public function restart(MessageInterface $message)
{
if ($message->isOpen() || $message->isRunning() || $message->isCancelled()) {
return;
}
$this->cancel($message, true);
$newMessage = clone $message;
$newMessage->setRestartCount($message->getRestartCount() + 1);
$newMessage->setType($message->getType());
return $newMessage;
} | php | public function restart(MessageInterface $message)
{
if ($message->isOpen() || $message->isRunning() || $message->isCancelled()) {
return;
}
$this->cancel($message, true);
$newMessage = clone $message;
$newMessage->setRestartCount($message->getRestartCount() + 1);
$newMessage->setType($message->getType());
return $newMessage;
} | [
"public",
"function",
"restart",
"(",
"MessageInterface",
"$",
"message",
")",
"{",
"if",
"(",
"$",
"message",
"->",
"isOpen",
"(",
")",
"||",
"$",
"message",
"->",
"isRunning",
"(",
")",
"||",
"$",
"message",
"->",
"isCancelled",
"(",
")",
")",
"{",
"return",
";",
"}",
"$",
"this",
"->",
"cancel",
"(",
"$",
"message",
",",
"true",
")",
";",
"$",
"newMessage",
"=",
"clone",
"$",
"message",
";",
"$",
"newMessage",
"->",
"setRestartCount",
"(",
"$",
"message",
"->",
"getRestartCount",
"(",
")",
"+",
"1",
")",
";",
"$",
"newMessage",
"->",
"setType",
"(",
"$",
"message",
"->",
"getType",
"(",
")",
")",
";",
"return",
"$",
"newMessage",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Entity/MessageManager.php#L136-L149 |
sonata-project/SonataNotificationBundle | src/Entity/MessageManager.php | MessageManager.prepareStateQuery | protected function prepareStateQuery($state, $types, $batchSize, &$parameters)
{
$query = $this->getRepository()
->createQueryBuilder('m')
->where('m.state = :state')
->orderBy('m.createdAt');
$parameters['state'] = $state;
if (\count($types) > 0) {
if (\array_key_exists('exclude', $types) || \array_key_exists('include', $types)) {
if (\array_key_exists('exclude', $types)) {
$query->andWhere('m.type NOT IN (:exclude)');
$parameters['exclude'] = $types['exclude'];
}
if (\array_key_exists('include', $types)) {
$query->andWhere('m.type IN (:include)');
$parameters['include'] = $types['include'];
}
} else { // BC
$query->andWhere('m.type IN (:types)');
$parameters['types'] = $types;
}
}
$query->setMaxResults($batchSize);
return $query;
} | php | protected function prepareStateQuery($state, $types, $batchSize, &$parameters)
{
$query = $this->getRepository()
->createQueryBuilder('m')
->where('m.state = :state')
->orderBy('m.createdAt');
$parameters['state'] = $state;
if (\count($types) > 0) {
if (\array_key_exists('exclude', $types) || \array_key_exists('include', $types)) {
if (\array_key_exists('exclude', $types)) {
$query->andWhere('m.type NOT IN (:exclude)');
$parameters['exclude'] = $types['exclude'];
}
if (\array_key_exists('include', $types)) {
$query->andWhere('m.type IN (:include)');
$parameters['include'] = $types['include'];
}
} else { // BC
$query->andWhere('m.type IN (:types)');
$parameters['types'] = $types;
}
}
$query->setMaxResults($batchSize);
return $query;
} | [
"protected",
"function",
"prepareStateQuery",
"(",
"$",
"state",
",",
"$",
"types",
",",
"$",
"batchSize",
",",
"&",
"$",
"parameters",
")",
"{",
"$",
"query",
"=",
"$",
"this",
"->",
"getRepository",
"(",
")",
"->",
"createQueryBuilder",
"(",
"'m'",
")",
"->",
"where",
"(",
"'m.state = :state'",
")",
"->",
"orderBy",
"(",
"'m.createdAt'",
")",
";",
"$",
"parameters",
"[",
"'state'",
"]",
"=",
"$",
"state",
";",
"if",
"(",
"\\",
"count",
"(",
"$",
"types",
")",
">",
"0",
")",
"{",
"if",
"(",
"\\",
"array_key_exists",
"(",
"'exclude'",
",",
"$",
"types",
")",
"||",
"\\",
"array_key_exists",
"(",
"'include'",
",",
"$",
"types",
")",
")",
"{",
"if",
"(",
"\\",
"array_key_exists",
"(",
"'exclude'",
",",
"$",
"types",
")",
")",
"{",
"$",
"query",
"->",
"andWhere",
"(",
"'m.type NOT IN (:exclude)'",
")",
";",
"$",
"parameters",
"[",
"'exclude'",
"]",
"=",
"$",
"types",
"[",
"'exclude'",
"]",
";",
"}",
"if",
"(",
"\\",
"array_key_exists",
"(",
"'include'",
",",
"$",
"types",
")",
")",
"{",
"$",
"query",
"->",
"andWhere",
"(",
"'m.type IN (:include)'",
")",
";",
"$",
"parameters",
"[",
"'include'",
"]",
"=",
"$",
"types",
"[",
"'include'",
"]",
";",
"}",
"}",
"else",
"{",
"// BC",
"$",
"query",
"->",
"andWhere",
"(",
"'m.type IN (:types)'",
")",
";",
"$",
"parameters",
"[",
"'types'",
"]",
"=",
"$",
"types",
";",
"}",
"}",
"$",
"query",
"->",
"setMaxResults",
"(",
"$",
"batchSize",
")",
";",
"return",
"$",
"query",
";",
"}"
] | @param int $state
@param array $types
@param int $batchSize
@param array $parameters
@return QueryBuilder | [
"@param",
"int",
"$state",
"@param",
"array",
"$types",
"@param",
"int",
"$batchSize",
"@param",
"array",
"$parameters"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Entity/MessageManager.php#L204-L233 |
sonata-project/SonataNotificationBundle | src/Model/Message.php | Message.getValue | public function getValue($names, $default = null)
{
if (!\is_array($names)) {
$names = [$names];
}
$body = $this->getBody();
foreach ($names as $name) {
if (!isset($body[$name])) {
return $default;
}
$body = $body[$name];
}
return $body;
} | php | public function getValue($names, $default = null)
{
if (!\is_array($names)) {
$names = [$names];
}
$body = $this->getBody();
foreach ($names as $name) {
if (!isset($body[$name])) {
return $default;
}
$body = $body[$name];
}
return $body;
} | [
"public",
"function",
"getValue",
"(",
"$",
"names",
",",
"$",
"default",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"\\",
"is_array",
"(",
"$",
"names",
")",
")",
"{",
"$",
"names",
"=",
"[",
"$",
"names",
"]",
";",
"}",
"$",
"body",
"=",
"$",
"this",
"->",
"getBody",
"(",
")",
";",
"foreach",
"(",
"$",
"names",
"as",
"$",
"name",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"body",
"[",
"$",
"name",
"]",
")",
")",
"{",
"return",
"$",
"default",
";",
"}",
"$",
"body",
"=",
"$",
"body",
"[",
"$",
"name",
"]",
";",
"}",
"return",
"$",
"body",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Model/Message.php#L102-L118 |
sonata-project/SonataNotificationBundle | src/Model/Message.php | Message.getStateName | public function getStateName()
{
$list = self::getStateList();
return isset($list[$this->getState()]) ? $list[$this->getState()] : '';
} | php | public function getStateName()
{
$list = self::getStateList();
return isset($list[$this->getState()]) ? $list[$this->getState()] : '';
} | [
"public",
"function",
"getStateName",
"(",
")",
"{",
"$",
"list",
"=",
"self",
"::",
"getStateList",
"(",
")",
";",
"return",
"isset",
"(",
"$",
"list",
"[",
"$",
"this",
"->",
"getState",
"(",
")",
"]",
")",
"?",
"$",
"list",
"[",
"$",
"this",
"->",
"getState",
"(",
")",
"]",
":",
"''",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Model/Message.php#L265-L270 |
sonata-project/SonataNotificationBundle | src/Command/RestartCommand.php | RestartCommand.execute | public function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln('<info>Starting... </info>');
if (!is_numeric($input->getOption('max-attempts'))) {
throw new \Exception('Option "max-attempts" is invalid (integer value needed).');
}
$pullMode = $input->getOption('pulling');
$manager = $this->getMessageManager();
if ($pullMode) {
$messages = new ErroneousMessageIterator(
$manager,
$input->getOption('type'),
$input->getOption('pause'),
$input->getOption('batch-size'),
$input->getOption('max-attempts'),
$input->getOption('attempt-delay'));
} else {
$messages = $this->getErroneousMessageSelector()->getMessages(
$input->getOption('type'),
$input->getOption('max-attempts')
);
/*
* Check messages count only for not pulling mode
* to avoid PHP warning message
* since ErroneousMessageIterator does not implement Countable.
*/
if (0 === \count($messages)) {
$output->writeln('Nothing to restart, bye.');
return;
}
}
$eventDispatcher = $this->getContainer()->get('event_dispatcher');
foreach ($messages as $message) {
$id = $message->getId();
$newMessage = $manager->restart($message);
$this->getBackend()->publish($newMessage);
$output->writeln(sprintf(
'Reset Message %s <info>#%d</info>, new id %d. Attempt #%d',
$newMessage->getType(),
$id,
$newMessage->getId(),
$newMessage->getRestartCount()
));
if ($pullMode) {
$eventDispatcher->dispatch(IterateEvent::EVENT_NAME, new IterateEvent($messages, null, $newMessage));
}
}
$output->writeln('<info>Done!</info>');
} | php | public function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln('<info>Starting... </info>');
if (!is_numeric($input->getOption('max-attempts'))) {
throw new \Exception('Option "max-attempts" is invalid (integer value needed).');
}
$pullMode = $input->getOption('pulling');
$manager = $this->getMessageManager();
if ($pullMode) {
$messages = new ErroneousMessageIterator(
$manager,
$input->getOption('type'),
$input->getOption('pause'),
$input->getOption('batch-size'),
$input->getOption('max-attempts'),
$input->getOption('attempt-delay'));
} else {
$messages = $this->getErroneousMessageSelector()->getMessages(
$input->getOption('type'),
$input->getOption('max-attempts')
);
/*
* Check messages count only for not pulling mode
* to avoid PHP warning message
* since ErroneousMessageIterator does not implement Countable.
*/
if (0 === \count($messages)) {
$output->writeln('Nothing to restart, bye.');
return;
}
}
$eventDispatcher = $this->getContainer()->get('event_dispatcher');
foreach ($messages as $message) {
$id = $message->getId();
$newMessage = $manager->restart($message);
$this->getBackend()->publish($newMessage);
$output->writeln(sprintf(
'Reset Message %s <info>#%d</info>, new id %d. Attempt #%d',
$newMessage->getType(),
$id,
$newMessage->getId(),
$newMessage->getRestartCount()
));
if ($pullMode) {
$eventDispatcher->dispatch(IterateEvent::EVENT_NAME, new IterateEvent($messages, null, $newMessage));
}
}
$output->writeln('<info>Done!</info>');
} | [
"public",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"output",
"->",
"writeln",
"(",
"'<info>Starting... </info>'",
")",
";",
"if",
"(",
"!",
"is_numeric",
"(",
"$",
"input",
"->",
"getOption",
"(",
"'max-attempts'",
")",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'Option \"max-attempts\" is invalid (integer value needed).'",
")",
";",
"}",
"$",
"pullMode",
"=",
"$",
"input",
"->",
"getOption",
"(",
"'pulling'",
")",
";",
"$",
"manager",
"=",
"$",
"this",
"->",
"getMessageManager",
"(",
")",
";",
"if",
"(",
"$",
"pullMode",
")",
"{",
"$",
"messages",
"=",
"new",
"ErroneousMessageIterator",
"(",
"$",
"manager",
",",
"$",
"input",
"->",
"getOption",
"(",
"'type'",
")",
",",
"$",
"input",
"->",
"getOption",
"(",
"'pause'",
")",
",",
"$",
"input",
"->",
"getOption",
"(",
"'batch-size'",
")",
",",
"$",
"input",
"->",
"getOption",
"(",
"'max-attempts'",
")",
",",
"$",
"input",
"->",
"getOption",
"(",
"'attempt-delay'",
")",
")",
";",
"}",
"else",
"{",
"$",
"messages",
"=",
"$",
"this",
"->",
"getErroneousMessageSelector",
"(",
")",
"->",
"getMessages",
"(",
"$",
"input",
"->",
"getOption",
"(",
"'type'",
")",
",",
"$",
"input",
"->",
"getOption",
"(",
"'max-attempts'",
")",
")",
";",
"/*\n * Check messages count only for not pulling mode\n * to avoid PHP warning message\n * since ErroneousMessageIterator does not implement Countable.\n */",
"if",
"(",
"0",
"===",
"\\",
"count",
"(",
"$",
"messages",
")",
")",
"{",
"$",
"output",
"->",
"writeln",
"(",
"'Nothing to restart, bye.'",
")",
";",
"return",
";",
"}",
"}",
"$",
"eventDispatcher",
"=",
"$",
"this",
"->",
"getContainer",
"(",
")",
"->",
"get",
"(",
"'event_dispatcher'",
")",
";",
"foreach",
"(",
"$",
"messages",
"as",
"$",
"message",
")",
"{",
"$",
"id",
"=",
"$",
"message",
"->",
"getId",
"(",
")",
";",
"$",
"newMessage",
"=",
"$",
"manager",
"->",
"restart",
"(",
"$",
"message",
")",
";",
"$",
"this",
"->",
"getBackend",
"(",
")",
"->",
"publish",
"(",
"$",
"newMessage",
")",
";",
"$",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'Reset Message %s <info>#%d</info>, new id %d. Attempt #%d'",
",",
"$",
"newMessage",
"->",
"getType",
"(",
")",
",",
"$",
"id",
",",
"$",
"newMessage",
"->",
"getId",
"(",
")",
",",
"$",
"newMessage",
"->",
"getRestartCount",
"(",
")",
")",
")",
";",
"if",
"(",
"$",
"pullMode",
")",
"{",
"$",
"eventDispatcher",
"->",
"dispatch",
"(",
"IterateEvent",
"::",
"EVENT_NAME",
",",
"new",
"IterateEvent",
"(",
"$",
"messages",
",",
"null",
",",
"$",
"newMessage",
")",
")",
";",
"}",
"}",
"$",
"output",
"->",
"writeln",
"(",
"'<info>Done!</info>'",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Command/RestartCommand.php#L46-L106 |
sonata-project/SonataNotificationBundle | src/Event/DoctrineBackendOptimizeListener.php | DoctrineBackendOptimizeListener.iterate | public function iterate(IterateEvent $event)
{
if (!method_exists($event->getIterator(), 'isBufferEmpty')) {
throw new \LogicException('You can\'t use DoctrineOptimizeListener with this iterator');
}
if ($event->getIterator()->isBufferEmpty()) {
$this->doctrine->getManager()->getUnitOfWork()->clear();
}
} | php | public function iterate(IterateEvent $event)
{
if (!method_exists($event->getIterator(), 'isBufferEmpty')) {
throw new \LogicException('You can\'t use DoctrineOptimizeListener with this iterator');
}
if ($event->getIterator()->isBufferEmpty()) {
$this->doctrine->getManager()->getUnitOfWork()->clear();
}
} | [
"public",
"function",
"iterate",
"(",
"IterateEvent",
"$",
"event",
")",
"{",
"if",
"(",
"!",
"method_exists",
"(",
"$",
"event",
"->",
"getIterator",
"(",
")",
",",
"'isBufferEmpty'",
")",
")",
"{",
"throw",
"new",
"\\",
"LogicException",
"(",
"'You can\\'t use DoctrineOptimizeListener with this iterator'",
")",
";",
"}",
"if",
"(",
"$",
"event",
"->",
"getIterator",
"(",
")",
"->",
"isBufferEmpty",
"(",
")",
")",
"{",
"$",
"this",
"->",
"doctrine",
"->",
"getManager",
"(",
")",
"->",
"getUnitOfWork",
"(",
")",
"->",
"clear",
"(",
")",
";",
"}",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Event/DoctrineBackendOptimizeListener.php#L43-L52 |
sonata-project/SonataNotificationBundle | src/Backend/PostponeRuntimeBackend.php | PostponeRuntimeBackend.publish | public function publish(MessageInterface $message)
{
// if the message is generated from the cli the message is handled
// directly as there is no kernel.terminate in cli
if (!$this->postponeOnCli && $this->isCommandLineInterface()) {
$this->handle($message, $this->dispatcher);
return;
}
$this->messages[] = $message;
} | php | public function publish(MessageInterface $message)
{
// if the message is generated from the cli the message is handled
// directly as there is no kernel.terminate in cli
if (!$this->postponeOnCli && $this->isCommandLineInterface()) {
$this->handle($message, $this->dispatcher);
return;
}
$this->messages[] = $message;
} | [
"public",
"function",
"publish",
"(",
"MessageInterface",
"$",
"message",
")",
"{",
"// if the message is generated from the cli the message is handled",
"// directly as there is no kernel.terminate in cli",
"if",
"(",
"!",
"$",
"this",
"->",
"postponeOnCli",
"&&",
"$",
"this",
"->",
"isCommandLineInterface",
"(",
")",
")",
"{",
"$",
"this",
"->",
"handle",
"(",
"$",
"message",
",",
"$",
"this",
"->",
"dispatcher",
")",
";",
"return",
";",
"}",
"$",
"this",
"->",
"messages",
"[",
"]",
"=",
"$",
"message",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Backend/PostponeRuntimeBackend.php#L59-L70 |
sonata-project/SonataNotificationBundle | src/Backend/PostponeRuntimeBackend.php | PostponeRuntimeBackend.onEvent | public function onEvent(Event $event = null)
{
while (!empty($this->messages)) {
$message = array_shift($this->messages);
$this->handle($message, $this->dispatcher);
}
} | php | public function onEvent(Event $event = null)
{
while (!empty($this->messages)) {
$message = array_shift($this->messages);
$this->handle($message, $this->dispatcher);
}
} | [
"public",
"function",
"onEvent",
"(",
"Event",
"$",
"event",
"=",
"null",
")",
"{",
"while",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"messages",
")",
")",
"{",
"$",
"message",
"=",
"array_shift",
"(",
"$",
"this",
"->",
"messages",
")",
";",
"$",
"this",
"->",
"handle",
"(",
"$",
"message",
",",
"$",
"this",
"->",
"dispatcher",
")",
";",
"}",
"}"
] | Listen on any event and handle the messages.
Actually, an event is not necessary, you can call this method manually, to.
The event is not processed in any way.
@param Event|null $event | [
"Listen",
"on",
"any",
"event",
"and",
"handle",
"the",
"messages",
"."
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Backend/PostponeRuntimeBackend.php#L80-L87 |
sonata-project/SonataNotificationBundle | src/Backend/MessageManagerBackendDispatcher.php | MessageManagerBackendDispatcher.getBackend | public function getBackend($type)
{
$default = null;
if (!$type) {
return $this->getDefaultBackend();
}
foreach ($this->backends as $backend) {
if (\in_array($type, $backend['types'], true)) {
return $backend['backend'];
}
}
return $this->getDefaultBackend();
} | php | public function getBackend($type)
{
$default = null;
if (!$type) {
return $this->getDefaultBackend();
}
foreach ($this->backends as $backend) {
if (\in_array($type, $backend['types'], true)) {
return $backend['backend'];
}
}
return $this->getDefaultBackend();
} | [
"public",
"function",
"getBackend",
"(",
"$",
"type",
")",
"{",
"$",
"default",
"=",
"null",
";",
"if",
"(",
"!",
"$",
"type",
")",
"{",
"return",
"$",
"this",
"->",
"getDefaultBackend",
"(",
")",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"backends",
"as",
"$",
"backend",
")",
"{",
"if",
"(",
"\\",
"in_array",
"(",
"$",
"type",
",",
"$",
"backend",
"[",
"'types'",
"]",
",",
"true",
")",
")",
"{",
"return",
"$",
"backend",
"[",
"'backend'",
"]",
";",
"}",
"}",
"return",
"$",
"this",
"->",
"getDefaultBackend",
"(",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Backend/MessageManagerBackendDispatcher.php#L64-L79 |
sonata-project/SonataNotificationBundle | src/Iterator/MessageManagerMessageIterator.php | MessageManagerMessageIterator.setCurrent | protected function setCurrent()
{
if (0 === \count($this->buffer)) {
$this->bufferize($this->types);
}
$this->current = array_pop($this->buffer);
} | php | protected function setCurrent()
{
if (0 === \count($this->buffer)) {
$this->bufferize($this->types);
}
$this->current = array_pop($this->buffer);
} | [
"protected",
"function",
"setCurrent",
"(",
")",
"{",
"if",
"(",
"0",
"===",
"\\",
"count",
"(",
"$",
"this",
"->",
"buffer",
")",
")",
"{",
"$",
"this",
"->",
"bufferize",
"(",
"$",
"this",
"->",
"types",
")",
";",
"}",
"$",
"this",
"->",
"current",
"=",
"array_pop",
"(",
"$",
"this",
"->",
"buffer",
")",
";",
"}"
] | Assign current pointer a message. | [
"Assign",
"current",
"pointer",
"a",
"message",
"."
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Iterator/MessageManagerMessageIterator.php#L120-L127 |
sonata-project/SonataNotificationBundle | src/Iterator/MessageManagerMessageIterator.php | MessageManagerMessageIterator.bufferize | protected function bufferize($types = [])
{
while (true) {
$this->buffer = $this->findNextMessages($types);
if (\count($this->buffer) > 0) {
break;
}
usleep($this->pause);
}
} | php | protected function bufferize($types = [])
{
while (true) {
$this->buffer = $this->findNextMessages($types);
if (\count($this->buffer) > 0) {
break;
}
usleep($this->pause);
}
} | [
"protected",
"function",
"bufferize",
"(",
"$",
"types",
"=",
"[",
"]",
")",
"{",
"while",
"(",
"true",
")",
"{",
"$",
"this",
"->",
"buffer",
"=",
"$",
"this",
"->",
"findNextMessages",
"(",
"$",
"types",
")",
";",
"if",
"(",
"\\",
"count",
"(",
"$",
"this",
"->",
"buffer",
")",
">",
"0",
")",
"{",
"break",
";",
"}",
"usleep",
"(",
"$",
"this",
"->",
"pause",
")",
";",
"}",
"}"
] | Fill the inner messages buffer.
@param array $types | [
"Fill",
"the",
"inner",
"messages",
"buffer",
"."
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Iterator/MessageManagerMessageIterator.php#L134-L145 |
sonata-project/SonataNotificationBundle | src/Iterator/MessageManagerMessageIterator.php | MessageManagerMessageIterator.findNextMessages | protected function findNextMessages($types)
{
return $this->messageManager->findByTypes($types, MessageInterface::STATE_OPEN, $this->batchSize);
} | php | protected function findNextMessages($types)
{
return $this->messageManager->findByTypes($types, MessageInterface::STATE_OPEN, $this->batchSize);
} | [
"protected",
"function",
"findNextMessages",
"(",
"$",
"types",
")",
"{",
"return",
"$",
"this",
"->",
"messageManager",
"->",
"findByTypes",
"(",
"$",
"types",
",",
"MessageInterface",
"::",
"STATE_OPEN",
",",
"$",
"this",
"->",
"batchSize",
")",
";",
"}"
] | Find open messages.
@param array $types
@return mixed | [
"Find",
"open",
"messages",
"."
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Iterator/MessageManagerMessageIterator.php#L154-L157 |
sonata-project/SonataNotificationBundle | src/Consumer/SwiftMailerConsumer.php | SwiftMailerConsumer.process | public function process(ConsumerEvent $event)
{
if (!$this->mailer->getTransport()->isStarted()) {
$this->mailer->getTransport()->start();
}
$exception = false;
try {
$this->sendEmail($event->getMessage());
} catch (\Exception $e) {
$exception = $e;
}
$this->mailer->getTransport()->stop();
if ($exception) {
throw $exception;
}
} | php | public function process(ConsumerEvent $event)
{
if (!$this->mailer->getTransport()->isStarted()) {
$this->mailer->getTransport()->start();
}
$exception = false;
try {
$this->sendEmail($event->getMessage());
} catch (\Exception $e) {
$exception = $e;
}
$this->mailer->getTransport()->stop();
if ($exception) {
throw $exception;
}
} | [
"public",
"function",
"process",
"(",
"ConsumerEvent",
"$",
"event",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"mailer",
"->",
"getTransport",
"(",
")",
"->",
"isStarted",
"(",
")",
")",
"{",
"$",
"this",
"->",
"mailer",
"->",
"getTransport",
"(",
")",
"->",
"start",
"(",
")",
";",
"}",
"$",
"exception",
"=",
"false",
";",
"try",
"{",
"$",
"this",
"->",
"sendEmail",
"(",
"$",
"event",
"->",
"getMessage",
"(",
")",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"$",
"exception",
"=",
"$",
"e",
";",
"}",
"$",
"this",
"->",
"mailer",
"->",
"getTransport",
"(",
")",
"->",
"stop",
"(",
")",
";",
"if",
"(",
"$",
"exception",
")",
"{",
"throw",
"$",
"exception",
";",
"}",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Consumer/SwiftMailerConsumer.php#L36-L55 |
sonata-project/SonataNotificationBundle | src/DependencyInjection/Configuration.php | Configuration.getConfigTreeBuilder | public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('sonata_notification');
// Keep compatibility with symfony/config < 4.2
if (!method_exists($treeBuilder, 'getRootNode')) {
$rootNode = $treeBuilder->root('sonata_notification')->children();
} else {
$rootNode = $treeBuilder->getRootNode()->children();
}
$backendInfo = <<<'EOF'
Other backends you can use:
sonata.notification.backend.postpone
sonata.notification.backend.doctrine
sonata.notification.backend.rabbitmq
EOF;
$iterationListenersInfo = <<<EOF
Listeners attached to the IterateEvent
Iterate event is thrown on each command iteration
Iteration listener class must implement Sonata\NotificationBundle\Event\IterationListener
EOF;
$rootNode
->scalarNode('backend')
->info($backendInfo)
->defaultValue('sonata.notification.backend.runtime')
->end()
->append($this->getQueueNode())
->arrayNode('backends')
->children()
->arrayNode('doctrine')
->children()
->scalarNode('message_manager')
->defaultValue('sonata.notification.manager.message.default')
->end()
->scalarNode('max_age')
->info('The max age in seconds')
->defaultValue(86400)
->end()
->scalarNode('pause')
->info('The delay in microseconds')
->defaultValue(500000)
->end()
->scalarNode('batch_size')
->info('The number of items on each iteration')
->defaultValue(10)
->end()
->arrayNode('states')
->info('Raising errors level')
->addDefaultsIfNotSet()
->children()
->integerNode('in_progress')
->defaultValue(10)
->end()
->integerNode('error')
->defaultValue(20)
->end()
->integerNode('open')
->defaultValue(100)
->end()
->integerNode('done')
->defaultValue(10000)
->end()
->end()
->end()
->end()
->end()
->arrayNode('rabbitmq')
->children()
->scalarNode('exchange')
->cannotBeEmpty()
->isRequired()
->end()
->arrayNode('connection')
->addDefaultsIfNotSet()
->children()
->scalarNode('host')
->defaultValue('localhost')
->end()
->scalarNode('port')
->defaultValue(5672)
->end()
->scalarNode('user')
->defaultValue('guest')
->end()
->scalarNode('pass')
->defaultValue('guest')
->end()
->scalarNode('vhost')
->defaultValue('guest')
->end()
->scalarNode('console_url')
->defaultValue('http://localhost:55672/api')
->end()
->scalarNode('factory_class')
->cannotBeEmpty()
->defaultValue(AmqpConnectionFactory::class)
->info('This option defines an AMQP connection factory to be used to establish a connection with RabbitMQ.')
->end()
->end()
->end()
->end()
->end()
->end()
->end()
->arrayNode('consumers')
->addDefaultsIfNotSet()
->children()
->booleanNode('register_default')
->info('If set to true, SwiftMailerConsumer and LoggerConsumer will be registered as services')
->defaultTrue()
->end()
->end()
->end()
->arrayNode('iteration_listeners')
->info($iterationListenersInfo)
->defaultValue([])
->prototype('scalar')->end()
->end()
->arrayNode('class')
->addDefaultsIfNotSet()
->children()
->scalarNode('message')
->defaultValue('Application\\Sonata\\NotificationBundle\\Entity\\Message')
->end()
->end()
->end()
->arrayNode('admin')
->addDefaultsIfNotSet()
->children()
->booleanNode('enabled')
->defaultTrue()
->end()
->arrayNode('message')
->addDefaultsIfNotSet()
->children()
->scalarNode('class')
->cannotBeEmpty()
->defaultValue('Sonata\\NotificationBundle\\Admin\\MessageAdmin')
->end()
->scalarNode('controller')
->cannotBeEmpty()
->defaultValue('SonataNotificationBundle:MessageAdmin')
->end()
->scalarNode('translation')
->cannotBeEmpty()
->defaultValue('SonataNotificationBundle')
->end()
->end()
->end()
->end()
->end()
;
return $treeBuilder;
} | php | public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('sonata_notification');
// Keep compatibility with symfony/config < 4.2
if (!method_exists($treeBuilder, 'getRootNode')) {
$rootNode = $treeBuilder->root('sonata_notification')->children();
} else {
$rootNode = $treeBuilder->getRootNode()->children();
}
$backendInfo = <<<'EOF'
Other backends you can use:
sonata.notification.backend.postpone
sonata.notification.backend.doctrine
sonata.notification.backend.rabbitmq
EOF;
$iterationListenersInfo = <<<EOF
Listeners attached to the IterateEvent
Iterate event is thrown on each command iteration
Iteration listener class must implement Sonata\NotificationBundle\Event\IterationListener
EOF;
$rootNode
->scalarNode('backend')
->info($backendInfo)
->defaultValue('sonata.notification.backend.runtime')
->end()
->append($this->getQueueNode())
->arrayNode('backends')
->children()
->arrayNode('doctrine')
->children()
->scalarNode('message_manager')
->defaultValue('sonata.notification.manager.message.default')
->end()
->scalarNode('max_age')
->info('The max age in seconds')
->defaultValue(86400)
->end()
->scalarNode('pause')
->info('The delay in microseconds')
->defaultValue(500000)
->end()
->scalarNode('batch_size')
->info('The number of items on each iteration')
->defaultValue(10)
->end()
->arrayNode('states')
->info('Raising errors level')
->addDefaultsIfNotSet()
->children()
->integerNode('in_progress')
->defaultValue(10)
->end()
->integerNode('error')
->defaultValue(20)
->end()
->integerNode('open')
->defaultValue(100)
->end()
->integerNode('done')
->defaultValue(10000)
->end()
->end()
->end()
->end()
->end()
->arrayNode('rabbitmq')
->children()
->scalarNode('exchange')
->cannotBeEmpty()
->isRequired()
->end()
->arrayNode('connection')
->addDefaultsIfNotSet()
->children()
->scalarNode('host')
->defaultValue('localhost')
->end()
->scalarNode('port')
->defaultValue(5672)
->end()
->scalarNode('user')
->defaultValue('guest')
->end()
->scalarNode('pass')
->defaultValue('guest')
->end()
->scalarNode('vhost')
->defaultValue('guest')
->end()
->scalarNode('console_url')
->defaultValue('http://localhost:55672/api')
->end()
->scalarNode('factory_class')
->cannotBeEmpty()
->defaultValue(AmqpConnectionFactory::class)
->info('This option defines an AMQP connection factory to be used to establish a connection with RabbitMQ.')
->end()
->end()
->end()
->end()
->end()
->end()
->end()
->arrayNode('consumers')
->addDefaultsIfNotSet()
->children()
->booleanNode('register_default')
->info('If set to true, SwiftMailerConsumer and LoggerConsumer will be registered as services')
->defaultTrue()
->end()
->end()
->end()
->arrayNode('iteration_listeners')
->info($iterationListenersInfo)
->defaultValue([])
->prototype('scalar')->end()
->end()
->arrayNode('class')
->addDefaultsIfNotSet()
->children()
->scalarNode('message')
->defaultValue('Application\\Sonata\\NotificationBundle\\Entity\\Message')
->end()
->end()
->end()
->arrayNode('admin')
->addDefaultsIfNotSet()
->children()
->booleanNode('enabled')
->defaultTrue()
->end()
->arrayNode('message')
->addDefaultsIfNotSet()
->children()
->scalarNode('class')
->cannotBeEmpty()
->defaultValue('Sonata\\NotificationBundle\\Admin\\MessageAdmin')
->end()
->scalarNode('controller')
->cannotBeEmpty()
->defaultValue('SonataNotificationBundle:MessageAdmin')
->end()
->scalarNode('translation')
->cannotBeEmpty()
->defaultValue('SonataNotificationBundle')
->end()
->end()
->end()
->end()
->end()
;
return $treeBuilder;
} | [
"public",
"function",
"getConfigTreeBuilder",
"(",
")",
"{",
"$",
"treeBuilder",
"=",
"new",
"TreeBuilder",
"(",
"'sonata_notification'",
")",
";",
"// Keep compatibility with symfony/config < 4.2",
"if",
"(",
"!",
"method_exists",
"(",
"$",
"treeBuilder",
",",
"'getRootNode'",
")",
")",
"{",
"$",
"rootNode",
"=",
"$",
"treeBuilder",
"->",
"root",
"(",
"'sonata_notification'",
")",
"->",
"children",
"(",
")",
";",
"}",
"else",
"{",
"$",
"rootNode",
"=",
"$",
"treeBuilder",
"->",
"getRootNode",
"(",
")",
"->",
"children",
"(",
")",
";",
"}",
"$",
"backendInfo",
"=",
" <<<'EOF'\nOther backends you can use:\n\nsonata.notification.backend.postpone\nsonata.notification.backend.doctrine\nsonata.notification.backend.rabbitmq\nEOF",
";",
"$",
"iterationListenersInfo",
"=",
" <<<EOF\nListeners attached to the IterateEvent\nIterate event is thrown on each command iteration\n\nIteration listener class must implement Sonata\\NotificationBundle\\Event\\IterationListener\nEOF",
";",
"$",
"rootNode",
"->",
"scalarNode",
"(",
"'backend'",
")",
"->",
"info",
"(",
"$",
"backendInfo",
")",
"->",
"defaultValue",
"(",
"'sonata.notification.backend.runtime'",
")",
"->",
"end",
"(",
")",
"->",
"append",
"(",
"$",
"this",
"->",
"getQueueNode",
"(",
")",
")",
"->",
"arrayNode",
"(",
"'backends'",
")",
"->",
"children",
"(",
")",
"->",
"arrayNode",
"(",
"'doctrine'",
")",
"->",
"children",
"(",
")",
"->",
"scalarNode",
"(",
"'message_manager'",
")",
"->",
"defaultValue",
"(",
"'sonata.notification.manager.message.default'",
")",
"->",
"end",
"(",
")",
"->",
"scalarNode",
"(",
"'max_age'",
")",
"->",
"info",
"(",
"'The max age in seconds'",
")",
"->",
"defaultValue",
"(",
"86400",
")",
"->",
"end",
"(",
")",
"->",
"scalarNode",
"(",
"'pause'",
")",
"->",
"info",
"(",
"'The delay in microseconds'",
")",
"->",
"defaultValue",
"(",
"500000",
")",
"->",
"end",
"(",
")",
"->",
"scalarNode",
"(",
"'batch_size'",
")",
"->",
"info",
"(",
"'The number of items on each iteration'",
")",
"->",
"defaultValue",
"(",
"10",
")",
"->",
"end",
"(",
")",
"->",
"arrayNode",
"(",
"'states'",
")",
"->",
"info",
"(",
"'Raising errors level'",
")",
"->",
"addDefaultsIfNotSet",
"(",
")",
"->",
"children",
"(",
")",
"->",
"integerNode",
"(",
"'in_progress'",
")",
"->",
"defaultValue",
"(",
"10",
")",
"->",
"end",
"(",
")",
"->",
"integerNode",
"(",
"'error'",
")",
"->",
"defaultValue",
"(",
"20",
")",
"->",
"end",
"(",
")",
"->",
"integerNode",
"(",
"'open'",
")",
"->",
"defaultValue",
"(",
"100",
")",
"->",
"end",
"(",
")",
"->",
"integerNode",
"(",
"'done'",
")",
"->",
"defaultValue",
"(",
"10000",
")",
"->",
"end",
"(",
")",
"->",
"end",
"(",
")",
"->",
"end",
"(",
")",
"->",
"end",
"(",
")",
"->",
"end",
"(",
")",
"->",
"arrayNode",
"(",
"'rabbitmq'",
")",
"->",
"children",
"(",
")",
"->",
"scalarNode",
"(",
"'exchange'",
")",
"->",
"cannotBeEmpty",
"(",
")",
"->",
"isRequired",
"(",
")",
"->",
"end",
"(",
")",
"->",
"arrayNode",
"(",
"'connection'",
")",
"->",
"addDefaultsIfNotSet",
"(",
")",
"->",
"children",
"(",
")",
"->",
"scalarNode",
"(",
"'host'",
")",
"->",
"defaultValue",
"(",
"'localhost'",
")",
"->",
"end",
"(",
")",
"->",
"scalarNode",
"(",
"'port'",
")",
"->",
"defaultValue",
"(",
"5672",
")",
"->",
"end",
"(",
")",
"->",
"scalarNode",
"(",
"'user'",
")",
"->",
"defaultValue",
"(",
"'guest'",
")",
"->",
"end",
"(",
")",
"->",
"scalarNode",
"(",
"'pass'",
")",
"->",
"defaultValue",
"(",
"'guest'",
")",
"->",
"end",
"(",
")",
"->",
"scalarNode",
"(",
"'vhost'",
")",
"->",
"defaultValue",
"(",
"'guest'",
")",
"->",
"end",
"(",
")",
"->",
"scalarNode",
"(",
"'console_url'",
")",
"->",
"defaultValue",
"(",
"'http://localhost:55672/api'",
")",
"->",
"end",
"(",
")",
"->",
"scalarNode",
"(",
"'factory_class'",
")",
"->",
"cannotBeEmpty",
"(",
")",
"->",
"defaultValue",
"(",
"AmqpConnectionFactory",
"::",
"class",
")",
"->",
"info",
"(",
"'This option defines an AMQP connection factory to be used to establish a connection with RabbitMQ.'",
")",
"->",
"end",
"(",
")",
"->",
"end",
"(",
")",
"->",
"end",
"(",
")",
"->",
"end",
"(",
")",
"->",
"end",
"(",
")",
"->",
"end",
"(",
")",
"->",
"end",
"(",
")",
"->",
"arrayNode",
"(",
"'consumers'",
")",
"->",
"addDefaultsIfNotSet",
"(",
")",
"->",
"children",
"(",
")",
"->",
"booleanNode",
"(",
"'register_default'",
")",
"->",
"info",
"(",
"'If set to true, SwiftMailerConsumer and LoggerConsumer will be registered as services'",
")",
"->",
"defaultTrue",
"(",
")",
"->",
"end",
"(",
")",
"->",
"end",
"(",
")",
"->",
"end",
"(",
")",
"->",
"arrayNode",
"(",
"'iteration_listeners'",
")",
"->",
"info",
"(",
"$",
"iterationListenersInfo",
")",
"->",
"defaultValue",
"(",
"[",
"]",
")",
"->",
"prototype",
"(",
"'scalar'",
")",
"->",
"end",
"(",
")",
"->",
"end",
"(",
")",
"->",
"arrayNode",
"(",
"'class'",
")",
"->",
"addDefaultsIfNotSet",
"(",
")",
"->",
"children",
"(",
")",
"->",
"scalarNode",
"(",
"'message'",
")",
"->",
"defaultValue",
"(",
"'Application\\\\Sonata\\\\NotificationBundle\\\\Entity\\\\Message'",
")",
"->",
"end",
"(",
")",
"->",
"end",
"(",
")",
"->",
"end",
"(",
")",
"->",
"arrayNode",
"(",
"'admin'",
")",
"->",
"addDefaultsIfNotSet",
"(",
")",
"->",
"children",
"(",
")",
"->",
"booleanNode",
"(",
"'enabled'",
")",
"->",
"defaultTrue",
"(",
")",
"->",
"end",
"(",
")",
"->",
"arrayNode",
"(",
"'message'",
")",
"->",
"addDefaultsIfNotSet",
"(",
")",
"->",
"children",
"(",
")",
"->",
"scalarNode",
"(",
"'class'",
")",
"->",
"cannotBeEmpty",
"(",
")",
"->",
"defaultValue",
"(",
"'Sonata\\\\NotificationBundle\\\\Admin\\\\MessageAdmin'",
")",
"->",
"end",
"(",
")",
"->",
"scalarNode",
"(",
"'controller'",
")",
"->",
"cannotBeEmpty",
"(",
")",
"->",
"defaultValue",
"(",
"'SonataNotificationBundle:MessageAdmin'",
")",
"->",
"end",
"(",
")",
"->",
"scalarNode",
"(",
"'translation'",
")",
"->",
"cannotBeEmpty",
"(",
")",
"->",
"defaultValue",
"(",
"'SonataNotificationBundle'",
")",
"->",
"end",
"(",
")",
"->",
"end",
"(",
")",
"->",
"end",
"(",
")",
"->",
"end",
"(",
")",
"->",
"end",
"(",
")",
";",
"return",
"$",
"treeBuilder",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/DependencyInjection/Configuration.php#L27-L186 |
sonata-project/SonataNotificationBundle | src/Admin/MessageAdmin.php | MessageAdmin.configureListFields | protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('id', null, ['route' => ['name' => 'show']])
->add('type')
->add('createdAt')
->add('startedAt')
->add('completedAt')
->add('getStateName')
->add('restartCount')
;
} | php | protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('id', null, ['route' => ['name' => 'show']])
->add('type')
->add('createdAt')
->add('startedAt')
->add('completedAt')
->add('getStateName')
->add('restartCount')
;
} | [
"protected",
"function",
"configureListFields",
"(",
"ListMapper",
"$",
"listMapper",
")",
"{",
"$",
"listMapper",
"->",
"addIdentifier",
"(",
"'id'",
",",
"null",
",",
"[",
"'route'",
"=>",
"[",
"'name'",
"=>",
"'show'",
"]",
"]",
")",
"->",
"add",
"(",
"'type'",
")",
"->",
"add",
"(",
"'createdAt'",
")",
"->",
"add",
"(",
"'startedAt'",
")",
"->",
"add",
"(",
"'completedAt'",
")",
"->",
"add",
"(",
"'getStateName'",
")",
"->",
"add",
"(",
"'restartCount'",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Admin/MessageAdmin.php#L80-L91 |
sonata-project/SonataNotificationBundle | src/Admin/MessageAdmin.php | MessageAdmin.configureDatagridFilters | protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$class = $this->getClass();
$datagridMapper
->add('type')
->add('state', null, [], ChoiceType::class, ['choices' => $class::getStateList()])
;
} | php | protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$class = $this->getClass();
$datagridMapper
->add('type')
->add('state', null, [], ChoiceType::class, ['choices' => $class::getStateList()])
;
} | [
"protected",
"function",
"configureDatagridFilters",
"(",
"DatagridMapper",
"$",
"datagridMapper",
")",
"{",
"$",
"class",
"=",
"$",
"this",
"->",
"getClass",
"(",
")",
";",
"$",
"datagridMapper",
"->",
"add",
"(",
"'type'",
")",
"->",
"add",
"(",
"'state'",
",",
"null",
",",
"[",
"]",
",",
"ChoiceType",
"::",
"class",
",",
"[",
"'choices'",
"=>",
"$",
"class",
"::",
"getStateList",
"(",
")",
"]",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Admin/MessageAdmin.php#L96-L104 |
sonata-project/SonataNotificationBundle | src/Iterator/ErroneousMessageIterator.php | ErroneousMessageIterator.findNextMessages | protected function findNextMessages($types)
{
return $this->messageManager->findByAttempts(
$this->types,
MessageInterface::STATE_ERROR,
$this->batchSize,
$this->maxAttempts,
$this->attemptDelay
);
} | php | protected function findNextMessages($types)
{
return $this->messageManager->findByAttempts(
$this->types,
MessageInterface::STATE_ERROR,
$this->batchSize,
$this->maxAttempts,
$this->attemptDelay
);
} | [
"protected",
"function",
"findNextMessages",
"(",
"$",
"types",
")",
"{",
"return",
"$",
"this",
"->",
"messageManager",
"->",
"findByAttempts",
"(",
"$",
"this",
"->",
"types",
",",
"MessageInterface",
"::",
"STATE_ERROR",
",",
"$",
"this",
"->",
"batchSize",
",",
"$",
"this",
"->",
"maxAttempts",
",",
"$",
"this",
"->",
"attemptDelay",
")",
";",
"}"
] | Find messages in error.
@param $types
@return mixed | [
"Find",
"messages",
"in",
"error",
"."
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Iterator/ErroneousMessageIterator.php#L54-L63 |
sonata-project/SonataNotificationBundle | src/Command/CreateAndPublishCommand.php | CreateAndPublishCommand.execute | public function execute(InputInterface $input, OutputInterface $output)
{
$type = $input->getArgument('type');
$body = json_decode($input->getArgument('body'), true);
if (null === $body) {
throw new \InvalidArgumentException('Body does not contain valid json.');
}
$this->getContainer()
->get('sonata.notification.backend')
->createAndPublish($type, $body)
;
$output->writeln('<info>Done !</info>');
} | php | public function execute(InputInterface $input, OutputInterface $output)
{
$type = $input->getArgument('type');
$body = json_decode($input->getArgument('body'), true);
if (null === $body) {
throw new \InvalidArgumentException('Body does not contain valid json.');
}
$this->getContainer()
->get('sonata.notification.backend')
->createAndPublish($type, $body)
;
$output->writeln('<info>Done !</info>');
} | [
"public",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"type",
"=",
"$",
"input",
"->",
"getArgument",
"(",
"'type'",
")",
";",
"$",
"body",
"=",
"json_decode",
"(",
"$",
"input",
"->",
"getArgument",
"(",
"'body'",
")",
",",
"true",
")",
";",
"if",
"(",
"null",
"===",
"$",
"body",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Body does not contain valid json.'",
")",
";",
"}",
"$",
"this",
"->",
"getContainer",
"(",
")",
"->",
"get",
"(",
"'sonata.notification.backend'",
")",
"->",
"createAndPublish",
"(",
"$",
"type",
",",
"$",
"body",
")",
";",
"$",
"output",
"->",
"writeln",
"(",
"'<info>Done !</info>'",
")",
";",
"}"
] | {@inheritdoc}
@param InputInterface $input
@param OutputInterface $output | [
"{",
"@inheritdoc",
"}"
] | train | https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Command/CreateAndPublishCommand.php#L40-L55 |
photondragon/webgeeker-validation | src/Validation/Validation.php | Validation.validateInt | public static function validateInt($value, $reason = null, $alias = 'Parameter')
{
$type = gettype($value);
if ($type === 'string') {
if (is_numeric($value) && strpos($value, '.') === false)
return $value;
} elseif ($type === 'integer') {
return $value;
}
if ($reason !== null)
throw new ValidationException($reason);
$error = self::getErrorTemplate('Int');
$error = str_replace('{{param}}', $alias, $error);
throw new ValidationException($error);
} | php | public static function validateInt($value, $reason = null, $alias = 'Parameter')
{
$type = gettype($value);
if ($type === 'string') {
if (is_numeric($value) && strpos($value, '.') === false)
return $value;
} elseif ($type === 'integer') {
return $value;
}
if ($reason !== null)
throw new ValidationException($reason);
$error = self::getErrorTemplate('Int');
$error = str_replace('{{param}}', $alias, $error);
throw new ValidationException($error);
} | [
"public",
"static",
"function",
"validateInt",
"(",
"$",
"value",
",",
"$",
"reason",
"=",
"null",
",",
"$",
"alias",
"=",
"'Parameter'",
")",
"{",
"$",
"type",
"=",
"gettype",
"(",
"$",
"value",
")",
";",
"if",
"(",
"$",
"type",
"===",
"'string'",
")",
"{",
"if",
"(",
"is_numeric",
"(",
"$",
"value",
")",
"&&",
"strpos",
"(",
"$",
"value",
",",
"'.'",
")",
"===",
"false",
")",
"return",
"$",
"value",
";",
"}",
"elseif",
"(",
"$",
"type",
"===",
"'integer'",
")",
"{",
"return",
"$",
"value",
";",
"}",
"if",
"(",
"$",
"reason",
"!==",
"null",
")",
"throw",
"new",
"ValidationException",
"(",
"$",
"reason",
")",
";",
"$",
"error",
"=",
"self",
"::",
"getErrorTemplate",
"(",
"'Int'",
")",
";",
"$",
"error",
"=",
"str_replace",
"(",
"'{{param}}'",
",",
"$",
"alias",
",",
"$",
"error",
")",
";",
"throw",
"new",
"ValidationException",
"(",
"$",
"error",
")",
";",
"}"
] | region integer | [
"region",
"integer"
] | train | https://github.com/photondragon/webgeeker-validation/blob/3bfc2b697ff526897c525af38c9e4ed4c889976d/src/Validation/Validation.php#L29-L45 |
photondragon/webgeeker-validation | src/Validation/Validation.php | Validation.validateIntNotIn | public static function validateIntNotIn($value, $valueList, $reason = null, $alias = 'Parameter')
{
if (is_array($valueList) === false || count($valueList) === 0)
throw new ValidationException("“${alias}”参数的验证模版(IntNotIn:)格式错误, 必须提供可取值的列表");
$type = gettype($value);
if ($type === 'string') {
if (is_numeric($value) && strpos($value, '.') === false) {
$intValue = intval($value);
if (!in_array($intValue, $valueList, true))
return $value;
$isTypeError = false;
} else
$isTypeError = true;
} elseif ($type === 'integer') {
if (!in_array($value, $valueList, true))
return $value;
$isTypeError = false;
} else
$isTypeError = true;
if ($reason !== null)
throw new ValidationException($reason);
if ($isTypeError) {
$error = self::getErrorTemplate('Int');
$error = str_replace('{{param}}', $alias, $error);
} else {
$error = self::getErrorTemplate('IntNotIn');
$error = str_replace('{{param}}', $alias, $error);
$error = str_replace('{{valueList}}', implode(', ', $valueList), $error);
}
throw new ValidationException($error);
} | php | public static function validateIntNotIn($value, $valueList, $reason = null, $alias = 'Parameter')
{
if (is_array($valueList) === false || count($valueList) === 0)
throw new ValidationException("“${alias}”参数的验证模版(IntNotIn:)格式错误, 必须提供可取值的列表");
$type = gettype($value);
if ($type === 'string') {
if (is_numeric($value) && strpos($value, '.') === false) {
$intValue = intval($value);
if (!in_array($intValue, $valueList, true))
return $value;
$isTypeError = false;
} else
$isTypeError = true;
} elseif ($type === 'integer') {
if (!in_array($value, $valueList, true))
return $value;
$isTypeError = false;
} else
$isTypeError = true;
if ($reason !== null)
throw new ValidationException($reason);
if ($isTypeError) {
$error = self::getErrorTemplate('Int');
$error = str_replace('{{param}}', $alias, $error);
} else {
$error = self::getErrorTemplate('IntNotIn');
$error = str_replace('{{param}}', $alias, $error);
$error = str_replace('{{valueList}}', implode(', ', $valueList), $error);
}
throw new ValidationException($error);
} | [
"public",
"static",
"function",
"validateIntNotIn",
"(",
"$",
"value",
",",
"$",
"valueList",
",",
"$",
"reason",
"=",
"null",
",",
"$",
"alias",
"=",
"'Parameter'",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"valueList",
")",
"===",
"false",
"||",
"count",
"(",
"$",
"valueList",
")",
"===",
"0",
")",
"throw",
"new",
"ValidationException",
"(",
"\"“${alias}”参数的验证模版(IntNotIn:)格式错误, 必须提供可取值的列表\");",
"",
"",
"$",
"type",
"=",
"gettype",
"(",
"$",
"value",
")",
";",
"if",
"(",
"$",
"type",
"===",
"'string'",
")",
"{",
"if",
"(",
"is_numeric",
"(",
"$",
"value",
")",
"&&",
"strpos",
"(",
"$",
"value",
",",
"'.'",
")",
"===",
"false",
")",
"{",
"$",
"intValue",
"=",
"intval",
"(",
"$",
"value",
")",
";",
"if",
"(",
"!",
"in_array",
"(",
"$",
"intValue",
",",
"$",
"valueList",
",",
"true",
")",
")",
"return",
"$",
"value",
";",
"$",
"isTypeError",
"=",
"false",
";",
"}",
"else",
"$",
"isTypeError",
"=",
"true",
";",
"}",
"elseif",
"(",
"$",
"type",
"===",
"'integer'",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"value",
",",
"$",
"valueList",
",",
"true",
")",
")",
"return",
"$",
"value",
";",
"$",
"isTypeError",
"=",
"false",
";",
"}",
"else",
"$",
"isTypeError",
"=",
"true",
";",
"if",
"(",
"$",
"reason",
"!==",
"null",
")",
"throw",
"new",
"ValidationException",
"(",
"$",
"reason",
")",
";",
"if",
"(",
"$",
"isTypeError",
")",
"{",
"$",
"error",
"=",
"self",
"::",
"getErrorTemplate",
"(",
"'Int'",
")",
";",
"$",
"error",
"=",
"str_replace",
"(",
"'{{param}}'",
",",
"$",
"alias",
",",
"$",
"error",
")",
";",
"}",
"else",
"{",
"$",
"error",
"=",
"self",
"::",
"getErrorTemplate",
"(",
"'IntNotIn'",
")",
";",
"$",
"error",
"=",
"str_replace",
"(",
"'{{param}}'",
",",
"$",
"alias",
",",
"$",
"error",
")",
";",
"$",
"error",
"=",
"str_replace",
"(",
"'{{valueList}}'",
",",
"implode",
"(",
"', '",
",",
"$",
"valueList",
")",
",",
"$",
"error",
")",
";",
"}",
"throw",
"new",
"ValidationException",
"(",
"$",
"error",
")",
";",
"}"
] | 验证IntNotIn: “{{param}}”不能取这些值: {{valueList}}
@param $value mixed 参数值
@param $valueList array 不可取的值的列表
@param $reason string|null 验证失败的错误提示字符串. 如果为null, 则自动生成
@param $alias string 参数别名, 用于错误提示
@return mixed
@throws ValidationException | [
"验证IntNotIn",
":",
"“",
"{{",
"param",
"}}",
"”不能取这些值",
":",
"{{",
"valueList",
"}}"
] | train | https://github.com/photondragon/webgeeker-validation/blob/3bfc2b697ff526897c525af38c9e4ed4c889976d/src/Validation/Validation.php#L394-L427 |
photondragon/webgeeker-validation | src/Validation/Validation.php | Validation.validateFloat | public static function validateFloat($value, $reason = null, $alias = 'Parameter')
{
$type = gettype($value);
if ($type === 'string') {
if (is_numeric($value))
return $value;
} elseif ($type === 'double' || $type === 'integer')
return $value;
if ($reason !== null)
throw new ValidationException($reason);
$error = self::getErrorTemplate('Float');
$error = str_replace('{{param}}', $alias, $error);
throw new ValidationException($error);
} | php | public static function validateFloat($value, $reason = null, $alias = 'Parameter')
{
$type = gettype($value);
if ($type === 'string') {
if (is_numeric($value))
return $value;
} elseif ($type === 'double' || $type === 'integer')
return $value;
if ($reason !== null)
throw new ValidationException($reason);
$error = self::getErrorTemplate('Float');
$error = str_replace('{{param}}', $alias, $error);
throw new ValidationException($error);
} | [
"public",
"static",
"function",
"validateFloat",
"(",
"$",
"value",
",",
"$",
"reason",
"=",
"null",
",",
"$",
"alias",
"=",
"'Parameter'",
")",
"{",
"$",
"type",
"=",
"gettype",
"(",
"$",
"value",
")",
";",
"if",
"(",
"$",
"type",
"===",
"'string'",
")",
"{",
"if",
"(",
"is_numeric",
"(",
"$",
"value",
")",
")",
"return",
"$",
"value",
";",
"}",
"elseif",
"(",
"$",
"type",
"===",
"'double'",
"||",
"$",
"type",
"===",
"'integer'",
")",
"return",
"$",
"value",
";",
"if",
"(",
"$",
"reason",
"!==",
"null",
")",
"throw",
"new",
"ValidationException",
"(",
"$",
"reason",
")",
";",
"$",
"error",
"=",
"self",
"::",
"getErrorTemplate",
"(",
"'Float'",
")",
";",
"$",
"error",
"=",
"str_replace",
"(",
"'{{param}}'",
",",
"$",
"alias",
",",
"$",
"error",
")",
";",
"throw",
"new",
"ValidationException",
"(",
"$",
"error",
")",
";",
"}"
] | region float | [
"region",
"float"
] | train | https://github.com/photondragon/webgeeker-validation/blob/3bfc2b697ff526897c525af38c9e4ed4c889976d/src/Validation/Validation.php#L433-L448 |
photondragon/webgeeker-validation | src/Validation/Validation.php | Validation.validateBool | public static function validateBool($value, $reason = null, $alias = 'Parameter')
{
if (is_bool($value)) {
return $value;
} else if (is_string($value)) {
$valuelc = mb_strtolower($value);
if ($valuelc === 'true' || $valuelc === 'false')
return $value;
}
if ($reason !== null)
throw new ValidationException($reason);
$error = self::getErrorTemplate('Bool');
$error = str_replace('{{param}}', $alias, $error);
throw new ValidationException($error);
} | php | public static function validateBool($value, $reason = null, $alias = 'Parameter')
{
if (is_bool($value)) {
return $value;
} else if (is_string($value)) {
$valuelc = mb_strtolower($value);
if ($valuelc === 'true' || $valuelc === 'false')
return $value;
}
if ($reason !== null)
throw new ValidationException($reason);
$error = self::getErrorTemplate('Bool');
$error = str_replace('{{param}}', $alias, $error);
throw new ValidationException($error);
} | [
"public",
"static",
"function",
"validateBool",
"(",
"$",
"value",
",",
"$",
"reason",
"=",
"null",
",",
"$",
"alias",
"=",
"'Parameter'",
")",
"{",
"if",
"(",
"is_bool",
"(",
"$",
"value",
")",
")",
"{",
"return",
"$",
"value",
";",
"}",
"else",
"if",
"(",
"is_string",
"(",
"$",
"value",
")",
")",
"{",
"$",
"valuelc",
"=",
"mb_strtolower",
"(",
"$",
"value",
")",
";",
"if",
"(",
"$",
"valuelc",
"===",
"'true'",
"||",
"$",
"valuelc",
"===",
"'false'",
")",
"return",
"$",
"value",
";",
"}",
"if",
"(",
"$",
"reason",
"!==",
"null",
")",
"throw",
"new",
"ValidationException",
"(",
"$",
"reason",
")",
";",
"$",
"error",
"=",
"self",
"::",
"getErrorTemplate",
"(",
"'Bool'",
")",
";",
"$",
"error",
"=",
"str_replace",
"(",
"'{{param}}'",
",",
"$",
"alias",
",",
"$",
"error",
")",
";",
"throw",
"new",
"ValidationException",
"(",
"$",
"error",
")",
";",
"}"
] | region bool | [
"region",
"bool"
] | train | https://github.com/photondragon/webgeeker-validation/blob/3bfc2b697ff526897c525af38c9e4ed4c889976d/src/Validation/Validation.php#L714-L730 |
photondragon/webgeeker-validation | src/Validation/Validation.php | Validation.validateStr | public static function validateStr($value, $reason = null, $alias = 'Parameter')
{
if (is_string($value)) {
return $value;
}
if ($reason !== null)
throw new ValidationException($reason);
$error = self::getErrorTemplate('Str');
$error = str_replace('{{param}}', $alias, $error);
throw new ValidationException($error);
} | php | public static function validateStr($value, $reason = null, $alias = 'Parameter')
{
if (is_string($value)) {
return $value;
}
if ($reason !== null)
throw new ValidationException($reason);
$error = self::getErrorTemplate('Str');
$error = str_replace('{{param}}', $alias, $error);
throw new ValidationException($error);
} | [
"public",
"static",
"function",
"validateStr",
"(",
"$",
"value",
",",
"$",
"reason",
"=",
"null",
",",
"$",
"alias",
"=",
"'Parameter'",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"value",
")",
")",
"{",
"return",
"$",
"value",
";",
"}",
"if",
"(",
"$",
"reason",
"!==",
"null",
")",
"throw",
"new",
"ValidationException",
"(",
"$",
"reason",
")",
";",
"$",
"error",
"=",
"self",
"::",
"getErrorTemplate",
"(",
"'Str'",
")",
";",
"$",
"error",
"=",
"str_replace",
"(",
"'{{param}}'",
",",
"$",
"alias",
",",
"$",
"error",
")",
";",
"throw",
"new",
"ValidationException",
"(",
"$",
"error",
")",
";",
"}"
] | region string | [
"region",
"string"
] | train | https://github.com/photondragon/webgeeker-validation/blob/3bfc2b697ff526897c525af38c9e4ed4c889976d/src/Validation/Validation.php#L757-L769 |
photondragon/webgeeker-validation | src/Validation/Validation.php | Validation.validateStrNotIn | public static function validateStrNotIn($value, $valueList, $reason = null, $alias = 'Parameter')
{
if (is_array($valueList) === false || count($valueList) === 0)
throw new ValidationException("“${alias}”参数的验证模版(StrNotIn:)格式错误, 必须提供不可取的值的列表");
if (is_string($value)) {
if (!in_array($value, $valueList, true))
return $value;
$isTypeError = false;
} else
$isTypeError = true;
if ($reason !== null)
throw new ValidationException($reason);
if ($isTypeError) {
$error = self::getErrorTemplate('Str');
$error = str_replace('{{param}}', $alias, $error);
} else if (count($valueList) === 1) {
$error = self::getErrorTemplate('StrNe');
$error = str_replace('{{param}}', $alias, $error);
$error = str_replace('{{value}}', $valueList[0], $error);
} else {
$error = self::getErrorTemplate('StrNotIn');
$error = str_replace('{{param}}', $alias, $error);
$error = str_replace('{{valueList}}', '"'.implode('", "', $valueList).'"', $error);
}
throw new ValidationException($error);
} | php | public static function validateStrNotIn($value, $valueList, $reason = null, $alias = 'Parameter')
{
if (is_array($valueList) === false || count($valueList) === 0)
throw new ValidationException("“${alias}”参数的验证模版(StrNotIn:)格式错误, 必须提供不可取的值的列表");
if (is_string($value)) {
if (!in_array($value, $valueList, true))
return $value;
$isTypeError = false;
} else
$isTypeError = true;
if ($reason !== null)
throw new ValidationException($reason);
if ($isTypeError) {
$error = self::getErrorTemplate('Str');
$error = str_replace('{{param}}', $alias, $error);
} else if (count($valueList) === 1) {
$error = self::getErrorTemplate('StrNe');
$error = str_replace('{{param}}', $alias, $error);
$error = str_replace('{{value}}', $valueList[0], $error);
} else {
$error = self::getErrorTemplate('StrNotIn');
$error = str_replace('{{param}}', $alias, $error);
$error = str_replace('{{valueList}}', '"'.implode('", "', $valueList).'"', $error);
}
throw new ValidationException($error);
} | [
"public",
"static",
"function",
"validateStrNotIn",
"(",
"$",
"value",
",",
"$",
"valueList",
",",
"$",
"reason",
"=",
"null",
",",
"$",
"alias",
"=",
"'Parameter'",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"valueList",
")",
"===",
"false",
"||",
"count",
"(",
"$",
"valueList",
")",
"===",
"0",
")",
"throw",
"new",
"ValidationException",
"(",
"\"“${alias}”参数的验证模版(StrNotIn:)格式错误, 必须提供不可取的值的列表\");",
"",
"",
"if",
"(",
"is_string",
"(",
"$",
"value",
")",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"value",
",",
"$",
"valueList",
",",
"true",
")",
")",
"return",
"$",
"value",
";",
"$",
"isTypeError",
"=",
"false",
";",
"}",
"else",
"$",
"isTypeError",
"=",
"true",
";",
"if",
"(",
"$",
"reason",
"!==",
"null",
")",
"throw",
"new",
"ValidationException",
"(",
"$",
"reason",
")",
";",
"if",
"(",
"$",
"isTypeError",
")",
"{",
"$",
"error",
"=",
"self",
"::",
"getErrorTemplate",
"(",
"'Str'",
")",
";",
"$",
"error",
"=",
"str_replace",
"(",
"'{{param}}'",
",",
"$",
"alias",
",",
"$",
"error",
")",
";",
"}",
"else",
"if",
"(",
"count",
"(",
"$",
"valueList",
")",
"===",
"1",
")",
"{",
"$",
"error",
"=",
"self",
"::",
"getErrorTemplate",
"(",
"'StrNe'",
")",
";",
"$",
"error",
"=",
"str_replace",
"(",
"'{{param}}'",
",",
"$",
"alias",
",",
"$",
"error",
")",
";",
"$",
"error",
"=",
"str_replace",
"(",
"'{{value}}'",
",",
"$",
"valueList",
"[",
"0",
"]",
",",
"$",
"error",
")",
";",
"}",
"else",
"{",
"$",
"error",
"=",
"self",
"::",
"getErrorTemplate",
"(",
"'StrNotIn'",
")",
";",
"$",
"error",
"=",
"str_replace",
"(",
"'{{param}}'",
",",
"$",
"alias",
",",
"$",
"error",
")",
";",
"$",
"error",
"=",
"str_replace",
"(",
"'{{valueList}}'",
",",
"'\"'",
".",
"implode",
"(",
"'\", \"'",
",",
"$",
"valueList",
")",
".",
"'\"'",
",",
"$",
"error",
")",
";",
"}",
"throw",
"new",
"ValidationException",
"(",
"$",
"error",
")",
";",
"}"
] | 验证: “{{param}}”不能取这些值: {{valueList}}
@param $value mixed 参数值
@param $valueList array 不可取的值的列表
@param $reason string|null 验证失败的错误提示字符串. 如果为null, 则自动生成
@param $alias string 参数别名, 用于错误提示
@return mixed
@throws ValidationException | [
"验证",
":",
"“",
"{{",
"param",
"}}",
"”不能取这些值",
":",
"{{",
"valueList",
"}}"
] | train | https://github.com/photondragon/webgeeker-validation/blob/3bfc2b697ff526897c525af38c9e4ed4c889976d/src/Validation/Validation.php#L884-L912 |
photondragon/webgeeker-validation | src/Validation/Validation.php | Validation.validateStrEqI | public static function validateStrEqI($value, $equalsValue, $reason = null, $alias = 'Parameter')
{
if (is_string($value)) {
if (strcasecmp($value, $equalsValue) === 0)
return $value;
$isTypeError = false;
} else
$isTypeError = true;
if ($reason !== null)
throw new ValidationException($reason);
if ($isTypeError) {
$error = self::getErrorTemplate('Str');
$error = str_replace('{{param}}', $alias, $error);
} else {
$error = self::getErrorTemplate('StrEqI');
$error = str_replace('{{param}}', $alias, $error);
$error = str_replace('{{value}}', $equalsValue, $error);
}
throw new ValidationException($error);
} | php | public static function validateStrEqI($value, $equalsValue, $reason = null, $alias = 'Parameter')
{
if (is_string($value)) {
if (strcasecmp($value, $equalsValue) === 0)
return $value;
$isTypeError = false;
} else
$isTypeError = true;
if ($reason !== null)
throw new ValidationException($reason);
if ($isTypeError) {
$error = self::getErrorTemplate('Str');
$error = str_replace('{{param}}', $alias, $error);
} else {
$error = self::getErrorTemplate('StrEqI');
$error = str_replace('{{param}}', $alias, $error);
$error = str_replace('{{value}}', $equalsValue, $error);
}
throw new ValidationException($error);
} | [
"public",
"static",
"function",
"validateStrEqI",
"(",
"$",
"value",
",",
"$",
"equalsValue",
",",
"$",
"reason",
"=",
"null",
",",
"$",
"alias",
"=",
"'Parameter'",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"value",
")",
")",
"{",
"if",
"(",
"strcasecmp",
"(",
"$",
"value",
",",
"$",
"equalsValue",
")",
"===",
"0",
")",
"return",
"$",
"value",
";",
"$",
"isTypeError",
"=",
"false",
";",
"}",
"else",
"$",
"isTypeError",
"=",
"true",
";",
"if",
"(",
"$",
"reason",
"!==",
"null",
")",
"throw",
"new",
"ValidationException",
"(",
"$",
"reason",
")",
";",
"if",
"(",
"$",
"isTypeError",
")",
"{",
"$",
"error",
"=",
"self",
"::",
"getErrorTemplate",
"(",
"'Str'",
")",
";",
"$",
"error",
"=",
"str_replace",
"(",
"'{{param}}'",
",",
"$",
"alias",
",",
"$",
"error",
")",
";",
"}",
"else",
"{",
"$",
"error",
"=",
"self",
"::",
"getErrorTemplate",
"(",
"'StrEqI'",
")",
";",
"$",
"error",
"=",
"str_replace",
"(",
"'{{param}}'",
",",
"$",
"alias",
",",
"$",
"error",
")",
";",
"$",
"error",
"=",
"str_replace",
"(",
"'{{value}}'",
",",
"$",
"equalsValue",
",",
"$",
"error",
")",
";",
"}",
"throw",
"new",
"ValidationException",
"(",
"$",
"error",
")",
";",
"}"
] | 验证: “{{param}}”必须等于 {{equalsValue}}(忽略大小写)
@param $value string 参数值
@param $equalsValue string 比较值
@param $reason string|null 验证失败的错误提示字符串. 如果为null, 则自动生成
@param $alias string 参数别名, 用于错误提示
@return mixed
@throws ValidationException | [
"验证",
":",
"“",
"{{",
"param",
"}}",
"”必须等于",
"{{",
"equalsValue",
"}}",
"(忽略大小写)"
] | train | https://github.com/photondragon/webgeeker-validation/blob/3bfc2b697ff526897c525af38c9e4ed4c889976d/src/Validation/Validation.php#L923-L944 |
photondragon/webgeeker-validation | src/Validation/Validation.php | Validation.validateStrInI | public static function validateStrInI($value, $valueList, $reason = null, $alias = 'Parameter')
{
if (is_array($valueList) === false || count($valueList) === 0)
throw new ValidationException("“${alias}”参数的验证模版(StrInI:)格式错误, 必须提供可取值的列表");
if (is_string($value)) {
$lowerValue = mb_strtolower($value);
foreach ($valueList as $v) {
if (is_string($v) && mb_strtolower($v) === $lowerValue)
return $value;
}
$isTypeError = false;
} else
$isTypeError = true;
if ($reason !== null)
throw new ValidationException($reason);
if ($isTypeError) {
$error = self::getErrorTemplate('Str');
$error = str_replace('{{param}}', $alias, $error);
} else if (count($valueList) === 1) {
$error = self::getErrorTemplate('StrEqI');
$error = str_replace('{{param}}', $alias, $error);
$error = str_replace('{{value}}', $valueList[0], $error);
} else {
$error = self::getErrorTemplate('StrInI');
$error = str_replace('{{param}}', $alias, $error);
$error = str_replace('{{valueList}}', '"'.implode('", "', $valueList).'"', $error);
}
throw new ValidationException($error);
} | php | public static function validateStrInI($value, $valueList, $reason = null, $alias = 'Parameter')
{
if (is_array($valueList) === false || count($valueList) === 0)
throw new ValidationException("“${alias}”参数的验证模版(StrInI:)格式错误, 必须提供可取值的列表");
if (is_string($value)) {
$lowerValue = mb_strtolower($value);
foreach ($valueList as $v) {
if (is_string($v) && mb_strtolower($v) === $lowerValue)
return $value;
}
$isTypeError = false;
} else
$isTypeError = true;
if ($reason !== null)
throw new ValidationException($reason);
if ($isTypeError) {
$error = self::getErrorTemplate('Str');
$error = str_replace('{{param}}', $alias, $error);
} else if (count($valueList) === 1) {
$error = self::getErrorTemplate('StrEqI');
$error = str_replace('{{param}}', $alias, $error);
$error = str_replace('{{value}}', $valueList[0], $error);
} else {
$error = self::getErrorTemplate('StrInI');
$error = str_replace('{{param}}', $alias, $error);
$error = str_replace('{{valueList}}', '"'.implode('", "', $valueList).'"', $error);
}
throw new ValidationException($error);
} | [
"public",
"static",
"function",
"validateStrInI",
"(",
"$",
"value",
",",
"$",
"valueList",
",",
"$",
"reason",
"=",
"null",
",",
"$",
"alias",
"=",
"'Parameter'",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"valueList",
")",
"===",
"false",
"||",
"count",
"(",
"$",
"valueList",
")",
"===",
"0",
")",
"throw",
"new",
"ValidationException",
"(",
"\"“${alias}”参数的验证模版(StrInI:)格式错误, 必须提供可取值的列表\");",
"",
"",
"if",
"(",
"is_string",
"(",
"$",
"value",
")",
")",
"{",
"$",
"lowerValue",
"=",
"mb_strtolower",
"(",
"$",
"value",
")",
";",
"foreach",
"(",
"$",
"valueList",
"as",
"$",
"v",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"v",
")",
"&&",
"mb_strtolower",
"(",
"$",
"v",
")",
"===",
"$",
"lowerValue",
")",
"return",
"$",
"value",
";",
"}",
"$",
"isTypeError",
"=",
"false",
";",
"}",
"else",
"$",
"isTypeError",
"=",
"true",
";",
"if",
"(",
"$",
"reason",
"!==",
"null",
")",
"throw",
"new",
"ValidationException",
"(",
"$",
"reason",
")",
";",
"if",
"(",
"$",
"isTypeError",
")",
"{",
"$",
"error",
"=",
"self",
"::",
"getErrorTemplate",
"(",
"'Str'",
")",
";",
"$",
"error",
"=",
"str_replace",
"(",
"'{{param}}'",
",",
"$",
"alias",
",",
"$",
"error",
")",
";",
"}",
"else",
"if",
"(",
"count",
"(",
"$",
"valueList",
")",
"===",
"1",
")",
"{",
"$",
"error",
"=",
"self",
"::",
"getErrorTemplate",
"(",
"'StrEqI'",
")",
";",
"$",
"error",
"=",
"str_replace",
"(",
"'{{param}}'",
",",
"$",
"alias",
",",
"$",
"error",
")",
";",
"$",
"error",
"=",
"str_replace",
"(",
"'{{value}}'",
",",
"$",
"valueList",
"[",
"0",
"]",
",",
"$",
"error",
")",
";",
"}",
"else",
"{",
"$",
"error",
"=",
"self",
"::",
"getErrorTemplate",
"(",
"'StrInI'",
")",
";",
"$",
"error",
"=",
"str_replace",
"(",
"'{{param}}'",
",",
"$",
"alias",
",",
"$",
"error",
")",
";",
"$",
"error",
"=",
"str_replace",
"(",
"'{{valueList}}'",
",",
"'\"'",
".",
"implode",
"(",
"'\", \"'",
",",
"$",
"valueList",
")",
".",
"'\"'",
",",
"$",
"error",
")",
";",
"}",
"throw",
"new",
"ValidationException",
"(",
"$",
"error",
")",
";",
"}"
] | 验证: “{{param}}”只能取这些值: {{valueList}}(忽略大小写)
@param $value mixed 参数值
@param $valueList array 可取值的列表
@param $reason string|null 验证失败的错误提示字符串. 如果为null, 则自动生成
@param $alias string 参数别名, 用于错误提示
@return mixed
@throws ValidationException | [
"验证",
":",
"“",
"{{",
"param",
"}}",
"”只能取这些值",
":",
"{{",
"valueList",
"}}",
"(忽略大小写)"
] | train | https://github.com/photondragon/webgeeker-validation/blob/3bfc2b697ff526897c525af38c9e4ed4c889976d/src/Validation/Validation.php#L987-L1018 |
photondragon/webgeeker-validation | src/Validation/Validation.php | Validation.validateLetters | public static function validateLetters($value, $reason = null, $alias = 'Parameter')
{
if (is_string($value)) {
if (preg_match('/^[a-zA-Z]+$/', $value) === 1)
return $value;
$isTypeError = false;
} else
$isTypeError = true;
if ($reason !== null)
throw new ValidationException($reason);
if ($isTypeError) {
$error = self::getErrorTemplate('Str');
$error = str_replace('{{param}}', $alias, $error);
} else {
$error = self::getErrorTemplate('Letters');
$error = str_replace('{{param}}', $alias, $error);
}
throw new ValidationException($error);
} | php | public static function validateLetters($value, $reason = null, $alias = 'Parameter')
{
if (is_string($value)) {
if (preg_match('/^[a-zA-Z]+$/', $value) === 1)
return $value;
$isTypeError = false;
} else
$isTypeError = true;
if ($reason !== null)
throw new ValidationException($reason);
if ($isTypeError) {
$error = self::getErrorTemplate('Str');
$error = str_replace('{{param}}', $alias, $error);
} else {
$error = self::getErrorTemplate('Letters');
$error = str_replace('{{param}}', $alias, $error);
}
throw new ValidationException($error);
} | [
"public",
"static",
"function",
"validateLetters",
"(",
"$",
"value",
",",
"$",
"reason",
"=",
"null",
",",
"$",
"alias",
"=",
"'Parameter'",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"value",
")",
")",
"{",
"if",
"(",
"preg_match",
"(",
"'/^[a-zA-Z]+$/'",
",",
"$",
"value",
")",
"===",
"1",
")",
"return",
"$",
"value",
";",
"$",
"isTypeError",
"=",
"false",
";",
"}",
"else",
"$",
"isTypeError",
"=",
"true",
";",
"if",
"(",
"$",
"reason",
"!==",
"null",
")",
"throw",
"new",
"ValidationException",
"(",
"$",
"reason",
")",
";",
"if",
"(",
"$",
"isTypeError",
")",
"{",
"$",
"error",
"=",
"self",
"::",
"getErrorTemplate",
"(",
"'Str'",
")",
";",
"$",
"error",
"=",
"str_replace",
"(",
"'{{param}}'",
",",
"$",
"alias",
",",
"$",
"error",
")",
";",
"}",
"else",
"{",
"$",
"error",
"=",
"self",
"::",
"getErrorTemplate",
"(",
"'Letters'",
")",
";",
"$",
"error",
"=",
"str_replace",
"(",
"'{{param}}'",
",",
"$",
"alias",
",",
"$",
"error",
")",
";",
"}",
"throw",
"new",
"ValidationException",
"(",
"$",
"error",
")",
";",
"}"
] | 验证: “{{param}}”只能包含字母
@param $value mixed 参数值
@param $reason string|null 验证失败的错误提示字符串. 如果为null, 则自动生成
@param $alias string 参数别名, 用于错误提示
@return mixed
@throws ValidationException | [
"验证",
":",
"“",
"{{",
"param",
"}}",
"”只能包含字母"
] | train | https://github.com/photondragon/webgeeker-validation/blob/3bfc2b697ff526897c525af38c9e4ed4c889976d/src/Validation/Validation.php#L1268-L1288 |
photondragon/webgeeker-validation | src/Validation/Validation.php | Validation.validateNumeric | public static function validateNumeric($value, $reason = null, $alias = 'Parameter')
{
if (is_string($value)) {
if (preg_match('/^\-?[0-9.]+$/', $value) === 1) {
$count = 0; //小数点的个数
$i = 0;
while (($i = strpos($value, '.', $i)) !== false) {
$count++;
$i += 1;
}
if ($count === 0)
return $value;
else if ($count === 1) {
if ($value !== '.' && $value !== '-.')
return $value;
}
}
$isTypeError = false;
} else
$isTypeError = true;
if ($reason !== null)
throw new ValidationException($reason);
if ($isTypeError) {
$error = self::getErrorTemplate('Str');
$error = str_replace('{{param}}', $alias, $error);
} else {
$error = self::getErrorTemplate('Numeric');
$error = str_replace('{{param}}', $alias, $error);
}
throw new ValidationException($error);
} | php | public static function validateNumeric($value, $reason = null, $alias = 'Parameter')
{
if (is_string($value)) {
if (preg_match('/^\-?[0-9.]+$/', $value) === 1) {
$count = 0; //小数点的个数
$i = 0;
while (($i = strpos($value, '.', $i)) !== false) {
$count++;
$i += 1;
}
if ($count === 0)
return $value;
else if ($count === 1) {
if ($value !== '.' && $value !== '-.')
return $value;
}
}
$isTypeError = false;
} else
$isTypeError = true;
if ($reason !== null)
throw new ValidationException($reason);
if ($isTypeError) {
$error = self::getErrorTemplate('Str');
$error = str_replace('{{param}}', $alias, $error);
} else {
$error = self::getErrorTemplate('Numeric');
$error = str_replace('{{param}}', $alias, $error);
}
throw new ValidationException($error);
} | [
"public",
"static",
"function",
"validateNumeric",
"(",
"$",
"value",
",",
"$",
"reason",
"=",
"null",
",",
"$",
"alias",
"=",
"'Parameter'",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"value",
")",
")",
"{",
"if",
"(",
"preg_match",
"(",
"'/^\\-?[0-9.]+$/'",
",",
"$",
"value",
")",
"===",
"1",
")",
"{",
"$",
"count",
"=",
"0",
";",
"//小数点的个数",
"$",
"i",
"=",
"0",
";",
"while",
"(",
"(",
"$",
"i",
"=",
"strpos",
"(",
"$",
"value",
",",
"'.'",
",",
"$",
"i",
")",
")",
"!==",
"false",
")",
"{",
"$",
"count",
"++",
";",
"$",
"i",
"+=",
"1",
";",
"}",
"if",
"(",
"$",
"count",
"===",
"0",
")",
"return",
"$",
"value",
";",
"else",
"if",
"(",
"$",
"count",
"===",
"1",
")",
"{",
"if",
"(",
"$",
"value",
"!==",
"'.'",
"&&",
"$",
"value",
"!==",
"'-.'",
")",
"return",
"$",
"value",
";",
"}",
"}",
"$",
"isTypeError",
"=",
"false",
";",
"}",
"else",
"$",
"isTypeError",
"=",
"true",
";",
"if",
"(",
"$",
"reason",
"!==",
"null",
")",
"throw",
"new",
"ValidationException",
"(",
"$",
"reason",
")",
";",
"if",
"(",
"$",
"isTypeError",
")",
"{",
"$",
"error",
"=",
"self",
"::",
"getErrorTemplate",
"(",
"'Str'",
")",
";",
"$",
"error",
"=",
"str_replace",
"(",
"'{{param}}'",
",",
"$",
"alias",
",",
"$",
"error",
")",
";",
"}",
"else",
"{",
"$",
"error",
"=",
"self",
"::",
"getErrorTemplate",
"(",
"'Numeric'",
")",
";",
"$",
"error",
"=",
"str_replace",
"(",
"'{{param}}'",
",",
"$",
"alias",
",",
"$",
"error",
")",
";",
"}",
"throw",
"new",
"ValidationException",
"(",
"$",
"error",
")",
";",
"}"
] | 验证: “{{param}}”必须是数值
一般用于大数处理(超过double表示范围的数,一般会用字符串来表示)
如果是正常范围内的数, 可以使用'Int'或'Float'来检测
@param $value mixed 参数值
@param $reason string|null 验证失败的错误提示字符串. 如果为null, 则自动生成
@param $alias string 参数别名, 用于错误提示
@return mixed
@throws ValidationException | [
"验证",
":",
"“",
"{{",
"param",
"}}",
"”必须是数值",
"一般用于大数处理(超过double表示范围的数",
"一般会用字符串来表示)",
"如果是正常范围内的数",
"可以使用",
"Int",
"或",
"Float",
"来检测"
] | train | https://github.com/photondragon/webgeeker-validation/blob/3bfc2b697ff526897c525af38c9e4ed4c889976d/src/Validation/Validation.php#L1422-L1454 |
photondragon/webgeeker-validation | src/Validation/Validation.php | Validation.validateRegexp | public static function validateRegexp($value, $regexp, $reason = null, $alias = 'Parameter')
{
if (is_string($regexp) === false || $regexp === '')
throw new ValidationException("“${alias}”参数的验证模版(Regexp:)格式错误, 没有提供正则表达式");
if (is_string($value)) {
$result = @preg_match($regexp, $value);
if ($result === 1)
return $value;
else if ($result === false)
throw new ValidationException("“${alias}”参数的正则表达式验证失败, 请检查正则表达式是否合法");
$isTypeError = false;
} else
$isTypeError = true;
if ($reason !== null)
throw new ValidationException($reason);
if ($isTypeError) {
$error = self::getErrorTemplate('Str');
$error = str_replace('{{param}}', $alias, $error);
} else {
$error = self::getErrorTemplate('Regexp');
$error = str_replace('{{param}}', $alias, $error);
$error = str_replace('{{regexp}}', $regexp, $error);
}
throw new ValidationException($error);
} | php | public static function validateRegexp($value, $regexp, $reason = null, $alias = 'Parameter')
{
if (is_string($regexp) === false || $regexp === '')
throw new ValidationException("“${alias}”参数的验证模版(Regexp:)格式错误, 没有提供正则表达式");
if (is_string($value)) {
$result = @preg_match($regexp, $value);
if ($result === 1)
return $value;
else if ($result === false)
throw new ValidationException("“${alias}”参数的正则表达式验证失败, 请检查正则表达式是否合法");
$isTypeError = false;
} else
$isTypeError = true;
if ($reason !== null)
throw new ValidationException($reason);
if ($isTypeError) {
$error = self::getErrorTemplate('Str');
$error = str_replace('{{param}}', $alias, $error);
} else {
$error = self::getErrorTemplate('Regexp');
$error = str_replace('{{param}}', $alias, $error);
$error = str_replace('{{regexp}}', $regexp, $error);
}
throw new ValidationException($error);
} | [
"public",
"static",
"function",
"validateRegexp",
"(",
"$",
"value",
",",
"$",
"regexp",
",",
"$",
"reason",
"=",
"null",
",",
"$",
"alias",
"=",
"'Parameter'",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"regexp",
")",
"===",
"false",
"||",
"$",
"regexp",
"===",
"''",
")",
"throw",
"new",
"ValidationException",
"(",
"\"“${alias}”参数的验证模版(Regexp:)格式错误, 没有提供正则表达式\");",
"",
"",
"if",
"(",
"is_string",
"(",
"$",
"value",
")",
")",
"{",
"$",
"result",
"=",
"@",
"preg_match",
"(",
"$",
"regexp",
",",
"$",
"value",
")",
";",
"if",
"(",
"$",
"result",
"===",
"1",
")",
"return",
"$",
"value",
";",
"else",
"if",
"(",
"$",
"result",
"===",
"false",
")",
"throw",
"new",
"ValidationException",
"(",
"\"“${alias}”参数的正则表达式验证失败, 请检查正则表达式是否合法\");",
"",
"",
"$",
"isTypeError",
"=",
"false",
";",
"}",
"else",
"$",
"isTypeError",
"=",
"true",
";",
"if",
"(",
"$",
"reason",
"!==",
"null",
")",
"throw",
"new",
"ValidationException",
"(",
"$",
"reason",
")",
";",
"if",
"(",
"$",
"isTypeError",
")",
"{",
"$",
"error",
"=",
"self",
"::",
"getErrorTemplate",
"(",
"'Str'",
")",
";",
"$",
"error",
"=",
"str_replace",
"(",
"'{{param}}'",
",",
"$",
"alias",
",",
"$",
"error",
")",
";",
"}",
"else",
"{",
"$",
"error",
"=",
"self",
"::",
"getErrorTemplate",
"(",
"'Regexp'",
")",
";",
"$",
"error",
"=",
"str_replace",
"(",
"'{{param}}'",
",",
"$",
"alias",
",",
"$",
"error",
")",
";",
"$",
"error",
"=",
"str_replace",
"(",
"'{{regexp}}'",
",",
"$",
"regexp",
",",
"$",
"error",
")",
";",
"}",
"throw",
"new",
"ValidationException",
"(",
"$",
"error",
")",
";",
"}"
] | Perl正则表达式验证
@param $value string 参数值
@param $regexp string Perl正则表达式. 正则表达式内的特殊字符需要转义(包括/). 首尾无需加/
@param $reason null|string 原因(当不匹配时用于错误提示). 如果为null, 当不匹配时会提示 “${alias}”不匹配正则表达式$regexp
@param $alias string 参数别名, 用于错误提示
@return mixed
@throws ValidationException | [
"Perl正则表达式验证"
] | train | https://github.com/photondragon/webgeeker-validation/blob/3bfc2b697ff526897c525af38c9e4ed4c889976d/src/Validation/Validation.php#L1583-L1610 |
photondragon/webgeeker-validation | src/Validation/Validation.php | Validation.validateArr | public static function validateArr($value, $reason = null, $alias = 'Parameter')
{
if (is_array($value)) {
$is = true;
foreach ($value as $key => $val) {
if (!is_integer($key)) {
$is = false;
break;
}
}
if ($is)
return $value;
}
if ($reason !== null)
throw new ValidationException($reason);
$error = self::getErrorTemplate('Arr');
$error = str_replace('{{param}}', $alias, $error);
throw new ValidationException($error);
} | php | public static function validateArr($value, $reason = null, $alias = 'Parameter')
{
if (is_array($value)) {
$is = true;
foreach ($value as $key => $val) {
if (!is_integer($key)) {
$is = false;
break;
}
}
if ($is)
return $value;
}
if ($reason !== null)
throw new ValidationException($reason);
$error = self::getErrorTemplate('Arr');
$error = str_replace('{{param}}', $alias, $error);
throw new ValidationException($error);
} | [
"public",
"static",
"function",
"validateArr",
"(",
"$",
"value",
",",
"$",
"reason",
"=",
"null",
",",
"$",
"alias",
"=",
"'Parameter'",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"value",
")",
")",
"{",
"$",
"is",
"=",
"true",
";",
"foreach",
"(",
"$",
"value",
"as",
"$",
"key",
"=>",
"$",
"val",
")",
"{",
"if",
"(",
"!",
"is_integer",
"(",
"$",
"key",
")",
")",
"{",
"$",
"is",
"=",
"false",
";",
"break",
";",
"}",
"}",
"if",
"(",
"$",
"is",
")",
"return",
"$",
"value",
";",
"}",
"if",
"(",
"$",
"reason",
"!==",
"null",
")",
"throw",
"new",
"ValidationException",
"(",
"$",
"reason",
")",
";",
"$",
"error",
"=",
"self",
"::",
"getErrorTemplate",
"(",
"'Arr'",
")",
";",
"$",
"error",
"=",
"str_replace",
"(",
"'{{param}}'",
",",
"$",
"alias",
",",
"$",
"error",
")",
";",
"throw",
"new",
"ValidationException",
"(",
"$",
"error",
")",
";",
"}"
] | region array | [
"region",
"array"
] | train | https://github.com/photondragon/webgeeker-validation/blob/3bfc2b697ff526897c525af38c9e4ed4c889976d/src/Validation/Validation.php#L1616-L1636 |
photondragon/webgeeker-validation | src/Validation/Validation.php | Validation.validateIf | protected static function validateIf($value)
{
if (is_string($value))
$value = mb_strtolower($value);
return in_array($value, [1, true, '1', 'true', 'yes', 'y'], true);
} | php | protected static function validateIf($value)
{
if (is_string($value))
$value = mb_strtolower($value);
return in_array($value, [1, true, '1', 'true', 'yes', 'y'], true);
} | [
"protected",
"static",
"function",
"validateIf",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"value",
")",
")",
"$",
"value",
"=",
"mb_strtolower",
"(",
"$",
"value",
")",
";",
"return",
"in_array",
"(",
"$",
"value",
",",
"[",
"1",
",",
"true",
",",
"'1'",
",",
"'true'",
",",
"'yes'",
",",
"'y'",
"]",
",",
"true",
")",
";",
"}"
] | region ifs | [
"region",
"ifs"
] | train | https://github.com/photondragon/webgeeker-validation/blob/3bfc2b697ff526897c525af38c9e4ed4c889976d/src/Validation/Validation.php#L2401-L2406 |
photondragon/webgeeker-validation | src/Validation/Validation.php | Validation._compileValidator | private static function _compileValidator($validator, $alias)
{
if (is_string($validator) === false)
throw new ValidationException("编译Validator失败: Validator必须是字符串");;
if (strlen($validator) === 0) {
return [
'countOfIfs' => 0,
'required' => false,
'units' => [],
];
}
$countOfIfs = 0; //Ifxxx的个数
// $ifUnits = [];
$required = false;
$validatorUnits = [];
$segments = explode('|', $validator);
$segCount = count($segments);
$customReason = null;
for ($i = 0; $i < $segCount;) {
$segment = $segments[$i];
$i++;
if (strpos($segment, 'Regexp:') === 0) // 是正则表达式
{
if (strpos($segment, '/') !== 7) // 非法的正则表达. 合法的必须首尾加/
throw new ValidationException("正则表达式验证器Regexp格式错误. 正确的格式是 Regexp:/xxxx/");
$pos = 8;
$len = strlen($segment);
$finish = false;
do {
$pos2 = strripos($segment, '/'); // 反向查找字符/
if ($pos2 !== $len - 1 // 不是以/结尾, 说明正则表达式中包含了|分隔符, 正则表达式被explode拆成了多段
|| $pos2 === 7
) // 第1个/后面就没字符了, 说明正则表达式中包含了|分隔符, 正则表达式被explode拆成了多段
{
} else // 以/结尾, 可能是完整的正则表达式, 也可能是不完整的正则表达式
{
do {
$pos = strpos($segment, '\\', $pos); // 从前往后扫描转义符\
if ($pos === false) // 结尾的/前面没有转义符\, 正则表达式扫描完毕
{
$finish = true;
break;
} else if ($pos === $len - 1) // 不可能, $len-1这个位置是字符/
{
;
} else if ($pos === $len - 2) // 结尾的/前面有转义符\, 说明/只是正则表达式内容的一部分, 正则表达式尚未结束
{
$pos += 3; // 跳过“\/|”三个字符
break;
} else {
$pos += 2;
}
} while (1);
if ($finish)
break;
}
if ($i >= $segCount) // 后面没有segment了
throw new ValidationException("正则表达式验证器Regexp格式错误. 正确的格式是 Regexp:/xxxx/");
$segment .= '|';
$segment .= $segments[$i]; // 拼接后面一个segment
$len = strlen($segment);
$i++;
continue;
} while (1);
$validatorUnits[] = ['Regexp', substr($segment, 7)];
} // end if(strpos($segment, 'Regexp:')===0)
else {
$pos = strpos($segment, ':');
if ($pos === false) {
if ($segment === 'Required') {
if (count($validatorUnits) > $countOfIfs)
throw new ValidationException("Required只能出现在验证器的开头(IfXxx后面)");
$required = true;
} else
$validatorUnits[] = [$segment];
} else {
$validatorName = substr($segment, 0, $pos);
$p = substr($segment, $pos + 1);
if ($p === false) {
if ($pos + 1 === strlen($segment))
$p = '';
}
if (strlen($validatorName) === 0) {
throw new ValidationException("无法识别的验证子“${segment}”");
}
switch ($validatorName) {
case 'IntEq':
case 'IntGt':
case 'IntGe':
case 'IntLt':
case 'IntLe':
case 'StrLen':
case 'StrLenGe':
case 'StrLenLe':
case 'ByteLen':
case 'ByteLenGe':
case 'ByteLenLe':
case 'ArrLen':
case 'ArrLenGe':
case 'ArrLenLe':
if (self::_isIntOrIntString($p) === false)
self::_throwFormatError($validatorName);
$validator = [$validatorName, intval($p)];
break;
case 'IntGtLt':
case 'IntGeLe':
case 'IntGtLe':
case 'IntGeLt':
case 'StrLenGeLe':
case 'ByteLenGeLe':
case 'ArrLenGeLe':
$vals = explode(',', $p);
if (count($vals) !== 2)
self::_throwFormatError($validatorName);
$p1 = $vals[0];
$p2 = $vals[1];
if (self::_isIntOrIntString($p1) === false || self::_isIntOrIntString($p2) === false)
self::_throwFormatError($validatorName);
$validator = [$validatorName, intval($p1), intval($p2)];
break;
case 'IntIn':
case 'IntNotIn':
$ints = self::_parseIntArray($p);
if ($ints === false)
self::_throwFormatError($validatorName);
$validator = [$validatorName, $ints];
break;
case 'StrEq':
case 'StrNe':
case 'StrEqI':
case 'StrNeI':
$validator = [$validatorName, $p];
break;
case 'StrIn':
case 'StrNotIn':
case 'StrInI':
case 'StrNotInI':
$strings = self::_parseStringArray($p);
if ($strings === false)
self::_throwFormatError($validatorName);
$validator = [$validatorName, $strings];
break;
case 'IfIntEq':
case 'IfIntNe':
case 'IfIntGt':
case 'IfIntLt':
case 'IfIntGe':
case 'IfIntLe':
if (count($validatorUnits) > $countOfIfs)
throw new ValidationException("IfXxx只能出现在验证器的开头");
$params = self::_parseIfXxxWith1Param1Int($p, $validatorName);
if ($params === false)
self::_throwFormatError($validatorName);
$validator = [$validatorName, $params[0], $params[1]];
$countOfIfs++;
break;
case 'IfIntIn':
case 'IfIntNotIn':
if (count($validatorUnits) > $countOfIfs)
throw new ValidationException("IfXxx只能出现在验证器的开头");
$params = self::_parseIfXxxWith1ParamMultiInts($p, $validatorName);
if ($params === false)
self::_throwFormatError($validatorName);
$validator = [$validatorName, $params[0], $params[1]];
$countOfIfs++;
break;
case 'IfStrEq':
case 'IfStrNe':
case 'IfStrGt':
case 'IfStrLt':
case 'IfStrGe':
case 'IfStrLe':
if (count($validatorUnits) > $countOfIfs)
throw new ValidationException("IfXxx只能出现在验证器的开头");
$params = self::_parseIfXxxWith1Param1Str($p, $validatorName);
if ($params === false)
self::_throwFormatError($validatorName);
$validator = [$validatorName, $params[0], $params[1]];
$countOfIfs++;
break;
case 'IfStrIn':
case 'IfStrNotIn':
if (count($validatorUnits) > $countOfIfs)
throw new ValidationException("IfXxx只能出现在验证器的开头");
$params = self::_parseIfXxxWith1ParamMultiStrings($p, $validatorName);
if ($params === false)
self::_throwFormatError($validatorName);
$validator = [$validatorName, $params[0], $params[1]];
$countOfIfs++;
break;
case 'If':
case 'IfNot':
case 'IfExist':
case 'IfNotExist':
case 'IfTrue':
case 'IfFalse':
// case 'IfSame':
// case 'IfNotSame':
if (count($validatorUnits) > $countOfIfs)
throw new ValidationException("IfXxx只能出现在验证器的开头");
$varname = self::_parseIfXxxWith1Param($p);
if ($varname === false)
self::_throwFormatError($validatorName);
$validator = [$validatorName, $varname];
$countOfIfs++;
break;
// case 'IfAny':
// break;
case 'FloatGt':
case 'FloatGe':
case 'FloatLt':
case 'FloatLe':
if (is_numeric($p) === false)
self::_throwFormatError($validatorName);
$validator = [$validatorName, doubleval($p)];
break;
case 'FloatGtLt':
case 'FloatGeLe':
case 'FloatGtLe':
case 'FloatGeLt':
$vals = explode(',', $p);
if (count($vals) !== 2)
self::_throwFormatError($validatorName);
$p1 = $vals[0];
$p2 = $vals[1];
if (is_numeric($p1) === false || is_numeric($p2) === false)
self::_throwFormatError($validatorName);
$validator = [$validatorName, doubleval($p1), doubleval($p2)];
break;
case 'DateFrom':
case 'DateTo':
$p = trim($p);
$timestamp = self::_parseDateString($p);
if ($timestamp === null)
self::_throwFormatError($validatorName);
$validator = [$validatorName, $timestamp];
break;
case 'DateFromTo':
$p = trim($p);
$timestamps = self::_parseTwoDateStrings($p);
if ($timestamps === null)
self::_throwFormatError($validatorName);
$validator = [$validatorName, $timestamps[0], $timestamps[1]];
break;
case 'DateTimeFrom':
case 'DateTimeTo':
$p = trim($p);
$timestamp = self::_parseDateTimeString($p);
if ($timestamp === null)
self::_throwFormatError($validatorName);
$validator = [$validatorName, $timestamp];
break;
case 'DateTimeFromTo':
$p = trim($p);
$timestamps = self::_parseTwoDateTimeStrings($p);
if ($timestamps === null)
self::_throwFormatError($validatorName);
$validator = [$validatorName, $timestamps[0], $timestamps[1]];
break;
case 'FileMimes':
$mimes = self::_parseMimesArray($p);
if ($mimes === false)
self::_throwFormatError($validatorName);
$validator = [$validatorName, $mimes, $p];
break;
case 'FileMaxSize':
case 'FileMinSize':
$size = self::_parseSizeString($p);
if ($size === null)
self::_throwFormatError($validatorName);
$validator = [$validatorName, $size, $p];
break;
case '>>>':
$customReason = $p;
// >>>:之后的所有字符都属于错误提示字符串
for (; $i < $segCount; $i++) {
$customReason .= '|' . $segments[$i];
}
$customReason = static::translateText($customReason);
$validator = null;
break;
case 'Alias':
if (strlen($p))
$alias = static::translateText($p);
$validator = null;
break;
default:
throw new ValidationException("无法识别的验证子“${segment}”");
}
if ($validator)
$validatorUnits[] = $validator;
} // end if 有冒号:分隔符
} // end else 不是Regexp
} // end for ($segments)
if (!is_string($alias) || strlen($alias) === 0)
$alias = 'UnknownParameter';
for ($i = count($validatorUnits) - 1; $i >= 0; $i--) {
$validatorUnits[$i][] = $customReason;
$validatorUnits[$i][] = $alias;
}
return [
'countOfIfs' => $countOfIfs,
'required' => $required,
'units' => $validatorUnits,
];
} | php | private static function _compileValidator($validator, $alias)
{
if (is_string($validator) === false)
throw new ValidationException("编译Validator失败: Validator必须是字符串");;
if (strlen($validator) === 0) {
return [
'countOfIfs' => 0,
'required' => false,
'units' => [],
];
}
$countOfIfs = 0; //Ifxxx的个数
// $ifUnits = [];
$required = false;
$validatorUnits = [];
$segments = explode('|', $validator);
$segCount = count($segments);
$customReason = null;
for ($i = 0; $i < $segCount;) {
$segment = $segments[$i];
$i++;
if (strpos($segment, 'Regexp:') === 0) // 是正则表达式
{
if (strpos($segment, '/') !== 7) // 非法的正则表达. 合法的必须首尾加/
throw new ValidationException("正则表达式验证器Regexp格式错误. 正确的格式是 Regexp:/xxxx/");
$pos = 8;
$len = strlen($segment);
$finish = false;
do {
$pos2 = strripos($segment, '/'); // 反向查找字符/
if ($pos2 !== $len - 1 // 不是以/结尾, 说明正则表达式中包含了|分隔符, 正则表达式被explode拆成了多段
|| $pos2 === 7
) // 第1个/后面就没字符了, 说明正则表达式中包含了|分隔符, 正则表达式被explode拆成了多段
{
} else // 以/结尾, 可能是完整的正则表达式, 也可能是不完整的正则表达式
{
do {
$pos = strpos($segment, '\\', $pos); // 从前往后扫描转义符\
if ($pos === false) // 结尾的/前面没有转义符\, 正则表达式扫描完毕
{
$finish = true;
break;
} else if ($pos === $len - 1) // 不可能, $len-1这个位置是字符/
{
;
} else if ($pos === $len - 2) // 结尾的/前面有转义符\, 说明/只是正则表达式内容的一部分, 正则表达式尚未结束
{
$pos += 3; // 跳过“\/|”三个字符
break;
} else {
$pos += 2;
}
} while (1);
if ($finish)
break;
}
if ($i >= $segCount) // 后面没有segment了
throw new ValidationException("正则表达式验证器Regexp格式错误. 正确的格式是 Regexp:/xxxx/");
$segment .= '|';
$segment .= $segments[$i]; // 拼接后面一个segment
$len = strlen($segment);
$i++;
continue;
} while (1);
$validatorUnits[] = ['Regexp', substr($segment, 7)];
} // end if(strpos($segment, 'Regexp:')===0)
else {
$pos = strpos($segment, ':');
if ($pos === false) {
if ($segment === 'Required') {
if (count($validatorUnits) > $countOfIfs)
throw new ValidationException("Required只能出现在验证器的开头(IfXxx后面)");
$required = true;
} else
$validatorUnits[] = [$segment];
} else {
$validatorName = substr($segment, 0, $pos);
$p = substr($segment, $pos + 1);
if ($p === false) {
if ($pos + 1 === strlen($segment))
$p = '';
}
if (strlen($validatorName) === 0) {
throw new ValidationException("无法识别的验证子“${segment}”");
}
switch ($validatorName) {
case 'IntEq':
case 'IntGt':
case 'IntGe':
case 'IntLt':
case 'IntLe':
case 'StrLen':
case 'StrLenGe':
case 'StrLenLe':
case 'ByteLen':
case 'ByteLenGe':
case 'ByteLenLe':
case 'ArrLen':
case 'ArrLenGe':
case 'ArrLenLe':
if (self::_isIntOrIntString($p) === false)
self::_throwFormatError($validatorName);
$validator = [$validatorName, intval($p)];
break;
case 'IntGtLt':
case 'IntGeLe':
case 'IntGtLe':
case 'IntGeLt':
case 'StrLenGeLe':
case 'ByteLenGeLe':
case 'ArrLenGeLe':
$vals = explode(',', $p);
if (count($vals) !== 2)
self::_throwFormatError($validatorName);
$p1 = $vals[0];
$p2 = $vals[1];
if (self::_isIntOrIntString($p1) === false || self::_isIntOrIntString($p2) === false)
self::_throwFormatError($validatorName);
$validator = [$validatorName, intval($p1), intval($p2)];
break;
case 'IntIn':
case 'IntNotIn':
$ints = self::_parseIntArray($p);
if ($ints === false)
self::_throwFormatError($validatorName);
$validator = [$validatorName, $ints];
break;
case 'StrEq':
case 'StrNe':
case 'StrEqI':
case 'StrNeI':
$validator = [$validatorName, $p];
break;
case 'StrIn':
case 'StrNotIn':
case 'StrInI':
case 'StrNotInI':
$strings = self::_parseStringArray($p);
if ($strings === false)
self::_throwFormatError($validatorName);
$validator = [$validatorName, $strings];
break;
case 'IfIntEq':
case 'IfIntNe':
case 'IfIntGt':
case 'IfIntLt':
case 'IfIntGe':
case 'IfIntLe':
if (count($validatorUnits) > $countOfIfs)
throw new ValidationException("IfXxx只能出现在验证器的开头");
$params = self::_parseIfXxxWith1Param1Int($p, $validatorName);
if ($params === false)
self::_throwFormatError($validatorName);
$validator = [$validatorName, $params[0], $params[1]];
$countOfIfs++;
break;
case 'IfIntIn':
case 'IfIntNotIn':
if (count($validatorUnits) > $countOfIfs)
throw new ValidationException("IfXxx只能出现在验证器的开头");
$params = self::_parseIfXxxWith1ParamMultiInts($p, $validatorName);
if ($params === false)
self::_throwFormatError($validatorName);
$validator = [$validatorName, $params[0], $params[1]];
$countOfIfs++;
break;
case 'IfStrEq':
case 'IfStrNe':
case 'IfStrGt':
case 'IfStrLt':
case 'IfStrGe':
case 'IfStrLe':
if (count($validatorUnits) > $countOfIfs)
throw new ValidationException("IfXxx只能出现在验证器的开头");
$params = self::_parseIfXxxWith1Param1Str($p, $validatorName);
if ($params === false)
self::_throwFormatError($validatorName);
$validator = [$validatorName, $params[0], $params[1]];
$countOfIfs++;
break;
case 'IfStrIn':
case 'IfStrNotIn':
if (count($validatorUnits) > $countOfIfs)
throw new ValidationException("IfXxx只能出现在验证器的开头");
$params = self::_parseIfXxxWith1ParamMultiStrings($p, $validatorName);
if ($params === false)
self::_throwFormatError($validatorName);
$validator = [$validatorName, $params[0], $params[1]];
$countOfIfs++;
break;
case 'If':
case 'IfNot':
case 'IfExist':
case 'IfNotExist':
case 'IfTrue':
case 'IfFalse':
// case 'IfSame':
// case 'IfNotSame':
if (count($validatorUnits) > $countOfIfs)
throw new ValidationException("IfXxx只能出现在验证器的开头");
$varname = self::_parseIfXxxWith1Param($p);
if ($varname === false)
self::_throwFormatError($validatorName);
$validator = [$validatorName, $varname];
$countOfIfs++;
break;
// case 'IfAny':
// break;
case 'FloatGt':
case 'FloatGe':
case 'FloatLt':
case 'FloatLe':
if (is_numeric($p) === false)
self::_throwFormatError($validatorName);
$validator = [$validatorName, doubleval($p)];
break;
case 'FloatGtLt':
case 'FloatGeLe':
case 'FloatGtLe':
case 'FloatGeLt':
$vals = explode(',', $p);
if (count($vals) !== 2)
self::_throwFormatError($validatorName);
$p1 = $vals[0];
$p2 = $vals[1];
if (is_numeric($p1) === false || is_numeric($p2) === false)
self::_throwFormatError($validatorName);
$validator = [$validatorName, doubleval($p1), doubleval($p2)];
break;
case 'DateFrom':
case 'DateTo':
$p = trim($p);
$timestamp = self::_parseDateString($p);
if ($timestamp === null)
self::_throwFormatError($validatorName);
$validator = [$validatorName, $timestamp];
break;
case 'DateFromTo':
$p = trim($p);
$timestamps = self::_parseTwoDateStrings($p);
if ($timestamps === null)
self::_throwFormatError($validatorName);
$validator = [$validatorName, $timestamps[0], $timestamps[1]];
break;
case 'DateTimeFrom':
case 'DateTimeTo':
$p = trim($p);
$timestamp = self::_parseDateTimeString($p);
if ($timestamp === null)
self::_throwFormatError($validatorName);
$validator = [$validatorName, $timestamp];
break;
case 'DateTimeFromTo':
$p = trim($p);
$timestamps = self::_parseTwoDateTimeStrings($p);
if ($timestamps === null)
self::_throwFormatError($validatorName);
$validator = [$validatorName, $timestamps[0], $timestamps[1]];
break;
case 'FileMimes':
$mimes = self::_parseMimesArray($p);
if ($mimes === false)
self::_throwFormatError($validatorName);
$validator = [$validatorName, $mimes, $p];
break;
case 'FileMaxSize':
case 'FileMinSize':
$size = self::_parseSizeString($p);
if ($size === null)
self::_throwFormatError($validatorName);
$validator = [$validatorName, $size, $p];
break;
case '>>>':
$customReason = $p;
// >>>:之后的所有字符都属于错误提示字符串
for (; $i < $segCount; $i++) {
$customReason .= '|' . $segments[$i];
}
$customReason = static::translateText($customReason);
$validator = null;
break;
case 'Alias':
if (strlen($p))
$alias = static::translateText($p);
$validator = null;
break;
default:
throw new ValidationException("无法识别的验证子“${segment}”");
}
if ($validator)
$validatorUnits[] = $validator;
} // end if 有冒号:分隔符
} // end else 不是Regexp
} // end for ($segments)
if (!is_string($alias) || strlen($alias) === 0)
$alias = 'UnknownParameter';
for ($i = count($validatorUnits) - 1; $i >= 0; $i--) {
$validatorUnits[$i][] = $customReason;
$validatorUnits[$i][] = $alias;
}
return [
'countOfIfs' => $countOfIfs,
'required' => $required,
'units' => $validatorUnits,
];
} | [
"private",
"static",
"function",
"_compileValidator",
"(",
"$",
"validator",
",",
"$",
"alias",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"validator",
")",
"===",
"false",
")",
"throw",
"new",
"ValidationException",
"(",
"\"编译Validator失败: Validator必须是字符串\");;",
"",
"",
"",
"if",
"(",
"strlen",
"(",
"$",
"validator",
")",
"===",
"0",
")",
"{",
"return",
"[",
"'countOfIfs'",
"=>",
"0",
",",
"'required'",
"=>",
"false",
",",
"'units'",
"=>",
"[",
"]",
",",
"]",
";",
"}",
"$",
"countOfIfs",
"=",
"0",
";",
"//Ifxxx的个数",
"// $ifUnits = [];",
"$",
"required",
"=",
"false",
";",
"$",
"validatorUnits",
"=",
"[",
"]",
";",
"$",
"segments",
"=",
"explode",
"(",
"'|'",
",",
"$",
"validator",
")",
";",
"$",
"segCount",
"=",
"count",
"(",
"$",
"segments",
")",
";",
"$",
"customReason",
"=",
"null",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"segCount",
";",
")",
"{",
"$",
"segment",
"=",
"$",
"segments",
"[",
"$",
"i",
"]",
";",
"$",
"i",
"++",
";",
"if",
"(",
"strpos",
"(",
"$",
"segment",
",",
"'Regexp:'",
")",
"===",
"0",
")",
"// 是正则表达式",
"{",
"if",
"(",
"strpos",
"(",
"$",
"segment",
",",
"'/'",
")",
"!==",
"7",
")",
"// 非法的正则表达. 合法的必须首尾加/",
"throw",
"new",
"ValidationException",
"(",
"\"正则表达式验证器Regexp格式错误. 正确的格式是 Regexp:/xxxx/\");",
"",
"",
"$",
"pos",
"=",
"8",
";",
"$",
"len",
"=",
"strlen",
"(",
"$",
"segment",
")",
";",
"$",
"finish",
"=",
"false",
";",
"do",
"{",
"$",
"pos2",
"=",
"strripos",
"(",
"$",
"segment",
",",
"'/'",
")",
";",
"// 反向查找字符/",
"if",
"(",
"$",
"pos2",
"!==",
"$",
"len",
"-",
"1",
"// 不是以/结尾, 说明正则表达式中包含了|分隔符, 正则表达式被explode拆成了多段",
"||",
"$",
"pos2",
"===",
"7",
")",
"// 第1个/后面就没字符了, 说明正则表达式中包含了|分隔符, 正则表达式被explode拆成了多段",
"{",
"}",
"else",
"// 以/结尾, 可能是完整的正则表达式, 也可能是不完整的正则表达式",
"{",
"do",
"{",
"$",
"pos",
"=",
"strpos",
"(",
"$",
"segment",
",",
"'\\\\'",
",",
"$",
"pos",
")",
";",
"// 从前往后扫描转义符\\",
"if",
"(",
"$",
"pos",
"===",
"false",
")",
"// 结尾的/前面没有转义符\\, 正则表达式扫描完毕",
"{",
"$",
"finish",
"=",
"true",
";",
"break",
";",
"}",
"else",
"if",
"(",
"$",
"pos",
"===",
"$",
"len",
"-",
"1",
")",
"// 不可能, $len-1这个位置是字符/",
"{",
";",
"}",
"else",
"if",
"(",
"$",
"pos",
"===",
"$",
"len",
"-",
"2",
")",
"// 结尾的/前面有转义符\\, 说明/只是正则表达式内容的一部分, 正则表达式尚未结束",
"{",
"$",
"pos",
"+=",
"3",
";",
"// 跳过“\\/|”三个字符",
"break",
";",
"}",
"else",
"{",
"$",
"pos",
"+=",
"2",
";",
"}",
"}",
"while",
"(",
"1",
")",
";",
"if",
"(",
"$",
"finish",
")",
"break",
";",
"}",
"if",
"(",
"$",
"i",
">=",
"$",
"segCount",
")",
"// 后面没有segment了",
"throw",
"new",
"ValidationException",
"(",
"\"正则表达式验证器Regexp格式错误. 正确的格式是 Regexp:/xxxx/\");",
"",
"",
"$",
"segment",
".=",
"'|'",
";",
"$",
"segment",
".=",
"$",
"segments",
"[",
"$",
"i",
"]",
";",
"// 拼接后面一个segment",
"$",
"len",
"=",
"strlen",
"(",
"$",
"segment",
")",
";",
"$",
"i",
"++",
";",
"continue",
";",
"}",
"while",
"(",
"1",
")",
";",
"$",
"validatorUnits",
"[",
"]",
"=",
"[",
"'Regexp'",
",",
"substr",
"(",
"$",
"segment",
",",
"7",
")",
"]",
";",
"}",
"// end if(strpos($segment, 'Regexp:')===0)",
"else",
"{",
"$",
"pos",
"=",
"strpos",
"(",
"$",
"segment",
",",
"':'",
")",
";",
"if",
"(",
"$",
"pos",
"===",
"false",
")",
"{",
"if",
"(",
"$",
"segment",
"===",
"'Required'",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"validatorUnits",
")",
">",
"$",
"countOfIfs",
")",
"throw",
"new",
"ValidationException",
"(",
"\"Required只能出现在验证器的开头(IfXxx后面)\");",
"",
"",
"$",
"required",
"=",
"true",
";",
"}",
"else",
"$",
"validatorUnits",
"[",
"]",
"=",
"[",
"$",
"segment",
"]",
";",
"}",
"else",
"{",
"$",
"validatorName",
"=",
"substr",
"(",
"$",
"segment",
",",
"0",
",",
"$",
"pos",
")",
";",
"$",
"p",
"=",
"substr",
"(",
"$",
"segment",
",",
"$",
"pos",
"+",
"1",
")",
";",
"if",
"(",
"$",
"p",
"===",
"false",
")",
"{",
"if",
"(",
"$",
"pos",
"+",
"1",
"===",
"strlen",
"(",
"$",
"segment",
")",
")",
"$",
"p",
"=",
"''",
";",
"}",
"if",
"(",
"strlen",
"(",
"$",
"validatorName",
")",
"===",
"0",
")",
"{",
"throw",
"new",
"ValidationException",
"(",
"\"无法识别的验证子“${segment}”\");",
"",
"",
"}",
"switch",
"(",
"$",
"validatorName",
")",
"{",
"case",
"'IntEq'",
":",
"case",
"'IntGt'",
":",
"case",
"'IntGe'",
":",
"case",
"'IntLt'",
":",
"case",
"'IntLe'",
":",
"case",
"'StrLen'",
":",
"case",
"'StrLenGe'",
":",
"case",
"'StrLenLe'",
":",
"case",
"'ByteLen'",
":",
"case",
"'ByteLenGe'",
":",
"case",
"'ByteLenLe'",
":",
"case",
"'ArrLen'",
":",
"case",
"'ArrLenGe'",
":",
"case",
"'ArrLenLe'",
":",
"if",
"(",
"self",
"::",
"_isIntOrIntString",
"(",
"$",
"p",
")",
"===",
"false",
")",
"self",
"::",
"_throwFormatError",
"(",
"$",
"validatorName",
")",
";",
"$",
"validator",
"=",
"[",
"$",
"validatorName",
",",
"intval",
"(",
"$",
"p",
")",
"]",
";",
"break",
";",
"case",
"'IntGtLt'",
":",
"case",
"'IntGeLe'",
":",
"case",
"'IntGtLe'",
":",
"case",
"'IntGeLt'",
":",
"case",
"'StrLenGeLe'",
":",
"case",
"'ByteLenGeLe'",
":",
"case",
"'ArrLenGeLe'",
":",
"$",
"vals",
"=",
"explode",
"(",
"','",
",",
"$",
"p",
")",
";",
"if",
"(",
"count",
"(",
"$",
"vals",
")",
"!==",
"2",
")",
"self",
"::",
"_throwFormatError",
"(",
"$",
"validatorName",
")",
";",
"$",
"p1",
"=",
"$",
"vals",
"[",
"0",
"]",
";",
"$",
"p2",
"=",
"$",
"vals",
"[",
"1",
"]",
";",
"if",
"(",
"self",
"::",
"_isIntOrIntString",
"(",
"$",
"p1",
")",
"===",
"false",
"||",
"self",
"::",
"_isIntOrIntString",
"(",
"$",
"p2",
")",
"===",
"false",
")",
"self",
"::",
"_throwFormatError",
"(",
"$",
"validatorName",
")",
";",
"$",
"validator",
"=",
"[",
"$",
"validatorName",
",",
"intval",
"(",
"$",
"p1",
")",
",",
"intval",
"(",
"$",
"p2",
")",
"]",
";",
"break",
";",
"case",
"'IntIn'",
":",
"case",
"'IntNotIn'",
":",
"$",
"ints",
"=",
"self",
"::",
"_parseIntArray",
"(",
"$",
"p",
")",
";",
"if",
"(",
"$",
"ints",
"===",
"false",
")",
"self",
"::",
"_throwFormatError",
"(",
"$",
"validatorName",
")",
";",
"$",
"validator",
"=",
"[",
"$",
"validatorName",
",",
"$",
"ints",
"]",
";",
"break",
";",
"case",
"'StrEq'",
":",
"case",
"'StrNe'",
":",
"case",
"'StrEqI'",
":",
"case",
"'StrNeI'",
":",
"$",
"validator",
"=",
"[",
"$",
"validatorName",
",",
"$",
"p",
"]",
";",
"break",
";",
"case",
"'StrIn'",
":",
"case",
"'StrNotIn'",
":",
"case",
"'StrInI'",
":",
"case",
"'StrNotInI'",
":",
"$",
"strings",
"=",
"self",
"::",
"_parseStringArray",
"(",
"$",
"p",
")",
";",
"if",
"(",
"$",
"strings",
"===",
"false",
")",
"self",
"::",
"_throwFormatError",
"(",
"$",
"validatorName",
")",
";",
"$",
"validator",
"=",
"[",
"$",
"validatorName",
",",
"$",
"strings",
"]",
";",
"break",
";",
"case",
"'IfIntEq'",
":",
"case",
"'IfIntNe'",
":",
"case",
"'IfIntGt'",
":",
"case",
"'IfIntLt'",
":",
"case",
"'IfIntGe'",
":",
"case",
"'IfIntLe'",
":",
"if",
"(",
"count",
"(",
"$",
"validatorUnits",
")",
">",
"$",
"countOfIfs",
")",
"throw",
"new",
"ValidationException",
"(",
"\"IfXxx只能出现在验证器的开头\");",
"",
"",
"$",
"params",
"=",
"self",
"::",
"_parseIfXxxWith1Param1Int",
"(",
"$",
"p",
",",
"$",
"validatorName",
")",
";",
"if",
"(",
"$",
"params",
"===",
"false",
")",
"self",
"::",
"_throwFormatError",
"(",
"$",
"validatorName",
")",
";",
"$",
"validator",
"=",
"[",
"$",
"validatorName",
",",
"$",
"params",
"[",
"0",
"]",
",",
"$",
"params",
"[",
"1",
"]",
"]",
";",
"$",
"countOfIfs",
"++",
";",
"break",
";",
"case",
"'IfIntIn'",
":",
"case",
"'IfIntNotIn'",
":",
"if",
"(",
"count",
"(",
"$",
"validatorUnits",
")",
">",
"$",
"countOfIfs",
")",
"throw",
"new",
"ValidationException",
"(",
"\"IfXxx只能出现在验证器的开头\");",
"",
"",
"$",
"params",
"=",
"self",
"::",
"_parseIfXxxWith1ParamMultiInts",
"(",
"$",
"p",
",",
"$",
"validatorName",
")",
";",
"if",
"(",
"$",
"params",
"===",
"false",
")",
"self",
"::",
"_throwFormatError",
"(",
"$",
"validatorName",
")",
";",
"$",
"validator",
"=",
"[",
"$",
"validatorName",
",",
"$",
"params",
"[",
"0",
"]",
",",
"$",
"params",
"[",
"1",
"]",
"]",
";",
"$",
"countOfIfs",
"++",
";",
"break",
";",
"case",
"'IfStrEq'",
":",
"case",
"'IfStrNe'",
":",
"case",
"'IfStrGt'",
":",
"case",
"'IfStrLt'",
":",
"case",
"'IfStrGe'",
":",
"case",
"'IfStrLe'",
":",
"if",
"(",
"count",
"(",
"$",
"validatorUnits",
")",
">",
"$",
"countOfIfs",
")",
"throw",
"new",
"ValidationException",
"(",
"\"IfXxx只能出现在验证器的开头\");",
"",
"",
"$",
"params",
"=",
"self",
"::",
"_parseIfXxxWith1Param1Str",
"(",
"$",
"p",
",",
"$",
"validatorName",
")",
";",
"if",
"(",
"$",
"params",
"===",
"false",
")",
"self",
"::",
"_throwFormatError",
"(",
"$",
"validatorName",
")",
";",
"$",
"validator",
"=",
"[",
"$",
"validatorName",
",",
"$",
"params",
"[",
"0",
"]",
",",
"$",
"params",
"[",
"1",
"]",
"]",
";",
"$",
"countOfIfs",
"++",
";",
"break",
";",
"case",
"'IfStrIn'",
":",
"case",
"'IfStrNotIn'",
":",
"if",
"(",
"count",
"(",
"$",
"validatorUnits",
")",
">",
"$",
"countOfIfs",
")",
"throw",
"new",
"ValidationException",
"(",
"\"IfXxx只能出现在验证器的开头\");",
"",
"",
"$",
"params",
"=",
"self",
"::",
"_parseIfXxxWith1ParamMultiStrings",
"(",
"$",
"p",
",",
"$",
"validatorName",
")",
";",
"if",
"(",
"$",
"params",
"===",
"false",
")",
"self",
"::",
"_throwFormatError",
"(",
"$",
"validatorName",
")",
";",
"$",
"validator",
"=",
"[",
"$",
"validatorName",
",",
"$",
"params",
"[",
"0",
"]",
",",
"$",
"params",
"[",
"1",
"]",
"]",
";",
"$",
"countOfIfs",
"++",
";",
"break",
";",
"case",
"'If'",
":",
"case",
"'IfNot'",
":",
"case",
"'IfExist'",
":",
"case",
"'IfNotExist'",
":",
"case",
"'IfTrue'",
":",
"case",
"'IfFalse'",
":",
"// case 'IfSame':",
"// case 'IfNotSame':",
"if",
"(",
"count",
"(",
"$",
"validatorUnits",
")",
">",
"$",
"countOfIfs",
")",
"throw",
"new",
"ValidationException",
"(",
"\"IfXxx只能出现在验证器的开头\");",
"",
"",
"$",
"varname",
"=",
"self",
"::",
"_parseIfXxxWith1Param",
"(",
"$",
"p",
")",
";",
"if",
"(",
"$",
"varname",
"===",
"false",
")",
"self",
"::",
"_throwFormatError",
"(",
"$",
"validatorName",
")",
";",
"$",
"validator",
"=",
"[",
"$",
"validatorName",
",",
"$",
"varname",
"]",
";",
"$",
"countOfIfs",
"++",
";",
"break",
";",
"// case 'IfAny':",
"// break;",
"case",
"'FloatGt'",
":",
"case",
"'FloatGe'",
":",
"case",
"'FloatLt'",
":",
"case",
"'FloatLe'",
":",
"if",
"(",
"is_numeric",
"(",
"$",
"p",
")",
"===",
"false",
")",
"self",
"::",
"_throwFormatError",
"(",
"$",
"validatorName",
")",
";",
"$",
"validator",
"=",
"[",
"$",
"validatorName",
",",
"doubleval",
"(",
"$",
"p",
")",
"]",
";",
"break",
";",
"case",
"'FloatGtLt'",
":",
"case",
"'FloatGeLe'",
":",
"case",
"'FloatGtLe'",
":",
"case",
"'FloatGeLt'",
":",
"$",
"vals",
"=",
"explode",
"(",
"','",
",",
"$",
"p",
")",
";",
"if",
"(",
"count",
"(",
"$",
"vals",
")",
"!==",
"2",
")",
"self",
"::",
"_throwFormatError",
"(",
"$",
"validatorName",
")",
";",
"$",
"p1",
"=",
"$",
"vals",
"[",
"0",
"]",
";",
"$",
"p2",
"=",
"$",
"vals",
"[",
"1",
"]",
";",
"if",
"(",
"is_numeric",
"(",
"$",
"p1",
")",
"===",
"false",
"||",
"is_numeric",
"(",
"$",
"p2",
")",
"===",
"false",
")",
"self",
"::",
"_throwFormatError",
"(",
"$",
"validatorName",
")",
";",
"$",
"validator",
"=",
"[",
"$",
"validatorName",
",",
"doubleval",
"(",
"$",
"p1",
")",
",",
"doubleval",
"(",
"$",
"p2",
")",
"]",
";",
"break",
";",
"case",
"'DateFrom'",
":",
"case",
"'DateTo'",
":",
"$",
"p",
"=",
"trim",
"(",
"$",
"p",
")",
";",
"$",
"timestamp",
"=",
"self",
"::",
"_parseDateString",
"(",
"$",
"p",
")",
";",
"if",
"(",
"$",
"timestamp",
"===",
"null",
")",
"self",
"::",
"_throwFormatError",
"(",
"$",
"validatorName",
")",
";",
"$",
"validator",
"=",
"[",
"$",
"validatorName",
",",
"$",
"timestamp",
"]",
";",
"break",
";",
"case",
"'DateFromTo'",
":",
"$",
"p",
"=",
"trim",
"(",
"$",
"p",
")",
";",
"$",
"timestamps",
"=",
"self",
"::",
"_parseTwoDateStrings",
"(",
"$",
"p",
")",
";",
"if",
"(",
"$",
"timestamps",
"===",
"null",
")",
"self",
"::",
"_throwFormatError",
"(",
"$",
"validatorName",
")",
";",
"$",
"validator",
"=",
"[",
"$",
"validatorName",
",",
"$",
"timestamps",
"[",
"0",
"]",
",",
"$",
"timestamps",
"[",
"1",
"]",
"]",
";",
"break",
";",
"case",
"'DateTimeFrom'",
":",
"case",
"'DateTimeTo'",
":",
"$",
"p",
"=",
"trim",
"(",
"$",
"p",
")",
";",
"$",
"timestamp",
"=",
"self",
"::",
"_parseDateTimeString",
"(",
"$",
"p",
")",
";",
"if",
"(",
"$",
"timestamp",
"===",
"null",
")",
"self",
"::",
"_throwFormatError",
"(",
"$",
"validatorName",
")",
";",
"$",
"validator",
"=",
"[",
"$",
"validatorName",
",",
"$",
"timestamp",
"]",
";",
"break",
";",
"case",
"'DateTimeFromTo'",
":",
"$",
"p",
"=",
"trim",
"(",
"$",
"p",
")",
";",
"$",
"timestamps",
"=",
"self",
"::",
"_parseTwoDateTimeStrings",
"(",
"$",
"p",
")",
";",
"if",
"(",
"$",
"timestamps",
"===",
"null",
")",
"self",
"::",
"_throwFormatError",
"(",
"$",
"validatorName",
")",
";",
"$",
"validator",
"=",
"[",
"$",
"validatorName",
",",
"$",
"timestamps",
"[",
"0",
"]",
",",
"$",
"timestamps",
"[",
"1",
"]",
"]",
";",
"break",
";",
"case",
"'FileMimes'",
":",
"$",
"mimes",
"=",
"self",
"::",
"_parseMimesArray",
"(",
"$",
"p",
")",
";",
"if",
"(",
"$",
"mimes",
"===",
"false",
")",
"self",
"::",
"_throwFormatError",
"(",
"$",
"validatorName",
")",
";",
"$",
"validator",
"=",
"[",
"$",
"validatorName",
",",
"$",
"mimes",
",",
"$",
"p",
"]",
";",
"break",
";",
"case",
"'FileMaxSize'",
":",
"case",
"'FileMinSize'",
":",
"$",
"size",
"=",
"self",
"::",
"_parseSizeString",
"(",
"$",
"p",
")",
";",
"if",
"(",
"$",
"size",
"===",
"null",
")",
"self",
"::",
"_throwFormatError",
"(",
"$",
"validatorName",
")",
";",
"$",
"validator",
"=",
"[",
"$",
"validatorName",
",",
"$",
"size",
",",
"$",
"p",
"]",
";",
"break",
";",
"case",
"'>>>'",
":",
"$",
"customReason",
"=",
"$",
"p",
";",
"// >>>:之后的所有字符都属于错误提示字符串",
"for",
"(",
";",
"$",
"i",
"<",
"$",
"segCount",
";",
"$",
"i",
"++",
")",
"{",
"$",
"customReason",
".=",
"'|'",
".",
"$",
"segments",
"[",
"$",
"i",
"]",
";",
"}",
"$",
"customReason",
"=",
"static",
"::",
"translateText",
"(",
"$",
"customReason",
")",
";",
"$",
"validator",
"=",
"null",
";",
"break",
";",
"case",
"'Alias'",
":",
"if",
"(",
"strlen",
"(",
"$",
"p",
")",
")",
"$",
"alias",
"=",
"static",
"::",
"translateText",
"(",
"$",
"p",
")",
";",
"$",
"validator",
"=",
"null",
";",
"break",
";",
"default",
":",
"throw",
"new",
"ValidationException",
"(",
"\"无法识别的验证子“${segment}”\");",
"",
"",
"}",
"if",
"(",
"$",
"validator",
")",
"$",
"validatorUnits",
"[",
"]",
"=",
"$",
"validator",
";",
"}",
"// end if 有冒号:分隔符",
"}",
"// end else 不是Regexp",
"}",
"// end for ($segments)",
"if",
"(",
"!",
"is_string",
"(",
"$",
"alias",
")",
"||",
"strlen",
"(",
"$",
"alias",
")",
"===",
"0",
")",
"$",
"alias",
"=",
"'UnknownParameter'",
";",
"for",
"(",
"$",
"i",
"=",
"count",
"(",
"$",
"validatorUnits",
")",
"-",
"1",
";",
"$",
"i",
">=",
"0",
";",
"$",
"i",
"--",
")",
"{",
"$",
"validatorUnits",
"[",
"$",
"i",
"]",
"[",
"]",
"=",
"$",
"customReason",
";",
"$",
"validatorUnits",
"[",
"$",
"i",
"]",
"[",
"]",
"=",
"$",
"alias",
";",
"}",
"return",
"[",
"'countOfIfs'",
"=>",
"$",
"countOfIfs",
",",
"'required'",
"=>",
"$",
"required",
",",
"'units'",
"=>",
"$",
"validatorUnits",
",",
"]",
";",
"}"
] | 将验证器(Validator)编译为验证子(Validator Unit)的数组
示例1:
输入: $validator = 'StrLen:6,16|regex:/^[a-zA-Z0-9]+$/'
输出: [
['StrLen', 6, 16, null, $alias],
['regex', '/^[a-zA-Z0-9]+$/', null, $alias],
]
示例2(自定义验证失败的提示):
输入: $validator = 'StrLen:6,16|regex:/^[a-zA-Z0-9]+$/|>>>:参数验证失败了'
输出: [
'countOfIfs' => 0,
'required' => false,
'units' => [
['StrLen', 6, 16, '参数验证失败了', $alias],
['regex', '/^[a-zA-Z0-9]+$/', '参数验证失败了', $alias],
],
]
@param $validator string 一条验证字符串
@param $alias string 参数的别名. 如果验证器中包含Alias:xxx, 会用xxx取代这个参数的值
@return array 返回包含验证信息的array
@throws ValidationException | [
"将验证器",
"(",
"Validator",
")",
"编译为验证子",
"(",
"Validator",
"Unit",
")",
"的数组"
] | train | https://github.com/photondragon/webgeeker-validation/blob/3bfc2b697ff526897c525af38c9e4ed4c889976d/src/Validation/Validation.php#L2940-L3255 |
photondragon/webgeeker-validation | src/Validation/Validation.php | Validation._parseIntArray | private static function _parseIntArray($value)
{
$vals = explode(',', $value);
$ints = [];
foreach ($vals as $val) {
if (is_numeric($val) === false || strpos($val, '.') !== false)
return false; // 检测到了非int
$ints[] = intval($val);
}
if (count($ints) === 0)
return false;
return $ints;
} | php | private static function _parseIntArray($value)
{
$vals = explode(',', $value);
$ints = [];
foreach ($vals as $val) {
if (is_numeric($val) === false || strpos($val, '.') !== false)
return false; // 检测到了非int
$ints[] = intval($val);
}
if (count($ints) === 0)
return false;
return $ints;
} | [
"private",
"static",
"function",
"_parseIntArray",
"(",
"$",
"value",
")",
"{",
"$",
"vals",
"=",
"explode",
"(",
"','",
",",
"$",
"value",
")",
";",
"$",
"ints",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"vals",
"as",
"$",
"val",
")",
"{",
"if",
"(",
"is_numeric",
"(",
"$",
"val",
")",
"===",
"false",
"||",
"strpos",
"(",
"$",
"val",
",",
"'.'",
")",
"!==",
"false",
")",
"return",
"false",
";",
"// 检测到了非int",
"$",
"ints",
"[",
"]",
"=",
"intval",
"(",
"$",
"val",
")",
";",
"}",
"if",
"(",
"count",
"(",
"$",
"ints",
")",
"===",
"0",
")",
"return",
"false",
";",
"return",
"$",
"ints",
";",
"}"
] | 将包含int数组的字符串转为int数组
@param $value
@return int[]|bool 如果是合法的int数组, 并且至少有1个int, 返回int数组; 否则返回false | [
"将包含int数组的字符串转为int数组"
] | train | https://github.com/photondragon/webgeeker-validation/blob/3bfc2b697ff526897c525af38c9e4ed4c889976d/src/Validation/Validation.php#L3275-L3287 |
photondragon/webgeeker-validation | src/Validation/Validation.php | Validation._parseStringArray | private static function _parseStringArray($value)
{
if (strlen($value)) {
$vals = explode(',', $value);
if ($vals === false)
return false;
// $vals = array_unique($vals); // 不需要去重, 不影响结果. 程序员不应该写出重复的字符串
} else
$vals = [''];
if (count($vals) === 0)
return false;
return $vals;
} | php | private static function _parseStringArray($value)
{
if (strlen($value)) {
$vals = explode(',', $value);
if ($vals === false)
return false;
// $vals = array_unique($vals); // 不需要去重, 不影响结果. 程序员不应该写出重复的字符串
} else
$vals = [''];
if (count($vals) === 0)
return false;
return $vals;
} | [
"private",
"static",
"function",
"_parseStringArray",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"strlen",
"(",
"$",
"value",
")",
")",
"{",
"$",
"vals",
"=",
"explode",
"(",
"','",
",",
"$",
"value",
")",
";",
"if",
"(",
"$",
"vals",
"===",
"false",
")",
"return",
"false",
";",
"// $vals = array_unique($vals); // 不需要去重, 不影响结果. 程序员不应该写出重复的字符串",
"}",
"else",
"$",
"vals",
"=",
"[",
"''",
"]",
";",
"if",
"(",
"count",
"(",
"$",
"vals",
")",
"===",
"0",
")",
"return",
"false",
";",
"return",
"$",
"vals",
";",
"}"
] | 将字符串转为字符串数组(逗号分隔)
@param $value
@return string[]|bool 如果至少有1个有效字符串, 返回字符串数组; 否则返回false | [
"将字符串转为字符串数组(逗号分隔)"
] | train | https://github.com/photondragon/webgeeker-validation/blob/3bfc2b697ff526897c525af38c9e4ed4c889976d/src/Validation/Validation.php#L3294-L3306 |
photondragon/webgeeker-validation | src/Validation/Validation.php | Validation._parseDateString | private static function _parseDateString($value)
{
$result = @preg_match('/^\d\d\d\d-\d?\d-\d?\d$/', $value);
if ($result !== 1)
return null;
$timestamp = strtotime($value);
if ($timestamp === false)
return null;
return $timestamp;
} | php | private static function _parseDateString($value)
{
$result = @preg_match('/^\d\d\d\d-\d?\d-\d?\d$/', $value);
if ($result !== 1)
return null;
$timestamp = strtotime($value);
if ($timestamp === false)
return null;
return $timestamp;
} | [
"private",
"static",
"function",
"_parseDateString",
"(",
"$",
"value",
")",
"{",
"$",
"result",
"=",
"@",
"preg_match",
"(",
"'/^\\d\\d\\d\\d-\\d?\\d-\\d?\\d$/'",
",",
"$",
"value",
")",
";",
"if",
"(",
"$",
"result",
"!==",
"1",
")",
"return",
"null",
";",
"$",
"timestamp",
"=",
"strtotime",
"(",
"$",
"value",
")",
";",
"if",
"(",
"$",
"timestamp",
"===",
"false",
")",
"return",
"null",
";",
"return",
"$",
"timestamp",
";",
"}"
] | 解析日期字符串
@param $value string 日期字符串, 格式为YYYY-MM-DD
@return int|null 时间戳. 日期格式错误返回null | [
"解析日期字符串"
] | train | https://github.com/photondragon/webgeeker-validation/blob/3bfc2b697ff526897c525af38c9e4ed4c889976d/src/Validation/Validation.php#L3333-L3343 |
photondragon/webgeeker-validation | src/Validation/Validation.php | Validation._parseDateTimeString | private static function _parseDateTimeString($value)
{
$result = @preg_match('/^\d\d\d\d-\d?\d-\d?\d \d\d:\d\d:\d\d$/', $value);
if ($result !== 1)
return null;
$timestamp = strtotime($value);
if ($timestamp === false)
return null;
return $timestamp;
} | php | private static function _parseDateTimeString($value)
{
$result = @preg_match('/^\d\d\d\d-\d?\d-\d?\d \d\d:\d\d:\d\d$/', $value);
if ($result !== 1)
return null;
$timestamp = strtotime($value);
if ($timestamp === false)
return null;
return $timestamp;
} | [
"private",
"static",
"function",
"_parseDateTimeString",
"(",
"$",
"value",
")",
"{",
"$",
"result",
"=",
"@",
"preg_match",
"(",
"'/^\\d\\d\\d\\d-\\d?\\d-\\d?\\d \\d\\d:\\d\\d:\\d\\d$/'",
",",
"$",
"value",
")",
";",
"if",
"(",
"$",
"result",
"!==",
"1",
")",
"return",
"null",
";",
"$",
"timestamp",
"=",
"strtotime",
"(",
"$",
"value",
")",
";",
"if",
"(",
"$",
"timestamp",
"===",
"false",
")",
"return",
"null",
";",
"return",
"$",
"timestamp",
";",
"}"
] | 解析日期时间字符串
@param $value string 日期字符串, 格式为YYYY-MM-DD HH:mm:ss
@return int|null 时间戳. 日期时间格式错误返回null | [
"解析日期时间字符串"
] | train | https://github.com/photondragon/webgeeker-validation/blob/3bfc2b697ff526897c525af38c9e4ed4c889976d/src/Validation/Validation.php#L3376-L3386 |
photondragon/webgeeker-validation | src/Validation/Validation.php | Validation._parseTwoDateTimeStrings | private static function _parseTwoDateTimeStrings($value)
{
$dateStrings = explode(',', $value);
if (count($dateStrings) !== 2)
return null;
$timestamps = [];
foreach ($dateStrings as $dateString) {
$result = @preg_match('/^\d\d\d\d-\d?\d-\d?\d \d\d:\d\d:\d\d$/', $dateString);
if ($result !== 1)
return null;
$timestamp = strtotime($dateString);
if ($timestamp === false)
return null;
$timestamps[] = $timestamp;
}
return $timestamps;
} | php | private static function _parseTwoDateTimeStrings($value)
{
$dateStrings = explode(',', $value);
if (count($dateStrings) !== 2)
return null;
$timestamps = [];
foreach ($dateStrings as $dateString) {
$result = @preg_match('/^\d\d\d\d-\d?\d-\d?\d \d\d:\d\d:\d\d$/', $dateString);
if ($result !== 1)
return null;
$timestamp = strtotime($dateString);
if ($timestamp === false)
return null;
$timestamps[] = $timestamp;
}
return $timestamps;
} | [
"private",
"static",
"function",
"_parseTwoDateTimeStrings",
"(",
"$",
"value",
")",
"{",
"$",
"dateStrings",
"=",
"explode",
"(",
"','",
",",
"$",
"value",
")",
";",
"if",
"(",
"count",
"(",
"$",
"dateStrings",
")",
"!==",
"2",
")",
"return",
"null",
";",
"$",
"timestamps",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"dateStrings",
"as",
"$",
"dateString",
")",
"{",
"$",
"result",
"=",
"@",
"preg_match",
"(",
"'/^\\d\\d\\d\\d-\\d?\\d-\\d?\\d \\d\\d:\\d\\d:\\d\\d$/'",
",",
"$",
"dateString",
")",
";",
"if",
"(",
"$",
"result",
"!==",
"1",
")",
"return",
"null",
";",
"$",
"timestamp",
"=",
"strtotime",
"(",
"$",
"dateString",
")",
";",
"if",
"(",
"$",
"timestamp",
"===",
"false",
")",
"return",
"null",
";",
"$",
"timestamps",
"[",
"]",
"=",
"$",
"timestamp",
";",
"}",
"return",
"$",
"timestamps",
";",
"}"
] | 解析两个日期时间字符串
@param $value string 两个日期字符串, 以逗号‘,’分隔, 格式为YYYY-MM-DD HH:mm:ss,YYYY-MM-DD HH:mm:ss
@return int[]|null 时间戳的数组. 日期时间格式错误返回null | [
"解析两个日期时间字符串"
] | train | https://github.com/photondragon/webgeeker-validation/blob/3bfc2b697ff526897c525af38c9e4ed4c889976d/src/Validation/Validation.php#L3393-L3412 |
photondragon/webgeeker-validation | src/Validation/Validation.php | Validation._parseMimesArray | private static function _parseMimesArray($value)
{
$mimes = explode(',', $value);
$strings = [];
foreach ($mimes as $mime) {
$mime = trim($mime);
if (strlen($mime) === 0)
continue;
if (($pos = strpos($mime, '/')) === false) // 没有斜杠'/'. 例: jpg 或 avi
{
if ($mime === '*')
throw new ValidationException("无效的MIME“${mime}”");
$mime = "/$mime";
} else // 有斜杠'/'. 例: image/jpeg 或 video/*
{
$parts = explode('/', $mime);
if (count($parts) !== 2)
throw new ValidationException("无效的MIME“${mime}”");
$type = $parts[0];
$ext = $parts[1];
if (strlen($type) === 0 || strlen($ext) === 0 || $type === '*')
throw new ValidationException("无效的MIME“${mime}”");
// 将形如"video/*"的转化为"video/"以方便后续处理
if ($ext === '*')
$mime = "$type/";
}
$strings[] = $mime;
}
if (count($strings) === 0)
return false;
return $strings;
} | php | private static function _parseMimesArray($value)
{
$mimes = explode(',', $value);
$strings = [];
foreach ($mimes as $mime) {
$mime = trim($mime);
if (strlen($mime) === 0)
continue;
if (($pos = strpos($mime, '/')) === false) // 没有斜杠'/'. 例: jpg 或 avi
{
if ($mime === '*')
throw new ValidationException("无效的MIME“${mime}”");
$mime = "/$mime";
} else // 有斜杠'/'. 例: image/jpeg 或 video/*
{
$parts = explode('/', $mime);
if (count($parts) !== 2)
throw new ValidationException("无效的MIME“${mime}”");
$type = $parts[0];
$ext = $parts[1];
if (strlen($type) === 0 || strlen($ext) === 0 || $type === '*')
throw new ValidationException("无效的MIME“${mime}”");
// 将形如"video/*"的转化为"video/"以方便后续处理
if ($ext === '*')
$mime = "$type/";
}
$strings[] = $mime;
}
if (count($strings) === 0)
return false;
return $strings;
} | [
"private",
"static",
"function",
"_parseMimesArray",
"(",
"$",
"value",
")",
"{",
"$",
"mimes",
"=",
"explode",
"(",
"','",
",",
"$",
"value",
")",
";",
"$",
"strings",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"mimes",
"as",
"$",
"mime",
")",
"{",
"$",
"mime",
"=",
"trim",
"(",
"$",
"mime",
")",
";",
"if",
"(",
"strlen",
"(",
"$",
"mime",
")",
"===",
"0",
")",
"continue",
";",
"if",
"(",
"(",
"$",
"pos",
"=",
"strpos",
"(",
"$",
"mime",
",",
"'/'",
")",
")",
"===",
"false",
")",
"// 没有斜杠'/'. 例: jpg 或 avi",
"{",
"if",
"(",
"$",
"mime",
"===",
"'*'",
")",
"throw",
"new",
"ValidationException",
"(",
"\"无效的MIME“${mime}”\");",
"",
"",
"$",
"mime",
"=",
"\"/$mime\"",
";",
"}",
"else",
"// 有斜杠'/'. 例: image/jpeg 或 video/*",
"{",
"$",
"parts",
"=",
"explode",
"(",
"'/'",
",",
"$",
"mime",
")",
";",
"if",
"(",
"count",
"(",
"$",
"parts",
")",
"!==",
"2",
")",
"throw",
"new",
"ValidationException",
"(",
"\"无效的MIME“${mime}”\");",
"",
"",
"$",
"type",
"=",
"$",
"parts",
"[",
"0",
"]",
";",
"$",
"ext",
"=",
"$",
"parts",
"[",
"1",
"]",
";",
"if",
"(",
"strlen",
"(",
"$",
"type",
")",
"===",
"0",
"||",
"strlen",
"(",
"$",
"ext",
")",
"===",
"0",
"||",
"$",
"type",
"===",
"'*'",
")",
"throw",
"new",
"ValidationException",
"(",
"\"无效的MIME“${mime}”\");",
"",
"",
"// 将形如\"video/*\"的转化为\"video/\"以方便后续处理",
"if",
"(",
"$",
"ext",
"===",
"'*'",
")",
"$",
"mime",
"=",
"\"$type/\"",
";",
"}",
"$",
"strings",
"[",
"]",
"=",
"$",
"mime",
";",
"}",
"if",
"(",
"count",
"(",
"$",
"strings",
")",
"===",
"0",
")",
"return",
"false",
";",
"return",
"$",
"strings",
";",
"}"
] | 将Mimes字符串转为Mimes数组(逗号分隔)
@param $value
@return string[]|bool 如果至少有1个有效字符串, 返回字符串数组; 否则返回false
@throws ValidationException | [
"将Mimes字符串转为Mimes数组(逗号分隔)"
] | train | https://github.com/photondragon/webgeeker-validation/blob/3bfc2b697ff526897c525af38c9e4ed4c889976d/src/Validation/Validation.php#L3420-L3454 |
photondragon/webgeeker-validation | src/Validation/Validation.php | Validation._parseIfXxxWith1Param1Int | private static function _parseIfXxxWith1Param1Int($paramstr, $validatorName)
{
$params = explode(',', $paramstr);
if (count($params) != 2)
return false;
$varName = $params[0];
$value = $params[1];
self::validateInt($value, "“$validatorName:${paramstr}”中“${varName}”后面必须是整数,实际上却是“${value}”");
return [$varName, intval($value)];
} | php | private static function _parseIfXxxWith1Param1Int($paramstr, $validatorName)
{
$params = explode(',', $paramstr);
if (count($params) != 2)
return false;
$varName = $params[0];
$value = $params[1];
self::validateInt($value, "“$validatorName:${paramstr}”中“${varName}”后面必须是整数,实际上却是“${value}”");
return [$varName, intval($value)];
} | [
"private",
"static",
"function",
"_parseIfXxxWith1Param1Int",
"(",
"$",
"paramstr",
",",
"$",
"validatorName",
")",
"{",
"$",
"params",
"=",
"explode",
"(",
"','",
",",
"$",
"paramstr",
")",
";",
"if",
"(",
"count",
"(",
"$",
"params",
")",
"!=",
"2",
")",
"return",
"false",
";",
"$",
"varName",
"=",
"$",
"params",
"[",
"0",
"]",
";",
"$",
"value",
"=",
"$",
"params",
"[",
"1",
"]",
";",
"self",
"::",
"validateInt",
"(",
"$",
"value",
",",
"\"“$validatorName:${paramstr}”中“${varName}”后面必须是整数,实际上却是“${value}”\");",
"",
"",
"return",
"[",
"$",
"varName",
",",
"intval",
"(",
"$",
"value",
")",
"]",
";",
"}"
] | 解析 IfIntXx:varname,123 中的冒号后面的部分(1个条件参数后面带1个Int值)
@param $paramstr string
@param $validatorName string 条件验证子'IfIntXx'
@return array|false 出错返回false, 否则返回 ['varname', 123]
@throws ValidationException | [
"解析",
"IfIntXx",
":",
"varname",
"123",
"中的冒号后面的部分(1个条件参数后面带1个Int值)"
] | train | https://github.com/photondragon/webgeeker-validation/blob/3bfc2b697ff526897c525af38c9e4ed4c889976d/src/Validation/Validation.php#L3463-L3473 |
photondragon/webgeeker-validation | src/Validation/Validation.php | Validation._parseIfXxxWith1Param1Str | private static function _parseIfXxxWith1Param1Str($paramstr, $validatorName)
{
$params = explode(',', $paramstr);
if (count($params) != 2)
return false;
$varName = $params[0];
// $value = $params[1];
if (strlen($varName) == 0) // 简单检测
throw new ValidationException("“$validatorName:${paramstr}”中“${$validatorName}”后面必须是一个参数(变量)名,实际上却是空串");
return $params;
} | php | private static function _parseIfXxxWith1Param1Str($paramstr, $validatorName)
{
$params = explode(',', $paramstr);
if (count($params) != 2)
return false;
$varName = $params[0];
// $value = $params[1];
if (strlen($varName) == 0) // 简单检测
throw new ValidationException("“$validatorName:${paramstr}”中“${$validatorName}”后面必须是一个参数(变量)名,实际上却是空串");
return $params;
} | [
"private",
"static",
"function",
"_parseIfXxxWith1Param1Str",
"(",
"$",
"paramstr",
",",
"$",
"validatorName",
")",
"{",
"$",
"params",
"=",
"explode",
"(",
"','",
",",
"$",
"paramstr",
")",
";",
"if",
"(",
"count",
"(",
"$",
"params",
")",
"!=",
"2",
")",
"return",
"false",
";",
"$",
"varName",
"=",
"$",
"params",
"[",
"0",
"]",
";",
"// $value = $params[1];",
"if",
"(",
"strlen",
"(",
"$",
"varName",
")",
"==",
"0",
")",
"// 简单检测",
"throw",
"new",
"ValidationException",
"(",
"\"“$validatorName:${paramstr}”中“${$validatorName}”后面必须是一个参数(变量)名,实际上却是空串\");",
"",
"",
"return",
"$",
"params",
";",
"}"
] | 解析 IfStrXx:varname,abc 中的冒号后面的部分(1个条件参数后面带1个String值)
@param $paramstr string
@param $validatorName string 条件验证子'IfStrXx'
@return array|false 出错返回false, 否则返回 ['varname', 'abc']
@throws ValidationException | [
"解析",
"IfStrXx",
":",
"varname",
"abc",
"中的冒号后面的部分(1个条件参数后面带1个String值)"
] | train | https://github.com/photondragon/webgeeker-validation/blob/3bfc2b697ff526897c525af38c9e4ed4c889976d/src/Validation/Validation.php#L3482-L3493 |
photondragon/webgeeker-validation | src/Validation/Validation.php | Validation._parseIfXxxWith1ParamMultiStrings | private static function _parseIfXxxWith1ParamMultiStrings($paramstr, $validatorName)
{
$params = explode(',', $paramstr);
$c = count($params);
if ($c < 2)
return false;
$varName = $params[0];
$vals = [];
for ($i = 1; $i < $c; $i++) {
$vals[] = $params[$i];
}
return [$varName, $vals];
} | php | private static function _parseIfXxxWith1ParamMultiStrings($paramstr, $validatorName)
{
$params = explode(',', $paramstr);
$c = count($params);
if ($c < 2)
return false;
$varName = $params[0];
$vals = [];
for ($i = 1; $i < $c; $i++) {
$vals[] = $params[$i];
}
return [$varName, $vals];
} | [
"private",
"static",
"function",
"_parseIfXxxWith1ParamMultiStrings",
"(",
"$",
"paramstr",
",",
"$",
"validatorName",
")",
"{",
"$",
"params",
"=",
"explode",
"(",
"','",
",",
"$",
"paramstr",
")",
";",
"$",
"c",
"=",
"count",
"(",
"$",
"params",
")",
";",
"if",
"(",
"$",
"c",
"<",
"2",
")",
"return",
"false",
";",
"$",
"varName",
"=",
"$",
"params",
"[",
"0",
"]",
";",
"$",
"vals",
"=",
"[",
"]",
";",
"for",
"(",
"$",
"i",
"=",
"1",
";",
"$",
"i",
"<",
"$",
"c",
";",
"$",
"i",
"++",
")",
"{",
"$",
"vals",
"[",
"]",
"=",
"$",
"params",
"[",
"$",
"i",
"]",
";",
"}",
"return",
"[",
"$",
"varName",
",",
"$",
"vals",
"]",
";",
"}"
] | 解析 IfStrXxx:varname,a,b,abc 中的冒号后面的部分(1个条件参数后面带多个字符串)
@param $paramstr string
@param $validatorName string 条件验证子'IfStrXxx'
@return array|false 出错返回false, 否则返回 ['varname', ['a','b','abc']]
@throws ValidationException | [
"解析",
"IfStrXxx",
":",
"varname",
"a",
"b",
"abc",
"中的冒号后面的部分(1个条件参数后面带多个字符串)"
] | train | https://github.com/photondragon/webgeeker-validation/blob/3bfc2b697ff526897c525af38c9e4ed4c889976d/src/Validation/Validation.php#L3518-L3531 |
photondragon/webgeeker-validation | src/Validation/Validation.php | Validation._parseIfXxxWith1ParamMultiInts | private static function _parseIfXxxWith1ParamMultiInts($paramstr, $validatorName)
{
$params = explode(',', $paramstr);
$c = count($params);
if ($c < 2)
return false;
$varName = $params[0];
$vals = [];
for ($i = 1; $i < $c; $i++) {
$intVal = $params[$i];
self::validateInt($intVal, "“$validatorName:${paramstr}”中“${varName}”后面必须全部是整数,实际上却包含了“${intVal}”");
$vals[] = intval($intVal);
}
return [$varName, $vals];
} | php | private static function _parseIfXxxWith1ParamMultiInts($paramstr, $validatorName)
{
$params = explode(',', $paramstr);
$c = count($params);
if ($c < 2)
return false;
$varName = $params[0];
$vals = [];
for ($i = 1; $i < $c; $i++) {
$intVal = $params[$i];
self::validateInt($intVal, "“$validatorName:${paramstr}”中“${varName}”后面必须全部是整数,实际上却包含了“${intVal}”");
$vals[] = intval($intVal);
}
return [$varName, $vals];
} | [
"private",
"static",
"function",
"_parseIfXxxWith1ParamMultiInts",
"(",
"$",
"paramstr",
",",
"$",
"validatorName",
")",
"{",
"$",
"params",
"=",
"explode",
"(",
"','",
",",
"$",
"paramstr",
")",
";",
"$",
"c",
"=",
"count",
"(",
"$",
"params",
")",
";",
"if",
"(",
"$",
"c",
"<",
"2",
")",
"return",
"false",
";",
"$",
"varName",
"=",
"$",
"params",
"[",
"0",
"]",
";",
"$",
"vals",
"=",
"[",
"]",
";",
"for",
"(",
"$",
"i",
"=",
"1",
";",
"$",
"i",
"<",
"$",
"c",
";",
"$",
"i",
"++",
")",
"{",
"$",
"intVal",
"=",
"$",
"params",
"[",
"$",
"i",
"]",
";",
"self",
"::",
"validateInt",
"(",
"$",
"intVal",
",",
"\"“$validatorName:${paramstr}”中“${varName}”后面必须全部是整数,实际上却包含了“${intVal}”\");",
"",
"",
"$",
"vals",
"[",
"]",
"=",
"intval",
"(",
"$",
"intVal",
")",
";",
"}",
"return",
"[",
"$",
"varName",
",",
"$",
"vals",
"]",
";",
"}"
] | 解析 IfIntXxx:varname,1,2,3 中的冒号后面的部分(1个条件参数后面带多个整数)
@param $paramstr string
@param $validatorName string 条件验证子'IfIntXxx'
@return array|false 出错返回false, 否则返回 ['varname', [1,2,3]]
@throws ValidationException | [
"解析",
"IfIntXxx",
":",
"varname",
"1",
"2",
"3",
"中的冒号后面的部分(1个条件参数后面带多个整数)"
] | train | https://github.com/photondragon/webgeeker-validation/blob/3bfc2b697ff526897c525af38c9e4ed4c889976d/src/Validation/Validation.php#L3540-L3555 |
photondragon/webgeeker-validation | src/Validation/Validation.php | Validation.validateValue | public static function validateValue($value, $validator, $alias = 'Parameter', $ignoreRequired = false, $originParams = [], $siblings = [])
{
if (is_array($validator)) {
$validators = $validator;
} else if (is_string($validator)) {
$validators = [$validator];
} else
throw new ValidationException(self::class . '::' . __FUNCTION__ . "(): \$validator必须是字符串或字符串数组");
/*
* 一个参数可以有一条或多条validator, 检测是否通过的规则如下:
* 1. 如果有一条validator检测成功, 则该参数检测通过
* 2. 如果即没有成功的也没有失败的(全部validator都被忽略或者有0条validator), 也算参数检测通过
* 3. 上面两条都不满足, 则参数检测失败
*/
$success = 0;
$failed = 0;
foreach ($validators as $validator) {
$validatorInfo = self::_compileValidator($validator, $alias);
$validatorUnits = $validatorInfo['units'];
try {
$countOfIfs = $validatorInfo['countOfIfs'];
$countOfUnits = count($validatorUnits);
for ($i = 0; $i < $countOfIfs; $i++) {
$validatorUnit = $validatorUnits[$i];
// echo "\n".json_encode($validatorUnit)."\n";
$ifName = $validatorUnit[0];
$method = 'validate' . ucfirst($ifName);
if (method_exists(self::class, $method) === false)
throw new ValidationException("找不到条件判断${$ifName}的验证方法");
$varkeypath = $validatorUnit[1]; // 条件参数的路径
// 提取条件参数的值
if (strpos($varkeypath, '.') === 0) // 以.开头, 是相对路径
{
$key = substr($varkeypath, 1); // 去掉开头的.号
self::validateVarName($key, "IfXxx中的条件参数“${key}”不是合法的变量名");
$actualValue = @$siblings[$key];
} else // 绝对路径
{
// 解析路径
$asterisksCount = 0;
$keys = self::_compileKeypath($varkeypath, $asterisksCount);
if ($asterisksCount > 0) {
throw new ValidationException("IfXxx中的条件参数“${varkeypath}”中不得包含*号");
}
$keysCount = count($keys);
$actualValue = self::_getValue($originParams, $keys, $keysCount, $ancestorExist);
}
// echo "\n\$actualValue = $actualValue\n";
// echo "\n\$compareVal = $compareVal\n";
// 处理条件参数不存在的情况
if ($ignoreRequired) // 这是增量更新
{
if ($value !== null) // 如果参数存在,则其依赖的条件参数也必须存在
{
if ($actualValue === null // 依赖的条件参数不存在
&& $ifName !== 'IfExist' && $ifName !== 'IfNotExist'
)
throw new ValidationException("必须提供条件参数“${varkeypath}”,因为参数“${alias}”的验证依赖它");
} else // 如果参数不存在,则该参数不检测
{
return $value;
}
} else // 不是增量更新
{
// 无论参数是否存在,则其依赖的条件参数都必须存在
if ($actualValue === null // 依赖的条件参数不存在
&& $ifName !== 'IfExist' && $ifName !== 'IfNotExist'
)
throw new ValidationException("必须提供条件参数“${varkeypath}”,因为参数“${alias}”的验证依赖它");
}
$compareVal = $validatorUnit[2];
$params = [$actualValue, $compareVal];
$trueOfFalse = call_user_func_array([self::class, $method], $params);
if ($trueOfFalse === false) // If条件不满足
break; // 跳出
}
if ($i < $countOfIfs) // 有If条件不满足, 忽略本条validator
// {
// echo "\n不满足条件\n";
continue;
// } else if ($countOfIfs)
// echo "\n满足条件\n";
if ($value === null) //没有提供参数
{
if (($validatorInfo['required'] === false) || $ignoreRequired)
continue; // 忽略本条validator
else
$failed++;
}
for ($i = $countOfIfs; $i < $countOfUnits; $i++) {
$validatorUnit = $validatorUnits[$i];
$validatorUnitName = $validatorUnit[0];
$method = 'validate' . ucfirst($validatorUnitName);
// if ($countOfIfs) {
// echo "\n$method()\n";
// }
if (method_exists(self::class, $method) === false)
throw new ValidationException("找不到验证子${validatorUnitName}的验证方法");
$params = [$value];
$paramsCount = count($validatorUnit);
for ($j = 1; $j < $paramsCount; $j++) {
$params[] = $validatorUnit[$j];
}
$value = call_user_func_array([static::class, $method], $params);
}
$success++;
break; // 多个validator只需要一条验证成功即可
} catch (ValidationException $e) {
$lastException = $e;
$failed++;
}
}
if ($success || $failed === 0)
return $value;
if (isset($lastException))
throw $lastException;
throw new ValidationException("“${alias}”验证失败"); // 这句应该不会执行
} | php | public static function validateValue($value, $validator, $alias = 'Parameter', $ignoreRequired = false, $originParams = [], $siblings = [])
{
if (is_array($validator)) {
$validators = $validator;
} else if (is_string($validator)) {
$validators = [$validator];
} else
throw new ValidationException(self::class . '::' . __FUNCTION__ . "(): \$validator必须是字符串或字符串数组");
/*
* 一个参数可以有一条或多条validator, 检测是否通过的规则如下:
* 1. 如果有一条validator检测成功, 则该参数检测通过
* 2. 如果即没有成功的也没有失败的(全部validator都被忽略或者有0条validator), 也算参数检测通过
* 3. 上面两条都不满足, 则参数检测失败
*/
$success = 0;
$failed = 0;
foreach ($validators as $validator) {
$validatorInfo = self::_compileValidator($validator, $alias);
$validatorUnits = $validatorInfo['units'];
try {
$countOfIfs = $validatorInfo['countOfIfs'];
$countOfUnits = count($validatorUnits);
for ($i = 0; $i < $countOfIfs; $i++) {
$validatorUnit = $validatorUnits[$i];
// echo "\n".json_encode($validatorUnit)."\n";
$ifName = $validatorUnit[0];
$method = 'validate' . ucfirst($ifName);
if (method_exists(self::class, $method) === false)
throw new ValidationException("找不到条件判断${$ifName}的验证方法");
$varkeypath = $validatorUnit[1]; // 条件参数的路径
// 提取条件参数的值
if (strpos($varkeypath, '.') === 0) // 以.开头, 是相对路径
{
$key = substr($varkeypath, 1); // 去掉开头的.号
self::validateVarName($key, "IfXxx中的条件参数“${key}”不是合法的变量名");
$actualValue = @$siblings[$key];
} else // 绝对路径
{
// 解析路径
$asterisksCount = 0;
$keys = self::_compileKeypath($varkeypath, $asterisksCount);
if ($asterisksCount > 0) {
throw new ValidationException("IfXxx中的条件参数“${varkeypath}”中不得包含*号");
}
$keysCount = count($keys);
$actualValue = self::_getValue($originParams, $keys, $keysCount, $ancestorExist);
}
// echo "\n\$actualValue = $actualValue\n";
// echo "\n\$compareVal = $compareVal\n";
// 处理条件参数不存在的情况
if ($ignoreRequired) // 这是增量更新
{
if ($value !== null) // 如果参数存在,则其依赖的条件参数也必须存在
{
if ($actualValue === null // 依赖的条件参数不存在
&& $ifName !== 'IfExist' && $ifName !== 'IfNotExist'
)
throw new ValidationException("必须提供条件参数“${varkeypath}”,因为参数“${alias}”的验证依赖它");
} else // 如果参数不存在,则该参数不检测
{
return $value;
}
} else // 不是增量更新
{
// 无论参数是否存在,则其依赖的条件参数都必须存在
if ($actualValue === null // 依赖的条件参数不存在
&& $ifName !== 'IfExist' && $ifName !== 'IfNotExist'
)
throw new ValidationException("必须提供条件参数“${varkeypath}”,因为参数“${alias}”的验证依赖它");
}
$compareVal = $validatorUnit[2];
$params = [$actualValue, $compareVal];
$trueOfFalse = call_user_func_array([self::class, $method], $params);
if ($trueOfFalse === false) // If条件不满足
break; // 跳出
}
if ($i < $countOfIfs) // 有If条件不满足, 忽略本条validator
// {
// echo "\n不满足条件\n";
continue;
// } else if ($countOfIfs)
// echo "\n满足条件\n";
if ($value === null) //没有提供参数
{
if (($validatorInfo['required'] === false) || $ignoreRequired)
continue; // 忽略本条validator
else
$failed++;
}
for ($i = $countOfIfs; $i < $countOfUnits; $i++) {
$validatorUnit = $validatorUnits[$i];
$validatorUnitName = $validatorUnit[0];
$method = 'validate' . ucfirst($validatorUnitName);
// if ($countOfIfs) {
// echo "\n$method()\n";
// }
if (method_exists(self::class, $method) === false)
throw new ValidationException("找不到验证子${validatorUnitName}的验证方法");
$params = [$value];
$paramsCount = count($validatorUnit);
for ($j = 1; $j < $paramsCount; $j++) {
$params[] = $validatorUnit[$j];
}
$value = call_user_func_array([static::class, $method], $params);
}
$success++;
break; // 多个validator只需要一条验证成功即可
} catch (ValidationException $e) {
$lastException = $e;
$failed++;
}
}
if ($success || $failed === 0)
return $value;
if (isset($lastException))
throw $lastException;
throw new ValidationException("“${alias}”验证失败"); // 这句应该不会执行
} | [
"public",
"static",
"function",
"validateValue",
"(",
"$",
"value",
",",
"$",
"validator",
",",
"$",
"alias",
"=",
"'Parameter'",
",",
"$",
"ignoreRequired",
"=",
"false",
",",
"$",
"originParams",
"=",
"[",
"]",
",",
"$",
"siblings",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"validator",
")",
")",
"{",
"$",
"validators",
"=",
"$",
"validator",
";",
"}",
"else",
"if",
"(",
"is_string",
"(",
"$",
"validator",
")",
")",
"{",
"$",
"validators",
"=",
"[",
"$",
"validator",
"]",
";",
"}",
"else",
"throw",
"new",
"ValidationException",
"(",
"self",
"::",
"class",
".",
"'::'",
".",
"__FUNCTION__",
".",
"\"(): \\$validator必须是字符串或字符串数组\");",
"",
"",
"/*\n * 一个参数可以有一条或多条validator, 检测是否通过的规则如下:\n * 1. 如果有一条validator检测成功, 则该参数检测通过\n * 2. 如果即没有成功的也没有失败的(全部validator都被忽略或者有0条validator), 也算参数检测通过\n * 3. 上面两条都不满足, 则参数检测失败\n */",
"$",
"success",
"=",
"0",
";",
"$",
"failed",
"=",
"0",
";",
"foreach",
"(",
"$",
"validators",
"as",
"$",
"validator",
")",
"{",
"$",
"validatorInfo",
"=",
"self",
"::",
"_compileValidator",
"(",
"$",
"validator",
",",
"$",
"alias",
")",
";",
"$",
"validatorUnits",
"=",
"$",
"validatorInfo",
"[",
"'units'",
"]",
";",
"try",
"{",
"$",
"countOfIfs",
"=",
"$",
"validatorInfo",
"[",
"'countOfIfs'",
"]",
";",
"$",
"countOfUnits",
"=",
"count",
"(",
"$",
"validatorUnits",
")",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"countOfIfs",
";",
"$",
"i",
"++",
")",
"{",
"$",
"validatorUnit",
"=",
"$",
"validatorUnits",
"[",
"$",
"i",
"]",
";",
"// echo \"\\n\".json_encode($validatorUnit).\"\\n\";",
"$",
"ifName",
"=",
"$",
"validatorUnit",
"[",
"0",
"]",
";",
"$",
"method",
"=",
"'validate'",
".",
"ucfirst",
"(",
"$",
"ifName",
")",
";",
"if",
"(",
"method_exists",
"(",
"self",
"::",
"class",
",",
"$",
"method",
")",
"===",
"false",
")",
"throw",
"new",
"ValidationException",
"(",
"\"找不到条件判断${$ifName}的验证方法\");",
"",
"",
"$",
"varkeypath",
"=",
"$",
"validatorUnit",
"[",
"1",
"]",
";",
"// 条件参数的路径",
"// 提取条件参数的值",
"if",
"(",
"strpos",
"(",
"$",
"varkeypath",
",",
"'.'",
")",
"===",
"0",
")",
"// 以.开头, 是相对路径",
"{",
"$",
"key",
"=",
"substr",
"(",
"$",
"varkeypath",
",",
"1",
")",
";",
"// 去掉开头的.号",
"self",
"::",
"validateVarName",
"(",
"$",
"key",
",",
"\"IfXxx中的条件参数“${key}”不是合法的变量名\");",
"",
"",
"$",
"actualValue",
"=",
"@",
"$",
"siblings",
"[",
"$",
"key",
"]",
";",
"}",
"else",
"// 绝对路径",
"{",
"// 解析路径",
"$",
"asterisksCount",
"=",
"0",
";",
"$",
"keys",
"=",
"self",
"::",
"_compileKeypath",
"(",
"$",
"varkeypath",
",",
"$",
"asterisksCount",
")",
";",
"if",
"(",
"$",
"asterisksCount",
">",
"0",
")",
"{",
"throw",
"new",
"ValidationException",
"(",
"\"IfXxx中的条件参数“${varkeypath}”中不得包含*号\");",
"",
"",
"}",
"$",
"keysCount",
"=",
"count",
"(",
"$",
"keys",
")",
";",
"$",
"actualValue",
"=",
"self",
"::",
"_getValue",
"(",
"$",
"originParams",
",",
"$",
"keys",
",",
"$",
"keysCount",
",",
"$",
"ancestorExist",
")",
";",
"}",
"// echo \"\\n\\$actualValue = $actualValue\\n\";",
"// echo \"\\n\\$compareVal = $compareVal\\n\";",
"// 处理条件参数不存在的情况",
"if",
"(",
"$",
"ignoreRequired",
")",
"// 这是增量更新",
"{",
"if",
"(",
"$",
"value",
"!==",
"null",
")",
"// 如果参数存在,则其依赖的条件参数也必须存在",
"{",
"if",
"(",
"$",
"actualValue",
"===",
"null",
"// 依赖的条件参数不存在",
"&&",
"$",
"ifName",
"!==",
"'IfExist'",
"&&",
"$",
"ifName",
"!==",
"'IfNotExist'",
")",
"throw",
"new",
"ValidationException",
"(",
"\"必须提供条件参数“${varkeypath}”,因为参数“${alias}”的验证依赖它\");",
"",
"",
"}",
"else",
"// 如果参数不存在,则该参数不检测",
"{",
"return",
"$",
"value",
";",
"}",
"}",
"else",
"// 不是增量更新",
"{",
"// 无论参数是否存在,则其依赖的条件参数都必须存在",
"if",
"(",
"$",
"actualValue",
"===",
"null",
"// 依赖的条件参数不存在",
"&&",
"$",
"ifName",
"!==",
"'IfExist'",
"&&",
"$",
"ifName",
"!==",
"'IfNotExist'",
")",
"throw",
"new",
"ValidationException",
"(",
"\"必须提供条件参数“${varkeypath}”,因为参数“${alias}”的验证依赖它\");",
"",
"",
"}",
"$",
"compareVal",
"=",
"$",
"validatorUnit",
"[",
"2",
"]",
";",
"$",
"params",
"=",
"[",
"$",
"actualValue",
",",
"$",
"compareVal",
"]",
";",
"$",
"trueOfFalse",
"=",
"call_user_func_array",
"(",
"[",
"self",
"::",
"class",
",",
"$",
"method",
"]",
",",
"$",
"params",
")",
";",
"if",
"(",
"$",
"trueOfFalse",
"===",
"false",
")",
"// If条件不满足",
"break",
";",
"// 跳出",
"}",
"if",
"(",
"$",
"i",
"<",
"$",
"countOfIfs",
")",
"// 有If条件不满足, 忽略本条validator",
"// {",
"// echo \"\\n不满足条件\\n\";",
"continue",
";",
"// } else if ($countOfIfs)",
"// echo \"\\n满足条件\\n\";",
"if",
"(",
"$",
"value",
"===",
"null",
")",
"//没有提供参数",
"{",
"if",
"(",
"(",
"$",
"validatorInfo",
"[",
"'required'",
"]",
"===",
"false",
")",
"||",
"$",
"ignoreRequired",
")",
"continue",
";",
"// 忽略本条validator",
"else",
"$",
"failed",
"++",
";",
"}",
"for",
"(",
"$",
"i",
"=",
"$",
"countOfIfs",
";",
"$",
"i",
"<",
"$",
"countOfUnits",
";",
"$",
"i",
"++",
")",
"{",
"$",
"validatorUnit",
"=",
"$",
"validatorUnits",
"[",
"$",
"i",
"]",
";",
"$",
"validatorUnitName",
"=",
"$",
"validatorUnit",
"[",
"0",
"]",
";",
"$",
"method",
"=",
"'validate'",
".",
"ucfirst",
"(",
"$",
"validatorUnitName",
")",
";",
"// if ($countOfIfs) {",
"// echo \"\\n$method()\\n\";",
"// }",
"if",
"(",
"method_exists",
"(",
"self",
"::",
"class",
",",
"$",
"method",
")",
"===",
"false",
")",
"throw",
"new",
"ValidationException",
"(",
"\"找不到验证子${validatorUnitName}的验证方法\");",
"",
"",
"$",
"params",
"=",
"[",
"$",
"value",
"]",
";",
"$",
"paramsCount",
"=",
"count",
"(",
"$",
"validatorUnit",
")",
";",
"for",
"(",
"$",
"j",
"=",
"1",
";",
"$",
"j",
"<",
"$",
"paramsCount",
";",
"$",
"j",
"++",
")",
"{",
"$",
"params",
"[",
"]",
"=",
"$",
"validatorUnit",
"[",
"$",
"j",
"]",
";",
"}",
"$",
"value",
"=",
"call_user_func_array",
"(",
"[",
"static",
"::",
"class",
",",
"$",
"method",
"]",
",",
"$",
"params",
")",
";",
"}",
"$",
"success",
"++",
";",
"break",
";",
"// 多个validator只需要一条验证成功即可",
"}",
"catch",
"(",
"ValidationException",
"$",
"e",
")",
"{",
"$",
"lastException",
"=",
"$",
"e",
";",
"$",
"failed",
"++",
";",
"}",
"}",
"if",
"(",
"$",
"success",
"||",
"$",
"failed",
"===",
"0",
")",
"return",
"$",
"value",
";",
"if",
"(",
"isset",
"(",
"$",
"lastException",
")",
")",
"throw",
"$",
"lastException",
";",
"throw",
"new",
"ValidationException",
"(",
"\"“${alias}”验证失败\"); // 这句应该不会",
"执",
"行",
"",
"}"
] | 验证一个值
@param $value mixed 要验证的值
@param $validator string|string[] 一条验证器, 例: 'StrLen:6,16|regex:/^[a-zA-Z0-9]+$/'; 或多条验证器的数组, 多条验证器之间是或的关系
@param string $alias 要验证的值的别名, 用于在验证不通过时生成提示字符串.
@param $ignoreRequired bool 是否忽略所有的Required检测子
@param array $originParams 原始参数的数组
@param array $siblings 与当前要检测的参数同级的全部参数的数组
@return mixed 返回$value被过滤后的新值
@throws ValidationException | [
"验证一个值"
] | train | https://github.com/photondragon/webgeeker-validation/blob/3bfc2b697ff526897c525af38c9e4ed4c889976d/src/Validation/Validation.php#L3568-L3708 |
photondragon/webgeeker-validation | src/Validation/Validation.php | Validation.validate | public static function validate($params, $validations, $ignoreRequired = false)
{
if (is_array($params) === false)
throw new ValidationException(self::class . '::' . __FUNCTION__ . "(): \$params必须是数组");
$cachedKeyValues = [];
foreach ($validations as $keypath => $validator) {
// 解析路径
$asterisksCount = 0;
$keys = self::_compileKeypath($keypath, $asterisksCount);
$keysCount = count($keys);
if ($keysCount > 1 && $cachedKeyValues === null)
$cachedKeyValues = [];
self::_validate($params, $keys, $keysCount, $validator, '', $ignoreRequired, $cachedKeyValues);
}
// if(count($cachedKeyValues))
// echo json_encode($cachedKeyValues, JSON_PRETTY_PRINT);
return $params;
} | php | public static function validate($params, $validations, $ignoreRequired = false)
{
if (is_array($params) === false)
throw new ValidationException(self::class . '::' . __FUNCTION__ . "(): \$params必须是数组");
$cachedKeyValues = [];
foreach ($validations as $keypath => $validator) {
// 解析路径
$asterisksCount = 0;
$keys = self::_compileKeypath($keypath, $asterisksCount);
$keysCount = count($keys);
if ($keysCount > 1 && $cachedKeyValues === null)
$cachedKeyValues = [];
self::_validate($params, $keys, $keysCount, $validator, '', $ignoreRequired, $cachedKeyValues);
}
// if(count($cachedKeyValues))
// echo json_encode($cachedKeyValues, JSON_PRETTY_PRINT);
return $params;
} | [
"public",
"static",
"function",
"validate",
"(",
"$",
"params",
",",
"$",
"validations",
",",
"$",
"ignoreRequired",
"=",
"false",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"params",
")",
"===",
"false",
")",
"throw",
"new",
"ValidationException",
"(",
"self",
"::",
"class",
".",
"'::'",
".",
"__FUNCTION__",
".",
"\"(): \\$params必须是数组\");",
"",
"",
"$",
"cachedKeyValues",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"validations",
"as",
"$",
"keypath",
"=>",
"$",
"validator",
")",
"{",
"// 解析路径",
"$",
"asterisksCount",
"=",
"0",
";",
"$",
"keys",
"=",
"self",
"::",
"_compileKeypath",
"(",
"$",
"keypath",
",",
"$",
"asterisksCount",
")",
";",
"$",
"keysCount",
"=",
"count",
"(",
"$",
"keys",
")",
";",
"if",
"(",
"$",
"keysCount",
">",
"1",
"&&",
"$",
"cachedKeyValues",
"===",
"null",
")",
"$",
"cachedKeyValues",
"=",
"[",
"]",
";",
"self",
"::",
"_validate",
"(",
"$",
"params",
",",
"$",
"keys",
",",
"$",
"keysCount",
",",
"$",
"validator",
",",
"''",
",",
"$",
"ignoreRequired",
",",
"$",
"cachedKeyValues",
")",
";",
"}",
"// if(count($cachedKeyValues))",
"// echo json_encode($cachedKeyValues, JSON_PRETTY_PRINT);",
"return",
"$",
"params",
";",
"}"
] | 验证输入参数
如果客户端通过HTTP协议要传递的参数的值是一个空Array或空Object, 实际上客户
端HTTP协议是会忽略这种参数的, 服务器接收到的参数数组中也就没有相应的参数.
举例, 如果客户端传了这样的参数: {
"bookname": "hello,world!",
"authors": [],
"extra": {},
}
服务器接收到的实际上会是: {
"bookname": "hello",
}
没有authors和extra参数
@param $params array 包含输入参数的数组. 如['page'=>1,'pageSize'=>10]
@param $validations array 包含验证字符串的数组. 如: [
'keypath1' => 'validator string',
'bookname' => 'StrLen:2',
'summary' => 'StrLen:0',
'authors' => 'Required|Arr',
'authors[*]' => 'Required|Obj',
'authors[*].name' => 'StrLen:2',
'authors[*].email' => 'Regexp:/^[a-zA-Z0-9]+@[a-zA-Z0-9-]+.[a-z]+$/',
]
@param $ignoreRequired bool 是否忽略所有的Required检测子
@return mixed
@throws ValidationException 验证不通过会抛出异常 | [
"验证输入参数"
] | train | https://github.com/photondragon/webgeeker-validation/blob/3bfc2b697ff526897c525af38c9e4ed4c889976d/src/Validation/Validation.php#L3832-L3853 |
photondragon/webgeeker-validation | src/Validation/Validation.php | Validation._getValue | private static function _getValue($params, $keys, $keysCount, &$ancestorExist, $keyPrefix = '', &$cachedKeyValues = null)
{
$keyPath = $keyPrefix;
$siblings = $params;
$value = $params;
if ($keysCount > 1) {
// 查询缓存
if ($cachedKeyValues !== null) {
// todo 如果没有*号, 没必要重新合成路径
$prefix = $keyPrefix;
for ($i = 0; $i < $keysCount - 1; $i++) {
$key = $keys[$i];
if ($prefix === '')
$prefix = $key;
else if (is_integer($key) || $key === '*')
$prefix .= "[$key]";
else
$prefix .= ".$key";
}
// if (array_key_exists($prefix, $cachedKeyValues)) {
// echo "\n命中: key=$prefix" . ", value=" . $cachedKeyValues[$prefix] . "\n";
// }
}
}
for ($n = 0; $n < $keysCount; $n++) {
$siblings = $value;
$keyPrefix = $keyPath;
$key = $keys[$n];
if ($key === '*') {
self::validateArr($siblings, null, $keyPrefix);
$c = count($siblings);
if ($c > 0) {
$subKeys = array_slice($keys, $n + 1);
$subKeysCount = $keysCount - $n - 1;
if ($subKeysCount) // *号后面还有keys
{
$values = [];
$ancestorExist = false;
for ($i = 0; $i < $c; $i++) {
$element = $siblings[$i];
$keyPath = $keyPrefix . "[$i]";
$aAncestorExist = false;
$aValue = self::_getValue($element, $subKeys, $subKeysCount, $aAncestorExist, $keyPath, $cachedKeyValues);
if ($aAncestorExist) {
$values[] = $aValue;
$ancestorExist = true;
}
// self::_validate($element, $subKeys, $subKeysCount, $validator, $keyPath, $ignoreRequired, $cachedKeyValues);
}
} else // *号是最后一级
{
$values = $siblings;
// todo 缓存数组本身的没什么用, 因为提取不到.
if ($cachedKeyValues !== null && $keyPrefix) {
$cachedKeyValues[$keyPrefix] = $siblings;
// echo "\n缓存: keyPrefix=$keyPrefix, key=$keyPath" . ", value=$siblings\n";
}
}
return $values;
} else // 'items[*]' => 'Required' 要求items至少有1个元素, 但上面的循环不检测items==[]的情况
$value = null; // 这里是针对$value==[]这种情况的特殊处理
} else {
if (is_integer($key))
self::validateArr($siblings, null, $keyPrefix);
else
self::validateObj($siblings, null, $keyPrefix);
$value = @$siblings[$key];
}
if ($keyPrefix === '')
$keyPath = $key;
else if (is_integer($key) || $key === '*')
$keyPath = $keyPrefix . "[$key]";
else
$keyPath = "$keyPrefix.$key";
if ($value === null) {
$n++;
break;
}
}
// 到这里$n表示当前的$value是第几层. 取值在[1, $keysCount]之间, 也就是说 $n 只可能小于或等于$keysCount
if ($n == $keysCount) {
$ancestorExist = true;
} else {
$ancestorExist = false;
if ($cachedKeyValues !== null) {
for (; $n < $keysCount; $n++) {
$keyPrefix = $keyPath;
$key = $keys[$n];
if ($keyPrefix === '')
$keyPath = $key;
else if (is_integer($key) || $key === '*')
$keyPath = $keyPrefix . "[$key]";
else
$keyPath = "$keyPrefix.$key";
}
$siblings = null;
}
}
if ($cachedKeyValues !== null && $keyPrefix) {
$cachedKeyValues[$keyPrefix] = $siblings; // 将父级数据缓存起来
// echo "\n缓存: keyPrefix=$keyPrefix, key=$keyPath" . ", value=$siblings\n";
}
return $value;
} | php | private static function _getValue($params, $keys, $keysCount, &$ancestorExist, $keyPrefix = '', &$cachedKeyValues = null)
{
$keyPath = $keyPrefix;
$siblings = $params;
$value = $params;
if ($keysCount > 1) {
// 查询缓存
if ($cachedKeyValues !== null) {
// todo 如果没有*号, 没必要重新合成路径
$prefix = $keyPrefix;
for ($i = 0; $i < $keysCount - 1; $i++) {
$key = $keys[$i];
if ($prefix === '')
$prefix = $key;
else if (is_integer($key) || $key === '*')
$prefix .= "[$key]";
else
$prefix .= ".$key";
}
// if (array_key_exists($prefix, $cachedKeyValues)) {
// echo "\n命中: key=$prefix" . ", value=" . $cachedKeyValues[$prefix] . "\n";
// }
}
}
for ($n = 0; $n < $keysCount; $n++) {
$siblings = $value;
$keyPrefix = $keyPath;
$key = $keys[$n];
if ($key === '*') {
self::validateArr($siblings, null, $keyPrefix);
$c = count($siblings);
if ($c > 0) {
$subKeys = array_slice($keys, $n + 1);
$subKeysCount = $keysCount - $n - 1;
if ($subKeysCount) // *号后面还有keys
{
$values = [];
$ancestorExist = false;
for ($i = 0; $i < $c; $i++) {
$element = $siblings[$i];
$keyPath = $keyPrefix . "[$i]";
$aAncestorExist = false;
$aValue = self::_getValue($element, $subKeys, $subKeysCount, $aAncestorExist, $keyPath, $cachedKeyValues);
if ($aAncestorExist) {
$values[] = $aValue;
$ancestorExist = true;
}
// self::_validate($element, $subKeys, $subKeysCount, $validator, $keyPath, $ignoreRequired, $cachedKeyValues);
}
} else // *号是最后一级
{
$values = $siblings;
// todo 缓存数组本身的没什么用, 因为提取不到.
if ($cachedKeyValues !== null && $keyPrefix) {
$cachedKeyValues[$keyPrefix] = $siblings;
// echo "\n缓存: keyPrefix=$keyPrefix, key=$keyPath" . ", value=$siblings\n";
}
}
return $values;
} else // 'items[*]' => 'Required' 要求items至少有1个元素, 但上面的循环不检测items==[]的情况
$value = null; // 这里是针对$value==[]这种情况的特殊处理
} else {
if (is_integer($key))
self::validateArr($siblings, null, $keyPrefix);
else
self::validateObj($siblings, null, $keyPrefix);
$value = @$siblings[$key];
}
if ($keyPrefix === '')
$keyPath = $key;
else if (is_integer($key) || $key === '*')
$keyPath = $keyPrefix . "[$key]";
else
$keyPath = "$keyPrefix.$key";
if ($value === null) {
$n++;
break;
}
}
// 到这里$n表示当前的$value是第几层. 取值在[1, $keysCount]之间, 也就是说 $n 只可能小于或等于$keysCount
if ($n == $keysCount) {
$ancestorExist = true;
} else {
$ancestorExist = false;
if ($cachedKeyValues !== null) {
for (; $n < $keysCount; $n++) {
$keyPrefix = $keyPath;
$key = $keys[$n];
if ($keyPrefix === '')
$keyPath = $key;
else if (is_integer($key) || $key === '*')
$keyPath = $keyPrefix . "[$key]";
else
$keyPath = "$keyPrefix.$key";
}
$siblings = null;
}
}
if ($cachedKeyValues !== null && $keyPrefix) {
$cachedKeyValues[$keyPrefix] = $siblings; // 将父级数据缓存起来
// echo "\n缓存: keyPrefix=$keyPrefix, key=$keyPath" . ", value=$siblings\n";
}
return $value;
} | [
"private",
"static",
"function",
"_getValue",
"(",
"$",
"params",
",",
"$",
"keys",
",",
"$",
"keysCount",
",",
"&",
"$",
"ancestorExist",
",",
"$",
"keyPrefix",
"=",
"''",
",",
"&",
"$",
"cachedKeyValues",
"=",
"null",
")",
"{",
"$",
"keyPath",
"=",
"$",
"keyPrefix",
";",
"$",
"siblings",
"=",
"$",
"params",
";",
"$",
"value",
"=",
"$",
"params",
";",
"if",
"(",
"$",
"keysCount",
">",
"1",
")",
"{",
"// 查询缓存",
"if",
"(",
"$",
"cachedKeyValues",
"!==",
"null",
")",
"{",
"// todo 如果没有*号, 没必要重新合成路径",
"$",
"prefix",
"=",
"$",
"keyPrefix",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"keysCount",
"-",
"1",
";",
"$",
"i",
"++",
")",
"{",
"$",
"key",
"=",
"$",
"keys",
"[",
"$",
"i",
"]",
";",
"if",
"(",
"$",
"prefix",
"===",
"''",
")",
"$",
"prefix",
"=",
"$",
"key",
";",
"else",
"if",
"(",
"is_integer",
"(",
"$",
"key",
")",
"||",
"$",
"key",
"===",
"'*'",
")",
"$",
"prefix",
".=",
"\"[$key]\"",
";",
"else",
"$",
"prefix",
".=",
"\".$key\"",
";",
"}",
"// if (array_key_exists($prefix, $cachedKeyValues)) {",
"// echo \"\\n命中: key=$prefix\" . \", value=\" . $cachedKeyValues[$prefix] . \"\\n\";",
"// }",
"}",
"}",
"for",
"(",
"$",
"n",
"=",
"0",
";",
"$",
"n",
"<",
"$",
"keysCount",
";",
"$",
"n",
"++",
")",
"{",
"$",
"siblings",
"=",
"$",
"value",
";",
"$",
"keyPrefix",
"=",
"$",
"keyPath",
";",
"$",
"key",
"=",
"$",
"keys",
"[",
"$",
"n",
"]",
";",
"if",
"(",
"$",
"key",
"===",
"'*'",
")",
"{",
"self",
"::",
"validateArr",
"(",
"$",
"siblings",
",",
"null",
",",
"$",
"keyPrefix",
")",
";",
"$",
"c",
"=",
"count",
"(",
"$",
"siblings",
")",
";",
"if",
"(",
"$",
"c",
">",
"0",
")",
"{",
"$",
"subKeys",
"=",
"array_slice",
"(",
"$",
"keys",
",",
"$",
"n",
"+",
"1",
")",
";",
"$",
"subKeysCount",
"=",
"$",
"keysCount",
"-",
"$",
"n",
"-",
"1",
";",
"if",
"(",
"$",
"subKeysCount",
")",
"// *号后面还有keys",
"{",
"$",
"values",
"=",
"[",
"]",
";",
"$",
"ancestorExist",
"=",
"false",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"c",
";",
"$",
"i",
"++",
")",
"{",
"$",
"element",
"=",
"$",
"siblings",
"[",
"$",
"i",
"]",
";",
"$",
"keyPath",
"=",
"$",
"keyPrefix",
".",
"\"[$i]\"",
";",
"$",
"aAncestorExist",
"=",
"false",
";",
"$",
"aValue",
"=",
"self",
"::",
"_getValue",
"(",
"$",
"element",
",",
"$",
"subKeys",
",",
"$",
"subKeysCount",
",",
"$",
"aAncestorExist",
",",
"$",
"keyPath",
",",
"$",
"cachedKeyValues",
")",
";",
"if",
"(",
"$",
"aAncestorExist",
")",
"{",
"$",
"values",
"[",
"]",
"=",
"$",
"aValue",
";",
"$",
"ancestorExist",
"=",
"true",
";",
"}",
"// self::_validate($element, $subKeys, $subKeysCount, $validator, $keyPath, $ignoreRequired, $cachedKeyValues);",
"}",
"}",
"else",
"// *号是最后一级",
"{",
"$",
"values",
"=",
"$",
"siblings",
";",
"// todo 缓存数组本身的没什么用, 因为提取不到.",
"if",
"(",
"$",
"cachedKeyValues",
"!==",
"null",
"&&",
"$",
"keyPrefix",
")",
"{",
"$",
"cachedKeyValues",
"[",
"$",
"keyPrefix",
"]",
"=",
"$",
"siblings",
";",
"// echo \"\\n缓存: keyPrefix=$keyPrefix, key=$keyPath\" . \", value=$siblings\\n\";",
"}",
"}",
"return",
"$",
"values",
";",
"}",
"else",
"// 'items[*]' => 'Required' 要求items至少有1个元素, 但上面的循环不检测items==[]的情况",
"$",
"value",
"=",
"null",
";",
"// 这里是针对$value==[]这种情况的特殊处理",
"}",
"else",
"{",
"if",
"(",
"is_integer",
"(",
"$",
"key",
")",
")",
"self",
"::",
"validateArr",
"(",
"$",
"siblings",
",",
"null",
",",
"$",
"keyPrefix",
")",
";",
"else",
"self",
"::",
"validateObj",
"(",
"$",
"siblings",
",",
"null",
",",
"$",
"keyPrefix",
")",
";",
"$",
"value",
"=",
"@",
"$",
"siblings",
"[",
"$",
"key",
"]",
";",
"}",
"if",
"(",
"$",
"keyPrefix",
"===",
"''",
")",
"$",
"keyPath",
"=",
"$",
"key",
";",
"else",
"if",
"(",
"is_integer",
"(",
"$",
"key",
")",
"||",
"$",
"key",
"===",
"'*'",
")",
"$",
"keyPath",
"=",
"$",
"keyPrefix",
".",
"\"[$key]\"",
";",
"else",
"$",
"keyPath",
"=",
"\"$keyPrefix.$key\"",
";",
"if",
"(",
"$",
"value",
"===",
"null",
")",
"{",
"$",
"n",
"++",
";",
"break",
";",
"}",
"}",
"// 到这里$n表示当前的$value是第几层. 取值在[1, $keysCount]之间, 也就是说 $n 只可能小于或等于$keysCount",
"if",
"(",
"$",
"n",
"==",
"$",
"keysCount",
")",
"{",
"$",
"ancestorExist",
"=",
"true",
";",
"}",
"else",
"{",
"$",
"ancestorExist",
"=",
"false",
";",
"if",
"(",
"$",
"cachedKeyValues",
"!==",
"null",
")",
"{",
"for",
"(",
";",
"$",
"n",
"<",
"$",
"keysCount",
";",
"$",
"n",
"++",
")",
"{",
"$",
"keyPrefix",
"=",
"$",
"keyPath",
";",
"$",
"key",
"=",
"$",
"keys",
"[",
"$",
"n",
"]",
";",
"if",
"(",
"$",
"keyPrefix",
"===",
"''",
")",
"$",
"keyPath",
"=",
"$",
"key",
";",
"else",
"if",
"(",
"is_integer",
"(",
"$",
"key",
")",
"||",
"$",
"key",
"===",
"'*'",
")",
"$",
"keyPath",
"=",
"$",
"keyPrefix",
".",
"\"[$key]\"",
";",
"else",
"$",
"keyPath",
"=",
"\"$keyPrefix.$key\"",
";",
"}",
"$",
"siblings",
"=",
"null",
";",
"}",
"}",
"if",
"(",
"$",
"cachedKeyValues",
"!==",
"null",
"&&",
"$",
"keyPrefix",
")",
"{",
"$",
"cachedKeyValues",
"[",
"$",
"keyPrefix",
"]",
"=",
"$",
"siblings",
";",
"// 将父级数据缓存起来",
"// echo \"\\n缓存: keyPrefix=$keyPrefix, key=$keyPath\" . \", value=$siblings\\n\";",
"}",
"return",
"$",
"value",
";",
"}"
] | 根据路径从参数数组中取值. 可以用于Ifxxx中参数的取值
@param $params array
@param $keys array
@param $keysCount int
@param $ancestorExist bool&
@param string $keyPrefix
@param $cachedKeyValues array&|null
@return null|mixed
@throws ValidationException | [
"根据路径从参数数组中取值",
".",
"可以用于Ifxxx中参数的取值"
] | train | https://github.com/photondragon/webgeeker-validation/blob/3bfc2b697ff526897c525af38c9e4ed4c889976d/src/Validation/Validation.php#L3866-L3981 |
photondragon/webgeeker-validation | src/Validation/Validation.php | Validation._validate | private static function _validate($params, $keys, $keysCount, $validator, $keyPrefix = '', $ignoreRequired = false, &$cachedKeyValues = null)
{
$keyPath = $keyPrefix;
$siblings = $params;
$value = $params;
if ($keysCount > 1) {
if ($cachedKeyValues !== null) {
$prefix = $keyPrefix;
for ($i = 0; $i < $keysCount - 1; $i++) {
$key = $keys[$i];
if ($prefix === '')
$prefix = $key;
else if (is_integer($key) || $key === '*')
$prefix .= "[$key]";
else
$prefix .= ".$key";
}
// if(array_key_exists($prefix, $cachedKeyValues)) {
// echo "\n命中: key=$prefix" . ", value=".json_encode($cachedKeyValues[$prefix])."\n";
// }
}
}
for ($n = 0; $n < $keysCount; $n++) {
$siblings = $value;
$keyPrefix = $keyPath;
$key = $keys[$n];
if ($key === '*') {
self::validateArr($siblings, null, $keyPrefix);
$c = count($siblings);
if ($c > 0) {
$subKeys = array_slice($keys, $n + 1);
$subKeysCount = $keysCount - $n - 1;
for ($i = 0; $i < $c; $i++) {
$element = $siblings[$i];
$keyPath = $keyPrefix . "[$i]";
if ($subKeysCount)
self::_validate($element, $subKeys, $subKeysCount, $validator, $keyPath, $ignoreRequired, $cachedKeyValues);
else {
self::validateValue($element, $validator, $keyPath, $ignoreRequired, $params, $siblings);
// 缓存数组本身的没什么用, 因为提取不到.
if ($cachedKeyValues !== null && $keyPrefix) {
$cachedKeyValues[$keyPrefix] = $siblings;
// echo "\n缓存: keyPrefix=$keyPrefix, key=$keyPath" . ", value=$siblings\n";
}
}
}
return;
} else // 'items[*]' => 'Required' 要求items至少有1个元素, 但上面的循环不检测items==[]的情况
$value = null; // 这里是针对$value==[]这种情况的特殊处理
} else {
if (is_integer($key))
self::validateArr($siblings, null, $keyPrefix);
else
self::validateObj($siblings, null, $keyPrefix);
$value = @$siblings[$key];
}
if ($keyPrefix === '')
$keyPath = $key;
else if (is_integer($key) || $key === '*')
$keyPath = $keyPrefix . "[$key]";
else
$keyPath = "$keyPrefix.$key";
if ($value === null) {
$n++;
break;
}
}
// 到这里$n表示当前的$value是第几层
if ($n == $keysCount) {
self::validateValue($value, $validator, $keyPath, $ignoreRequired, $params, $siblings);
} else {
if ($cachedKeyValues !== null) {
for (; $n < $keysCount; $n++) {
$keyPrefix = $keyPath;
$key = $keys[$n];
if ($keyPrefix === '')
$keyPath = $key;
else if (is_integer($key) || $key === '*')
$keyPath = $keyPrefix . "[$key]";
else
$keyPath = "$keyPrefix.$key";
}
$siblings = null;
}
}
if ($cachedKeyValues !== null && $keyPrefix) {
$cachedKeyValues[$keyPrefix] = $siblings;
// echo "\n缓存: keyPrefix=$keyPrefix, key=$keyPath" . ", value=$siblings\n";
}
} | php | private static function _validate($params, $keys, $keysCount, $validator, $keyPrefix = '', $ignoreRequired = false, &$cachedKeyValues = null)
{
$keyPath = $keyPrefix;
$siblings = $params;
$value = $params;
if ($keysCount > 1) {
if ($cachedKeyValues !== null) {
$prefix = $keyPrefix;
for ($i = 0; $i < $keysCount - 1; $i++) {
$key = $keys[$i];
if ($prefix === '')
$prefix = $key;
else if (is_integer($key) || $key === '*')
$prefix .= "[$key]";
else
$prefix .= ".$key";
}
// if(array_key_exists($prefix, $cachedKeyValues)) {
// echo "\n命中: key=$prefix" . ", value=".json_encode($cachedKeyValues[$prefix])."\n";
// }
}
}
for ($n = 0; $n < $keysCount; $n++) {
$siblings = $value;
$keyPrefix = $keyPath;
$key = $keys[$n];
if ($key === '*') {
self::validateArr($siblings, null, $keyPrefix);
$c = count($siblings);
if ($c > 0) {
$subKeys = array_slice($keys, $n + 1);
$subKeysCount = $keysCount - $n - 1;
for ($i = 0; $i < $c; $i++) {
$element = $siblings[$i];
$keyPath = $keyPrefix . "[$i]";
if ($subKeysCount)
self::_validate($element, $subKeys, $subKeysCount, $validator, $keyPath, $ignoreRequired, $cachedKeyValues);
else {
self::validateValue($element, $validator, $keyPath, $ignoreRequired, $params, $siblings);
// 缓存数组本身的没什么用, 因为提取不到.
if ($cachedKeyValues !== null && $keyPrefix) {
$cachedKeyValues[$keyPrefix] = $siblings;
// echo "\n缓存: keyPrefix=$keyPrefix, key=$keyPath" . ", value=$siblings\n";
}
}
}
return;
} else // 'items[*]' => 'Required' 要求items至少有1个元素, 但上面的循环不检测items==[]的情况
$value = null; // 这里是针对$value==[]这种情况的特殊处理
} else {
if (is_integer($key))
self::validateArr($siblings, null, $keyPrefix);
else
self::validateObj($siblings, null, $keyPrefix);
$value = @$siblings[$key];
}
if ($keyPrefix === '')
$keyPath = $key;
else if (is_integer($key) || $key === '*')
$keyPath = $keyPrefix . "[$key]";
else
$keyPath = "$keyPrefix.$key";
if ($value === null) {
$n++;
break;
}
}
// 到这里$n表示当前的$value是第几层
if ($n == $keysCount) {
self::validateValue($value, $validator, $keyPath, $ignoreRequired, $params, $siblings);
} else {
if ($cachedKeyValues !== null) {
for (; $n < $keysCount; $n++) {
$keyPrefix = $keyPath;
$key = $keys[$n];
if ($keyPrefix === '')
$keyPath = $key;
else if (is_integer($key) || $key === '*')
$keyPath = $keyPrefix . "[$key]";
else
$keyPath = "$keyPrefix.$key";
}
$siblings = null;
}
}
if ($cachedKeyValues !== null && $keyPrefix) {
$cachedKeyValues[$keyPrefix] = $siblings;
// echo "\n缓存: keyPrefix=$keyPrefix, key=$keyPath" . ", value=$siblings\n";
}
} | [
"private",
"static",
"function",
"_validate",
"(",
"$",
"params",
",",
"$",
"keys",
",",
"$",
"keysCount",
",",
"$",
"validator",
",",
"$",
"keyPrefix",
"=",
"''",
",",
"$",
"ignoreRequired",
"=",
"false",
",",
"&",
"$",
"cachedKeyValues",
"=",
"null",
")",
"{",
"$",
"keyPath",
"=",
"$",
"keyPrefix",
";",
"$",
"siblings",
"=",
"$",
"params",
";",
"$",
"value",
"=",
"$",
"params",
";",
"if",
"(",
"$",
"keysCount",
">",
"1",
")",
"{",
"if",
"(",
"$",
"cachedKeyValues",
"!==",
"null",
")",
"{",
"$",
"prefix",
"=",
"$",
"keyPrefix",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"keysCount",
"-",
"1",
";",
"$",
"i",
"++",
")",
"{",
"$",
"key",
"=",
"$",
"keys",
"[",
"$",
"i",
"]",
";",
"if",
"(",
"$",
"prefix",
"===",
"''",
")",
"$",
"prefix",
"=",
"$",
"key",
";",
"else",
"if",
"(",
"is_integer",
"(",
"$",
"key",
")",
"||",
"$",
"key",
"===",
"'*'",
")",
"$",
"prefix",
".=",
"\"[$key]\"",
";",
"else",
"$",
"prefix",
".=",
"\".$key\"",
";",
"}",
"// if(array_key_exists($prefix, $cachedKeyValues)) {",
"// echo \"\\n命中: key=$prefix\" . \", value=\".json_encode($cachedKeyValues[$prefix]).\"\\n\";",
"// }",
"}",
"}",
"for",
"(",
"$",
"n",
"=",
"0",
";",
"$",
"n",
"<",
"$",
"keysCount",
";",
"$",
"n",
"++",
")",
"{",
"$",
"siblings",
"=",
"$",
"value",
";",
"$",
"keyPrefix",
"=",
"$",
"keyPath",
";",
"$",
"key",
"=",
"$",
"keys",
"[",
"$",
"n",
"]",
";",
"if",
"(",
"$",
"key",
"===",
"'*'",
")",
"{",
"self",
"::",
"validateArr",
"(",
"$",
"siblings",
",",
"null",
",",
"$",
"keyPrefix",
")",
";",
"$",
"c",
"=",
"count",
"(",
"$",
"siblings",
")",
";",
"if",
"(",
"$",
"c",
">",
"0",
")",
"{",
"$",
"subKeys",
"=",
"array_slice",
"(",
"$",
"keys",
",",
"$",
"n",
"+",
"1",
")",
";",
"$",
"subKeysCount",
"=",
"$",
"keysCount",
"-",
"$",
"n",
"-",
"1",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"c",
";",
"$",
"i",
"++",
")",
"{",
"$",
"element",
"=",
"$",
"siblings",
"[",
"$",
"i",
"]",
";",
"$",
"keyPath",
"=",
"$",
"keyPrefix",
".",
"\"[$i]\"",
";",
"if",
"(",
"$",
"subKeysCount",
")",
"self",
"::",
"_validate",
"(",
"$",
"element",
",",
"$",
"subKeys",
",",
"$",
"subKeysCount",
",",
"$",
"validator",
",",
"$",
"keyPath",
",",
"$",
"ignoreRequired",
",",
"$",
"cachedKeyValues",
")",
";",
"else",
"{",
"self",
"::",
"validateValue",
"(",
"$",
"element",
",",
"$",
"validator",
",",
"$",
"keyPath",
",",
"$",
"ignoreRequired",
",",
"$",
"params",
",",
"$",
"siblings",
")",
";",
"// 缓存数组本身的没什么用, 因为提取不到.",
"if",
"(",
"$",
"cachedKeyValues",
"!==",
"null",
"&&",
"$",
"keyPrefix",
")",
"{",
"$",
"cachedKeyValues",
"[",
"$",
"keyPrefix",
"]",
"=",
"$",
"siblings",
";",
"// echo \"\\n缓存: keyPrefix=$keyPrefix, key=$keyPath\" . \", value=$siblings\\n\";",
"}",
"}",
"}",
"return",
";",
"}",
"else",
"// 'items[*]' => 'Required' 要求items至少有1个元素, 但上面的循环不检测items==[]的情况",
"$",
"value",
"=",
"null",
";",
"// 这里是针对$value==[]这种情况的特殊处理",
"}",
"else",
"{",
"if",
"(",
"is_integer",
"(",
"$",
"key",
")",
")",
"self",
"::",
"validateArr",
"(",
"$",
"siblings",
",",
"null",
",",
"$",
"keyPrefix",
")",
";",
"else",
"self",
"::",
"validateObj",
"(",
"$",
"siblings",
",",
"null",
",",
"$",
"keyPrefix",
")",
";",
"$",
"value",
"=",
"@",
"$",
"siblings",
"[",
"$",
"key",
"]",
";",
"}",
"if",
"(",
"$",
"keyPrefix",
"===",
"''",
")",
"$",
"keyPath",
"=",
"$",
"key",
";",
"else",
"if",
"(",
"is_integer",
"(",
"$",
"key",
")",
"||",
"$",
"key",
"===",
"'*'",
")",
"$",
"keyPath",
"=",
"$",
"keyPrefix",
".",
"\"[$key]\"",
";",
"else",
"$",
"keyPath",
"=",
"\"$keyPrefix.$key\"",
";",
"if",
"(",
"$",
"value",
"===",
"null",
")",
"{",
"$",
"n",
"++",
";",
"break",
";",
"}",
"}",
"// 到这里$n表示当前的$value是第几层",
"if",
"(",
"$",
"n",
"==",
"$",
"keysCount",
")",
"{",
"self",
"::",
"validateValue",
"(",
"$",
"value",
",",
"$",
"validator",
",",
"$",
"keyPath",
",",
"$",
"ignoreRequired",
",",
"$",
"params",
",",
"$",
"siblings",
")",
";",
"}",
"else",
"{",
"if",
"(",
"$",
"cachedKeyValues",
"!==",
"null",
")",
"{",
"for",
"(",
";",
"$",
"n",
"<",
"$",
"keysCount",
";",
"$",
"n",
"++",
")",
"{",
"$",
"keyPrefix",
"=",
"$",
"keyPath",
";",
"$",
"key",
"=",
"$",
"keys",
"[",
"$",
"n",
"]",
";",
"if",
"(",
"$",
"keyPrefix",
"===",
"''",
")",
"$",
"keyPath",
"=",
"$",
"key",
";",
"else",
"if",
"(",
"is_integer",
"(",
"$",
"key",
")",
"||",
"$",
"key",
"===",
"'*'",
")",
"$",
"keyPath",
"=",
"$",
"keyPrefix",
".",
"\"[$key]\"",
";",
"else",
"$",
"keyPath",
"=",
"\"$keyPrefix.$key\"",
";",
"}",
"$",
"siblings",
"=",
"null",
";",
"}",
"}",
"if",
"(",
"$",
"cachedKeyValues",
"!==",
"null",
"&&",
"$",
"keyPrefix",
")",
"{",
"$",
"cachedKeyValues",
"[",
"$",
"keyPrefix",
"]",
"=",
"$",
"siblings",
";",
"// echo \"\\n缓存: keyPrefix=$keyPrefix, key=$keyPath\" . \", value=$siblings\\n\";",
"}",
"}"
] | 验证一条Validation
@param $params array
@param $keys array
@param $keysCount int
@param $validator string
@param string $keyPrefix
@param $cachedKeyValues array|null 缓存已取过的值. 存储格式为: ['key1' => val1, 'key2' => val2]
@param $ignoreRequired bool 是否忽略所有的Required检测子
@throws ValidationException | [
"验证一条Validation"
] | train | https://github.com/photondragon/webgeeker-validation/blob/3bfc2b697ff526897c525af38c9e4ed4c889976d/src/Validation/Validation.php#L3994-L4092 |
nullivex/lib-array2xml | LSS/Array2XML.php | Array2XML.& | public static function &createXML($node_name, $arr = array()) {
$xml = self::getXMLRoot();
$xml->appendChild(self::convert($node_name, $arr));
self::$xml = null; // clear the xml node in the class for 2nd time use.
return $xml;
} | php | public static function &createXML($node_name, $arr = array()) {
$xml = self::getXMLRoot();
$xml->appendChild(self::convert($node_name, $arr));
self::$xml = null; // clear the xml node in the class for 2nd time use.
return $xml;
} | [
"public",
"static",
"function",
"&",
"createXML",
"(",
"$",
"node_name",
",",
"$",
"arr",
"=",
"array",
"(",
")",
")",
"{",
"$",
"xml",
"=",
"self",
"::",
"getXMLRoot",
"(",
")",
";",
"$",
"xml",
"->",
"appendChild",
"(",
"self",
"::",
"convert",
"(",
"$",
"node_name",
",",
"$",
"arr",
")",
")",
";",
"self",
"::",
"$",
"xml",
"=",
"null",
";",
"// clear the xml node in the class for 2nd time use.",
"return",
"$",
"xml",
";",
"}"
] | Convert an Array to XML
@param string $node_name - name of the root node to be converted
@param array $arr - aray to be converterd
@return DomDocument | [
"Convert",
"an",
"Array",
"to",
"XML"
] | train | https://github.com/nullivex/lib-array2xml/blob/a91f18a8dfc69ffabe5f9b068bc39bb202c81d90/LSS/Array2XML.php#L85-L91 |
nullivex/lib-array2xml | LSS/Array2XML.php | Array2XML.bool2str | private static function bool2str($v) {
//convert boolean to text value.
$v = $v === true ? 'true' : $v;
$v = $v === false ? 'false' : $v;
return $v;
} | php | private static function bool2str($v) {
//convert boolean to text value.
$v = $v === true ? 'true' : $v;
$v = $v === false ? 'false' : $v;
return $v;
} | [
"private",
"static",
"function",
"bool2str",
"(",
"$",
"v",
")",
"{",
"//convert boolean to text value.",
"$",
"v",
"=",
"$",
"v",
"===",
"true",
"?",
"'true'",
":",
"$",
"v",
";",
"$",
"v",
"=",
"$",
"v",
"===",
"false",
"?",
"'false'",
":",
"$",
"v",
";",
"return",
"$",
"v",
";",
"}"
] | /*
Get string representation of boolean value | [
"/",
"*",
"Get",
"string",
"representation",
"of",
"boolean",
"value"
] | train | https://github.com/nullivex/lib-array2xml/blob/a91f18a8dfc69ffabe5f9b068bc39bb202c81d90/LSS/Array2XML.php#L193-L198 |
yiisoft/yii-console | src/ErrorHandler.php | ErrorHandler.renderException | protected function renderException($exception)
{
if ($exception instanceof UnknownCommandException) {
// display message and suggest alternatives in case of unknown command
$message = $this->formatMessage($exception->getName() . ': ') . $exception->command;
$alternatives = $exception->getSuggestedAlternatives();
if (count($alternatives) === 1) {
$message .= "\n\nDid you mean \"" . reset($alternatives) . '"?';
} elseif (count($alternatives) > 1) {
$message .= "\n\nDid you mean one of these?\n - " . implode("\n - ", $alternatives);
}
} elseif ($exception instanceof Exception && ($exception instanceof UserException || !YII_DEBUG)) {
$message = $this->formatMessage($exception->getName() . ': ') . $exception->getMessage();
} elseif (YII_DEBUG) {
if ($exception instanceof Exception) {
$message = $this->formatMessage("Exception ({$exception->getName()})");
} elseif ($exception instanceof ErrorException) {
$message = $this->formatMessage($exception->getName());
} else {
$message = $this->formatMessage('Exception');
}
$message .= $this->formatMessage(" '" . get_class($exception) . "'", [Console::BOLD, Console::FG_BLUE])
. ' with message ' . $this->formatMessage("'{$exception->getMessage()}'", [Console::BOLD]) //. "\n"
. "\n\nin " . dirname($exception->getFile()) . DIRECTORY_SEPARATOR . $this->formatMessage(basename($exception->getFile()), [Console::BOLD])
. ':' . $this->formatMessage($exception->getLine(), [Console::BOLD, Console::FG_YELLOW]) . "\n";
if ($exception instanceof \Yiisoft\Db\Exception && !empty($exception->errorInfo)) {
$message .= "\n" . $this->formatMessage("Error Info:\n", [Console::BOLD]) . print_r($exception->errorInfo, true);
}
$message .= "\n" . $this->formatMessage("Stack trace:\n", [Console::BOLD]) . $exception->getTraceAsString();
} else {
$message = $this->formatMessage('Error: ') . $exception->getMessage();
}
if (PHP_SAPI === 'cli') {
Console::stderr($message . "\n");
} else {
echo $message . "\n";
}
} | php | protected function renderException($exception)
{
if ($exception instanceof UnknownCommandException) {
// display message and suggest alternatives in case of unknown command
$message = $this->formatMessage($exception->getName() . ': ') . $exception->command;
$alternatives = $exception->getSuggestedAlternatives();
if (count($alternatives) === 1) {
$message .= "\n\nDid you mean \"" . reset($alternatives) . '"?';
} elseif (count($alternatives) > 1) {
$message .= "\n\nDid you mean one of these?\n - " . implode("\n - ", $alternatives);
}
} elseif ($exception instanceof Exception && ($exception instanceof UserException || !YII_DEBUG)) {
$message = $this->formatMessage($exception->getName() . ': ') . $exception->getMessage();
} elseif (YII_DEBUG) {
if ($exception instanceof Exception) {
$message = $this->formatMessage("Exception ({$exception->getName()})");
} elseif ($exception instanceof ErrorException) {
$message = $this->formatMessage($exception->getName());
} else {
$message = $this->formatMessage('Exception');
}
$message .= $this->formatMessage(" '" . get_class($exception) . "'", [Console::BOLD, Console::FG_BLUE])
. ' with message ' . $this->formatMessage("'{$exception->getMessage()}'", [Console::BOLD]) //. "\n"
. "\n\nin " . dirname($exception->getFile()) . DIRECTORY_SEPARATOR . $this->formatMessage(basename($exception->getFile()), [Console::BOLD])
. ':' . $this->formatMessage($exception->getLine(), [Console::BOLD, Console::FG_YELLOW]) . "\n";
if ($exception instanceof \Yiisoft\Db\Exception && !empty($exception->errorInfo)) {
$message .= "\n" . $this->formatMessage("Error Info:\n", [Console::BOLD]) . print_r($exception->errorInfo, true);
}
$message .= "\n" . $this->formatMessage("Stack trace:\n", [Console::BOLD]) . $exception->getTraceAsString();
} else {
$message = $this->formatMessage('Error: ') . $exception->getMessage();
}
if (PHP_SAPI === 'cli') {
Console::stderr($message . "\n");
} else {
echo $message . "\n";
}
} | [
"protected",
"function",
"renderException",
"(",
"$",
"exception",
")",
"{",
"if",
"(",
"$",
"exception",
"instanceof",
"UnknownCommandException",
")",
"{",
"// display message and suggest alternatives in case of unknown command",
"$",
"message",
"=",
"$",
"this",
"->",
"formatMessage",
"(",
"$",
"exception",
"->",
"getName",
"(",
")",
".",
"': '",
")",
".",
"$",
"exception",
"->",
"command",
";",
"$",
"alternatives",
"=",
"$",
"exception",
"->",
"getSuggestedAlternatives",
"(",
")",
";",
"if",
"(",
"count",
"(",
"$",
"alternatives",
")",
"===",
"1",
")",
"{",
"$",
"message",
".=",
"\"\\n\\nDid you mean \\\"\"",
".",
"reset",
"(",
"$",
"alternatives",
")",
".",
"'\"?'",
";",
"}",
"elseif",
"(",
"count",
"(",
"$",
"alternatives",
")",
">",
"1",
")",
"{",
"$",
"message",
".=",
"\"\\n\\nDid you mean one of these?\\n - \"",
".",
"implode",
"(",
"\"\\n - \"",
",",
"$",
"alternatives",
")",
";",
"}",
"}",
"elseif",
"(",
"$",
"exception",
"instanceof",
"Exception",
"&&",
"(",
"$",
"exception",
"instanceof",
"UserException",
"||",
"!",
"YII_DEBUG",
")",
")",
"{",
"$",
"message",
"=",
"$",
"this",
"->",
"formatMessage",
"(",
"$",
"exception",
"->",
"getName",
"(",
")",
".",
"': '",
")",
".",
"$",
"exception",
"->",
"getMessage",
"(",
")",
";",
"}",
"elseif",
"(",
"YII_DEBUG",
")",
"{",
"if",
"(",
"$",
"exception",
"instanceof",
"Exception",
")",
"{",
"$",
"message",
"=",
"$",
"this",
"->",
"formatMessage",
"(",
"\"Exception ({$exception->getName()})\"",
")",
";",
"}",
"elseif",
"(",
"$",
"exception",
"instanceof",
"ErrorException",
")",
"{",
"$",
"message",
"=",
"$",
"this",
"->",
"formatMessage",
"(",
"$",
"exception",
"->",
"getName",
"(",
")",
")",
";",
"}",
"else",
"{",
"$",
"message",
"=",
"$",
"this",
"->",
"formatMessage",
"(",
"'Exception'",
")",
";",
"}",
"$",
"message",
".=",
"$",
"this",
"->",
"formatMessage",
"(",
"\" '\"",
".",
"get_class",
"(",
"$",
"exception",
")",
".",
"\"'\"",
",",
"[",
"Console",
"::",
"BOLD",
",",
"Console",
"::",
"FG_BLUE",
"]",
")",
".",
"' with message '",
".",
"$",
"this",
"->",
"formatMessage",
"(",
"\"'{$exception->getMessage()}'\"",
",",
"[",
"Console",
"::",
"BOLD",
"]",
")",
"//. \"\\n\"",
".",
"\"\\n\\nin \"",
".",
"dirname",
"(",
"$",
"exception",
"->",
"getFile",
"(",
")",
")",
".",
"DIRECTORY_SEPARATOR",
".",
"$",
"this",
"->",
"formatMessage",
"(",
"basename",
"(",
"$",
"exception",
"->",
"getFile",
"(",
")",
")",
",",
"[",
"Console",
"::",
"BOLD",
"]",
")",
".",
"':'",
".",
"$",
"this",
"->",
"formatMessage",
"(",
"$",
"exception",
"->",
"getLine",
"(",
")",
",",
"[",
"Console",
"::",
"BOLD",
",",
"Console",
"::",
"FG_YELLOW",
"]",
")",
".",
"\"\\n\"",
";",
"if",
"(",
"$",
"exception",
"instanceof",
"\\",
"Yiisoft",
"\\",
"Db",
"\\",
"Exception",
"&&",
"!",
"empty",
"(",
"$",
"exception",
"->",
"errorInfo",
")",
")",
"{",
"$",
"message",
".=",
"\"\\n\"",
".",
"$",
"this",
"->",
"formatMessage",
"(",
"\"Error Info:\\n\"",
",",
"[",
"Console",
"::",
"BOLD",
"]",
")",
".",
"print_r",
"(",
"$",
"exception",
"->",
"errorInfo",
",",
"true",
")",
";",
"}",
"$",
"message",
".=",
"\"\\n\"",
".",
"$",
"this",
"->",
"formatMessage",
"(",
"\"Stack trace:\\n\"",
",",
"[",
"Console",
"::",
"BOLD",
"]",
")",
".",
"$",
"exception",
"->",
"getTraceAsString",
"(",
")",
";",
"}",
"else",
"{",
"$",
"message",
"=",
"$",
"this",
"->",
"formatMessage",
"(",
"'Error: '",
")",
".",
"$",
"exception",
"->",
"getMessage",
"(",
")",
";",
"}",
"if",
"(",
"PHP_SAPI",
"===",
"'cli'",
")",
"{",
"Console",
"::",
"stderr",
"(",
"$",
"message",
".",
"\"\\n\"",
")",
";",
"}",
"else",
"{",
"echo",
"$",
"message",
".",
"\"\\n\"",
";",
"}",
"}"
] | Renders an exception using ansi format for console output.
@param \Exception $exception the exception to be rendered. | [
"Renders",
"an",
"exception",
"using",
"ansi",
"format",
"for",
"console",
"output",
"."
] | train | https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/ErrorHandler.php#L30-L68 |
yiisoft/yii-console | src/ErrorHandler.php | ErrorHandler.formatMessage | protected function formatMessage($message, $format = [Console::FG_RED, Console::BOLD])
{
$stream = (PHP_SAPI === 'cli') ? \STDERR : \STDOUT;
// try controller first to allow check for --color switch
if ($this->app->controller instanceof Controller && $this->app->controller->isColorEnabled($stream)
|| $this->app instanceof Application && Console::streamSupportsAnsiColors($stream)) {
$message = Console::ansiFormat($message, $format);
}
return $message;
} | php | protected function formatMessage($message, $format = [Console::FG_RED, Console::BOLD])
{
$stream = (PHP_SAPI === 'cli') ? \STDERR : \STDOUT;
// try controller first to allow check for --color switch
if ($this->app->controller instanceof Controller && $this->app->controller->isColorEnabled($stream)
|| $this->app instanceof Application && Console::streamSupportsAnsiColors($stream)) {
$message = Console::ansiFormat($message, $format);
}
return $message;
} | [
"protected",
"function",
"formatMessage",
"(",
"$",
"message",
",",
"$",
"format",
"=",
"[",
"Console",
"::",
"FG_RED",
",",
"Console",
"::",
"BOLD",
"]",
")",
"{",
"$",
"stream",
"=",
"(",
"PHP_SAPI",
"===",
"'cli'",
")",
"?",
"\\",
"STDERR",
":",
"\\",
"STDOUT",
";",
"// try controller first to allow check for --color switch",
"if",
"(",
"$",
"this",
"->",
"app",
"->",
"controller",
"instanceof",
"Controller",
"&&",
"$",
"this",
"->",
"app",
"->",
"controller",
"->",
"isColorEnabled",
"(",
"$",
"stream",
")",
"||",
"$",
"this",
"->",
"app",
"instanceof",
"Application",
"&&",
"Console",
"::",
"streamSupportsAnsiColors",
"(",
"$",
"stream",
")",
")",
"{",
"$",
"message",
"=",
"Console",
"::",
"ansiFormat",
"(",
"$",
"message",
",",
"$",
"format",
")",
";",
"}",
"return",
"$",
"message",
";",
"}"
] | Colorizes a message for console output.
@param string $message the message to colorize.
@param array $format the message format.
@return string the colorized message.
@see Console::ansiFormat() for details on how to specify the message format. | [
"Colorizes",
"a",
"message",
"for",
"console",
"output",
"."
] | train | https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/ErrorHandler.php#L77-L87 |
yiisoft/yii-jquery | src/Validators/Client/RegularExpressionValidator.php | RegularExpressionValidator.getClientOptions | public function getClientOptions($validator, $model, $attribute)
{
$pattern = Html::escapeJsRegularExpression($validator->pattern);
$options = [
'pattern' => new JsExpression($pattern),
'not' => $validator->not,
'message' => $validator->formatMessage($validator->message, [
'attribute' => $model->getAttributeLabel($attribute),
]),
];
if ($validator->skipOnEmpty) {
$options['skipOnEmpty'] = 1;
}
return $options;
} | php | public function getClientOptions($validator, $model, $attribute)
{
$pattern = Html::escapeJsRegularExpression($validator->pattern);
$options = [
'pattern' => new JsExpression($pattern),
'not' => $validator->not,
'message' => $validator->formatMessage($validator->message, [
'attribute' => $model->getAttributeLabel($attribute),
]),
];
if ($validator->skipOnEmpty) {
$options['skipOnEmpty'] = 1;
}
return $options;
} | [
"public",
"function",
"getClientOptions",
"(",
"$",
"validator",
",",
"$",
"model",
",",
"$",
"attribute",
")",
"{",
"$",
"pattern",
"=",
"Html",
"::",
"escapeJsRegularExpression",
"(",
"$",
"validator",
"->",
"pattern",
")",
";",
"$",
"options",
"=",
"[",
"'pattern'",
"=>",
"new",
"JsExpression",
"(",
"$",
"pattern",
")",
",",
"'not'",
"=>",
"$",
"validator",
"->",
"not",
",",
"'message'",
"=>",
"$",
"validator",
"->",
"formatMessage",
"(",
"$",
"validator",
"->",
"message",
",",
"[",
"'attribute'",
"=>",
"$",
"model",
"->",
"getAttributeLabel",
"(",
"$",
"attribute",
")",
",",
"]",
")",
",",
"]",
";",
"if",
"(",
"$",
"validator",
"->",
"skipOnEmpty",
")",
"{",
"$",
"options",
"[",
"'skipOnEmpty'",
"]",
"=",
"1",
";",
"}",
"return",
"$",
"options",
";",
"}"
] | Returns the client-side validation options.
@param \yii\validators\RegularExpressionValidator $validator the server-side validator.
@param \yii\base\Model $model the model being validated
@param string $attribute the attribute name being validated
@return array the client-side validation options | [
"Returns",
"the",
"client",
"-",
"side",
"validation",
"options",
"."
] | train | https://github.com/yiisoft/yii-jquery/blob/1c257928cba2b46d267e90771652abe2b0e2cfcb/src/Validators/Client/RegularExpressionValidator.php#L44-L60 |
yiisoft/yii-console | src/Controllers/FixtureController.php | FixtureController.actionLoad | public function actionLoad(array $fixturesInput = [])
{
if ($fixturesInput === []) {
$this->stdout($this->getHelpSummary() . "\n");
$helpCommand = Console::ansiFormat('yii help fixture', [Console::FG_CYAN]);
$this->stdout("Use $helpCommand to get usage info.\n");
return ExitCode::OK;
}
$filtered = $this->filterFixtures($fixturesInput);
$except = $filtered['except'];
if (!$this->needToApplyAll($fixturesInput[0])) {
$fixtures = $filtered['apply'];
$foundFixtures = $this->findFixtures($fixtures);
$notFoundFixtures = array_diff($fixtures, $foundFixtures);
if ($notFoundFixtures) {
$this->notifyNotFound($notFoundFixtures);
}
} else {
$foundFixtures = $this->findFixtures();
}
$fixturesToLoad = array_diff($foundFixtures, $except);
if (!$foundFixtures) {
throw new Exception(
'No files were found for: "' . implode(', ', $fixturesInput) . "\".\n" .
"Check that files exist under fixtures path: \n\"" . $this->getFixturePath() . '".'
);
}
if (!$fixturesToLoad) {
$this->notifyNothingToLoad($foundFixtures, $except);
return ExitCode::OK;
}
if (!$this->confirmLoad($fixturesToLoad, $except)) {
return ExitCode::OK;
}
$fixtures = $this->getFixturesConfig(array_merge($this->globalFixtures, $fixturesToLoad));
if (!$fixtures) {
throw new Exception('No fixtures were found in namespace: "' . $this->namespace . '"' . '');
}
$fixturesObjects = $this->createFixtures($fixtures);
$this->unloadFixtures($fixturesObjects);
$this->loadFixtures($fixturesObjects);
$this->notifyLoaded($fixtures);
return ExitCode::OK;
} | php | public function actionLoad(array $fixturesInput = [])
{
if ($fixturesInput === []) {
$this->stdout($this->getHelpSummary() . "\n");
$helpCommand = Console::ansiFormat('yii help fixture', [Console::FG_CYAN]);
$this->stdout("Use $helpCommand to get usage info.\n");
return ExitCode::OK;
}
$filtered = $this->filterFixtures($fixturesInput);
$except = $filtered['except'];
if (!$this->needToApplyAll($fixturesInput[0])) {
$fixtures = $filtered['apply'];
$foundFixtures = $this->findFixtures($fixtures);
$notFoundFixtures = array_diff($fixtures, $foundFixtures);
if ($notFoundFixtures) {
$this->notifyNotFound($notFoundFixtures);
}
} else {
$foundFixtures = $this->findFixtures();
}
$fixturesToLoad = array_diff($foundFixtures, $except);
if (!$foundFixtures) {
throw new Exception(
'No files were found for: "' . implode(', ', $fixturesInput) . "\".\n" .
"Check that files exist under fixtures path: \n\"" . $this->getFixturePath() . '".'
);
}
if (!$fixturesToLoad) {
$this->notifyNothingToLoad($foundFixtures, $except);
return ExitCode::OK;
}
if (!$this->confirmLoad($fixturesToLoad, $except)) {
return ExitCode::OK;
}
$fixtures = $this->getFixturesConfig(array_merge($this->globalFixtures, $fixturesToLoad));
if (!$fixtures) {
throw new Exception('No fixtures were found in namespace: "' . $this->namespace . '"' . '');
}
$fixturesObjects = $this->createFixtures($fixtures);
$this->unloadFixtures($fixturesObjects);
$this->loadFixtures($fixturesObjects);
$this->notifyLoaded($fixtures);
return ExitCode::OK;
} | [
"public",
"function",
"actionLoad",
"(",
"array",
"$",
"fixturesInput",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"$",
"fixturesInput",
"===",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"stdout",
"(",
"$",
"this",
"->",
"getHelpSummary",
"(",
")",
".",
"\"\\n\"",
")",
";",
"$",
"helpCommand",
"=",
"Console",
"::",
"ansiFormat",
"(",
"'yii help fixture'",
",",
"[",
"Console",
"::",
"FG_CYAN",
"]",
")",
";",
"$",
"this",
"->",
"stdout",
"(",
"\"Use $helpCommand to get usage info.\\n\"",
")",
";",
"return",
"ExitCode",
"::",
"OK",
";",
"}",
"$",
"filtered",
"=",
"$",
"this",
"->",
"filterFixtures",
"(",
"$",
"fixturesInput",
")",
";",
"$",
"except",
"=",
"$",
"filtered",
"[",
"'except'",
"]",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"needToApplyAll",
"(",
"$",
"fixturesInput",
"[",
"0",
"]",
")",
")",
"{",
"$",
"fixtures",
"=",
"$",
"filtered",
"[",
"'apply'",
"]",
";",
"$",
"foundFixtures",
"=",
"$",
"this",
"->",
"findFixtures",
"(",
"$",
"fixtures",
")",
";",
"$",
"notFoundFixtures",
"=",
"array_diff",
"(",
"$",
"fixtures",
",",
"$",
"foundFixtures",
")",
";",
"if",
"(",
"$",
"notFoundFixtures",
")",
"{",
"$",
"this",
"->",
"notifyNotFound",
"(",
"$",
"notFoundFixtures",
")",
";",
"}",
"}",
"else",
"{",
"$",
"foundFixtures",
"=",
"$",
"this",
"->",
"findFixtures",
"(",
")",
";",
"}",
"$",
"fixturesToLoad",
"=",
"array_diff",
"(",
"$",
"foundFixtures",
",",
"$",
"except",
")",
";",
"if",
"(",
"!",
"$",
"foundFixtures",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'No files were found for: \"'",
".",
"implode",
"(",
"', '",
",",
"$",
"fixturesInput",
")",
".",
"\"\\\".\\n\"",
".",
"\"Check that files exist under fixtures path: \\n\\\"\"",
".",
"$",
"this",
"->",
"getFixturePath",
"(",
")",
".",
"'\".'",
")",
";",
"}",
"if",
"(",
"!",
"$",
"fixturesToLoad",
")",
"{",
"$",
"this",
"->",
"notifyNothingToLoad",
"(",
"$",
"foundFixtures",
",",
"$",
"except",
")",
";",
"return",
"ExitCode",
"::",
"OK",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"confirmLoad",
"(",
"$",
"fixturesToLoad",
",",
"$",
"except",
")",
")",
"{",
"return",
"ExitCode",
"::",
"OK",
";",
"}",
"$",
"fixtures",
"=",
"$",
"this",
"->",
"getFixturesConfig",
"(",
"array_merge",
"(",
"$",
"this",
"->",
"globalFixtures",
",",
"$",
"fixturesToLoad",
")",
")",
";",
"if",
"(",
"!",
"$",
"fixtures",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'No fixtures were found in namespace: \"'",
".",
"$",
"this",
"->",
"namespace",
".",
"'\"'",
".",
"''",
")",
";",
"}",
"$",
"fixturesObjects",
"=",
"$",
"this",
"->",
"createFixtures",
"(",
"$",
"fixtures",
")",
";",
"$",
"this",
"->",
"unloadFixtures",
"(",
"$",
"fixturesObjects",
")",
";",
"$",
"this",
"->",
"loadFixtures",
"(",
"$",
"fixturesObjects",
")",
";",
"$",
"this",
"->",
"notifyLoaded",
"(",
"$",
"fixtures",
")",
";",
"return",
"ExitCode",
"::",
"OK",
";",
"}"
] | Loads the specified fixture data.
For example,
```
# load the fixture data specified by User and UserProfile.
# any existing fixture data will be removed first
yii fixture/load "User, UserProfile"
# load all available fixtures found under 'tests\unit\fixtures'
yii fixture/load "*"
# load all fixtures except User and UserProfile
yii fixture/load "*, -User, -UserProfile"
```
@param array $fixturesInput
@return int return code
@throws Exception if the specified fixture does not exist. | [
"Loads",
"the",
"specified",
"fixture",
"data",
"."
] | train | https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Controllers/FixtureController.php#L109-L167 |
yiisoft/yii-console | src/Controllers/FixtureController.php | FixtureController.actionUnload | public function actionUnload(array $fixturesInput = [])
{
$filtered = $this->filterFixtures($fixturesInput);
$except = $filtered['except'];
if (!$this->needToApplyAll($fixturesInput[0])) {
$fixtures = $filtered['apply'];
$foundFixtures = $this->findFixtures($fixtures);
$notFoundFixtures = array_diff($fixtures, $foundFixtures);
if ($notFoundFixtures) {
$this->notifyNotFound($notFoundFixtures);
}
} else {
$foundFixtures = $this->findFixtures();
}
$fixturesToUnload = array_diff($foundFixtures, $except);
if (!$foundFixtures) {
throw new Exception(
'No files were found for: "' . implode(', ', $fixturesInput) . "\".\n" .
"Check that files exist under fixtures path: \n\"" . $this->getFixturePath() . '".'
);
}
if (!$fixturesToUnload) {
$this->notifyNothingToUnload($foundFixtures, $except);
return ExitCode::OK;
}
if (!$this->confirmUnload($fixturesToUnload, $except)) {
return ExitCode::OK;
}
$fixtures = $this->getFixturesConfig(array_merge($this->globalFixtures, $fixturesToUnload));
if (!$fixtures) {
throw new Exception('No fixtures were found in namespace: ' . $this->namespace . '".');
}
$this->unloadFixtures($this->createFixtures($fixtures));
$this->notifyUnloaded($fixtures);
} | php | public function actionUnload(array $fixturesInput = [])
{
$filtered = $this->filterFixtures($fixturesInput);
$except = $filtered['except'];
if (!$this->needToApplyAll($fixturesInput[0])) {
$fixtures = $filtered['apply'];
$foundFixtures = $this->findFixtures($fixtures);
$notFoundFixtures = array_diff($fixtures, $foundFixtures);
if ($notFoundFixtures) {
$this->notifyNotFound($notFoundFixtures);
}
} else {
$foundFixtures = $this->findFixtures();
}
$fixturesToUnload = array_diff($foundFixtures, $except);
if (!$foundFixtures) {
throw new Exception(
'No files were found for: "' . implode(', ', $fixturesInput) . "\".\n" .
"Check that files exist under fixtures path: \n\"" . $this->getFixturePath() . '".'
);
}
if (!$fixturesToUnload) {
$this->notifyNothingToUnload($foundFixtures, $except);
return ExitCode::OK;
}
if (!$this->confirmUnload($fixturesToUnload, $except)) {
return ExitCode::OK;
}
$fixtures = $this->getFixturesConfig(array_merge($this->globalFixtures, $fixturesToUnload));
if (!$fixtures) {
throw new Exception('No fixtures were found in namespace: ' . $this->namespace . '".');
}
$this->unloadFixtures($this->createFixtures($fixtures));
$this->notifyUnloaded($fixtures);
} | [
"public",
"function",
"actionUnload",
"(",
"array",
"$",
"fixturesInput",
"=",
"[",
"]",
")",
"{",
"$",
"filtered",
"=",
"$",
"this",
"->",
"filterFixtures",
"(",
"$",
"fixturesInput",
")",
";",
"$",
"except",
"=",
"$",
"filtered",
"[",
"'except'",
"]",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"needToApplyAll",
"(",
"$",
"fixturesInput",
"[",
"0",
"]",
")",
")",
"{",
"$",
"fixtures",
"=",
"$",
"filtered",
"[",
"'apply'",
"]",
";",
"$",
"foundFixtures",
"=",
"$",
"this",
"->",
"findFixtures",
"(",
"$",
"fixtures",
")",
";",
"$",
"notFoundFixtures",
"=",
"array_diff",
"(",
"$",
"fixtures",
",",
"$",
"foundFixtures",
")",
";",
"if",
"(",
"$",
"notFoundFixtures",
")",
"{",
"$",
"this",
"->",
"notifyNotFound",
"(",
"$",
"notFoundFixtures",
")",
";",
"}",
"}",
"else",
"{",
"$",
"foundFixtures",
"=",
"$",
"this",
"->",
"findFixtures",
"(",
")",
";",
"}",
"$",
"fixturesToUnload",
"=",
"array_diff",
"(",
"$",
"foundFixtures",
",",
"$",
"except",
")",
";",
"if",
"(",
"!",
"$",
"foundFixtures",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'No files were found for: \"'",
".",
"implode",
"(",
"', '",
",",
"$",
"fixturesInput",
")",
".",
"\"\\\".\\n\"",
".",
"\"Check that files exist under fixtures path: \\n\\\"\"",
".",
"$",
"this",
"->",
"getFixturePath",
"(",
")",
".",
"'\".'",
")",
";",
"}",
"if",
"(",
"!",
"$",
"fixturesToUnload",
")",
"{",
"$",
"this",
"->",
"notifyNothingToUnload",
"(",
"$",
"foundFixtures",
",",
"$",
"except",
")",
";",
"return",
"ExitCode",
"::",
"OK",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"confirmUnload",
"(",
"$",
"fixturesToUnload",
",",
"$",
"except",
")",
")",
"{",
"return",
"ExitCode",
"::",
"OK",
";",
"}",
"$",
"fixtures",
"=",
"$",
"this",
"->",
"getFixturesConfig",
"(",
"array_merge",
"(",
"$",
"this",
"->",
"globalFixtures",
",",
"$",
"fixturesToUnload",
")",
")",
";",
"if",
"(",
"!",
"$",
"fixtures",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'No fixtures were found in namespace: '",
".",
"$",
"this",
"->",
"namespace",
".",
"'\".'",
")",
";",
"}",
"$",
"this",
"->",
"unloadFixtures",
"(",
"$",
"this",
"->",
"createFixtures",
"(",
"$",
"fixtures",
")",
")",
";",
"$",
"this",
"->",
"notifyUnloaded",
"(",
"$",
"fixtures",
")",
";",
"}"
] | Unloads the specified fixtures.
For example,
```
# unload the fixture data specified by User and UserProfile.
yii fixture/unload "User, UserProfile"
# unload all fixtures found under 'tests\unit\fixtures'
yii fixture/unload "*"
# unload all fixtures except User and UserProfile
yii fixture/unload "*, -User, -UserProfile"
```
@param array $fixturesInput
@return int return code
@throws Exception if the specified fixture does not exist. | [
"Unloads",
"the",
"specified",
"fixtures",
"."
] | train | https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Controllers/FixtureController.php#L189-L233 |
yiisoft/yii-console | src/Controllers/FixtureController.php | FixtureController.getFixturePath | private function getFixturePath()
{
try {
return $this->app->getAlias('@' . str_replace('\\', '/', $this->namespace));
} catch (InvalidArgumentException $e) {
throw new InvalidConfigException('Invalid fixture namespace: "' . $this->namespace . '". Please, check your FixtureController::namespace parameter');
}
} | php | private function getFixturePath()
{
try {
return $this->app->getAlias('@' . str_replace('\\', '/', $this->namespace));
} catch (InvalidArgumentException $e) {
throw new InvalidConfigException('Invalid fixture namespace: "' . $this->namespace . '". Please, check your FixtureController::namespace parameter');
}
} | [
"private",
"function",
"getFixturePath",
"(",
")",
"{",
"try",
"{",
"return",
"$",
"this",
"->",
"app",
"->",
"getAlias",
"(",
"'@'",
".",
"str_replace",
"(",
"'\\\\'",
",",
"'/'",
",",
"$",
"this",
"->",
"namespace",
")",
")",
";",
"}",
"catch",
"(",
"InvalidArgumentException",
"$",
"e",
")",
"{",
"throw",
"new",
"InvalidConfigException",
"(",
"'Invalid fixture namespace: \"'",
".",
"$",
"this",
"->",
"namespace",
".",
"'\". Please, check your FixtureController::namespace parameter'",
")",
";",
"}",
"}"
] | Returns fixture path that determined on fixtures namespace.
@throws InvalidConfigException if fixture namespace is invalid
@return string fixture path | [
"Returns",
"fixture",
"path",
"that",
"determined",
"on",
"fixtures",
"namespace",
"."
] | train | https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Controllers/FixtureController.php#L514-L521 |
yiisoft/yii-console | src/Controllers/CacheController.php | CacheController.actionIndex | public function actionIndex()
{
$caches = $this->findCaches();
if (!empty($caches)) {
$this->notifyCachesCanBeCleared($caches);
} else {
$this->notifyNoCachesFound();
}
} | php | public function actionIndex()
{
$caches = $this->findCaches();
if (!empty($caches)) {
$this->notifyCachesCanBeCleared($caches);
} else {
$this->notifyNoCachesFound();
}
} | [
"public",
"function",
"actionIndex",
"(",
")",
"{",
"$",
"caches",
"=",
"$",
"this",
"->",
"findCaches",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"caches",
")",
")",
"{",
"$",
"this",
"->",
"notifyCachesCanBeCleared",
"(",
"$",
"caches",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"notifyNoCachesFound",
"(",
")",
";",
"}",
"}"
] | Lists the caches that can be cleared. | [
"Lists",
"the",
"caches",
"that",
"can",
"be",
"cleared",
"."
] | train | https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Controllers/CacheController.php#L53-L62 |
yiisoft/yii-console | src/Controllers/CacheController.php | CacheController.actionClear | public function actionClear()
{
$cachesInput = func_get_args();
if (empty($cachesInput)) {
throw new Exception('You should specify cache components names');
}
$caches = $this->findCaches($cachesInput);
$cachesInfo = [];
$foundCaches = array_keys($caches);
$notFoundCaches = array_diff($cachesInput, array_keys($caches));
if ($notFoundCaches) {
$this->notifyNotFoundCaches($notFoundCaches);
}
if (!$foundCaches) {
$this->notifyNoCachesFound();
return ExitCode::OK;
}
if (!$this->confirmClear($foundCaches)) {
return ExitCode::OK;
}
foreach ($caches as $name => $class) {
$cachesInfo[] = [
'name' => $name,
'class' => $class,
'is_flushed' => $this->canBeCleared($class) ? $this->app->get($name)->clear() : false,
];
}
$this->notifyCleared($cachesInfo);
} | php | public function actionClear()
{
$cachesInput = func_get_args();
if (empty($cachesInput)) {
throw new Exception('You should specify cache components names');
}
$caches = $this->findCaches($cachesInput);
$cachesInfo = [];
$foundCaches = array_keys($caches);
$notFoundCaches = array_diff($cachesInput, array_keys($caches));
if ($notFoundCaches) {
$this->notifyNotFoundCaches($notFoundCaches);
}
if (!$foundCaches) {
$this->notifyNoCachesFound();
return ExitCode::OK;
}
if (!$this->confirmClear($foundCaches)) {
return ExitCode::OK;
}
foreach ($caches as $name => $class) {
$cachesInfo[] = [
'name' => $name,
'class' => $class,
'is_flushed' => $this->canBeCleared($class) ? $this->app->get($name)->clear() : false,
];
}
$this->notifyCleared($cachesInfo);
} | [
"public",
"function",
"actionClear",
"(",
")",
"{",
"$",
"cachesInput",
"=",
"func_get_args",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"cachesInput",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'You should specify cache components names'",
")",
";",
"}",
"$",
"caches",
"=",
"$",
"this",
"->",
"findCaches",
"(",
"$",
"cachesInput",
")",
";",
"$",
"cachesInfo",
"=",
"[",
"]",
";",
"$",
"foundCaches",
"=",
"array_keys",
"(",
"$",
"caches",
")",
";",
"$",
"notFoundCaches",
"=",
"array_diff",
"(",
"$",
"cachesInput",
",",
"array_keys",
"(",
"$",
"caches",
")",
")",
";",
"if",
"(",
"$",
"notFoundCaches",
")",
"{",
"$",
"this",
"->",
"notifyNotFoundCaches",
"(",
"$",
"notFoundCaches",
")",
";",
"}",
"if",
"(",
"!",
"$",
"foundCaches",
")",
"{",
"$",
"this",
"->",
"notifyNoCachesFound",
"(",
")",
";",
"return",
"ExitCode",
"::",
"OK",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"confirmClear",
"(",
"$",
"foundCaches",
")",
")",
"{",
"return",
"ExitCode",
"::",
"OK",
";",
"}",
"foreach",
"(",
"$",
"caches",
"as",
"$",
"name",
"=>",
"$",
"class",
")",
"{",
"$",
"cachesInfo",
"[",
"]",
"=",
"[",
"'name'",
"=>",
"$",
"name",
",",
"'class'",
"=>",
"$",
"class",
",",
"'is_flushed'",
"=>",
"$",
"this",
"->",
"canBeCleared",
"(",
"$",
"class",
")",
"?",
"$",
"this",
"->",
"app",
"->",
"get",
"(",
"$",
"name",
")",
"->",
"clear",
"(",
")",
":",
"false",
",",
"]",
";",
"}",
"$",
"this",
"->",
"notifyCleared",
"(",
"$",
"cachesInfo",
")",
";",
"}"
] | Clears given cache components.
For example,
```
# clears caches specified by their id: "first", "second", "third"
yii cache/clear first second third
``` | [
"Clears",
"given",
"cache",
"components",
".",
"For",
"example"
] | train | https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Controllers/CacheController.php#L73-L109 |
yiisoft/yii-console | src/Controllers/CacheController.php | CacheController.actionClearAll | public function actionClearAll()
{
$caches = $this->findCaches();
$cachesInfo = [];
if (empty($caches)) {
$this->notifyNoCachesFound();
return ExitCode::OK;
}
foreach ($caches as $name => $class) {
$cachesInfo[] = [
'name' => $name,
'class' => $class,
'is_flushed' => $this->canBeCleared($class) ? $this->app->get($name)->clear() : false,
];
}
$this->notifyCleared($cachesInfo);
} | php | public function actionClearAll()
{
$caches = $this->findCaches();
$cachesInfo = [];
if (empty($caches)) {
$this->notifyNoCachesFound();
return ExitCode::OK;
}
foreach ($caches as $name => $class) {
$cachesInfo[] = [
'name' => $name,
'class' => $class,
'is_flushed' => $this->canBeCleared($class) ? $this->app->get($name)->clear() : false,
];
}
$this->notifyCleared($cachesInfo);
} | [
"public",
"function",
"actionClearAll",
"(",
")",
"{",
"$",
"caches",
"=",
"$",
"this",
"->",
"findCaches",
"(",
")",
";",
"$",
"cachesInfo",
"=",
"[",
"]",
";",
"if",
"(",
"empty",
"(",
"$",
"caches",
")",
")",
"{",
"$",
"this",
"->",
"notifyNoCachesFound",
"(",
")",
";",
"return",
"ExitCode",
"::",
"OK",
";",
"}",
"foreach",
"(",
"$",
"caches",
"as",
"$",
"name",
"=>",
"$",
"class",
")",
"{",
"$",
"cachesInfo",
"[",
"]",
"=",
"[",
"'name'",
"=>",
"$",
"name",
",",
"'class'",
"=>",
"$",
"class",
",",
"'is_flushed'",
"=>",
"$",
"this",
"->",
"canBeCleared",
"(",
"$",
"class",
")",
"?",
"$",
"this",
"->",
"app",
"->",
"get",
"(",
"$",
"name",
")",
"->",
"clear",
"(",
")",
":",
"false",
",",
"]",
";",
"}",
"$",
"this",
"->",
"notifyCleared",
"(",
"$",
"cachesInfo",
")",
";",
"}"
] | Flushes all caches registered in the system. | [
"Flushes",
"all",
"caches",
"registered",
"in",
"the",
"system",
"."
] | train | https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Controllers/CacheController.php#L114-L133 |
yiisoft/yii-console | src/Controllers/CacheController.php | CacheController.actionClearSchema | public function actionClearSchema($db = 'db')
{
$connection = $this->app->get($db, false);
if ($connection === null) {
$this->stdout("Unknown component \"$db\".\n", Console::FG_RED);
return ExitCode::UNSPECIFIED_ERROR;
}
if (!$connection instanceof \Yiisoft\Db\Connection) {
$this->stdout("\"$db\" component doesn't inherit \\Yiisoft\\Db\\Connection.\n", Console::FG_RED);
return ExitCode::UNSPECIFIED_ERROR;
} elseif (!$this->confirm("Flush cache schema for \"$db\" connection?")) {
return ExitCode::OK;
}
try {
$schema = $connection->getSchema();
$schema->refresh();
$this->stdout("Schema cache for component \"$db\", was flushed.\n\n", Console::FG_GREEN);
} catch (\Exception $e) {
$this->stdout($e->getMessage() . "\n\n", Console::FG_RED);
}
} | php | public function actionClearSchema($db = 'db')
{
$connection = $this->app->get($db, false);
if ($connection === null) {
$this->stdout("Unknown component \"$db\".\n", Console::FG_RED);
return ExitCode::UNSPECIFIED_ERROR;
}
if (!$connection instanceof \Yiisoft\Db\Connection) {
$this->stdout("\"$db\" component doesn't inherit \\Yiisoft\\Db\\Connection.\n", Console::FG_RED);
return ExitCode::UNSPECIFIED_ERROR;
} elseif (!$this->confirm("Flush cache schema for \"$db\" connection?")) {
return ExitCode::OK;
}
try {
$schema = $connection->getSchema();
$schema->refresh();
$this->stdout("Schema cache for component \"$db\", was flushed.\n\n", Console::FG_GREEN);
} catch (\Exception $e) {
$this->stdout($e->getMessage() . "\n\n", Console::FG_RED);
}
} | [
"public",
"function",
"actionClearSchema",
"(",
"$",
"db",
"=",
"'db'",
")",
"{",
"$",
"connection",
"=",
"$",
"this",
"->",
"app",
"->",
"get",
"(",
"$",
"db",
",",
"false",
")",
";",
"if",
"(",
"$",
"connection",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"stdout",
"(",
"\"Unknown component \\\"$db\\\".\\n\"",
",",
"Console",
"::",
"FG_RED",
")",
";",
"return",
"ExitCode",
"::",
"UNSPECIFIED_ERROR",
";",
"}",
"if",
"(",
"!",
"$",
"connection",
"instanceof",
"\\",
"Yiisoft",
"\\",
"Db",
"\\",
"Connection",
")",
"{",
"$",
"this",
"->",
"stdout",
"(",
"\"\\\"$db\\\" component doesn't inherit \\\\Yiisoft\\\\Db\\\\Connection.\\n\"",
",",
"Console",
"::",
"FG_RED",
")",
";",
"return",
"ExitCode",
"::",
"UNSPECIFIED_ERROR",
";",
"}",
"elseif",
"(",
"!",
"$",
"this",
"->",
"confirm",
"(",
"\"Flush cache schema for \\\"$db\\\" connection?\"",
")",
")",
"{",
"return",
"ExitCode",
"::",
"OK",
";",
"}",
"try",
"{",
"$",
"schema",
"=",
"$",
"connection",
"->",
"getSchema",
"(",
")",
";",
"$",
"schema",
"->",
"refresh",
"(",
")",
";",
"$",
"this",
"->",
"stdout",
"(",
"\"Schema cache for component \\\"$db\\\", was flushed.\\n\\n\"",
",",
"Console",
"::",
"FG_GREEN",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"stdout",
"(",
"$",
"e",
"->",
"getMessage",
"(",
")",
".",
"\"\\n\\n\"",
",",
"Console",
"::",
"FG_RED",
")",
";",
"}",
"}"
] | Clears DB schema cache for a given connection component.
```
# clears cache schema specified by component id: "db"
yii cache/clear-schema db
```
@param string $db id connection component
@return int exit code
@throws Exception
@throws \yii\exceptions\InvalidConfigException
@since 2.0.1 | [
"Clears",
"DB",
"schema",
"cache",
"for",
"a",
"given",
"connection",
"component",
"."
] | train | https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Controllers/CacheController.php#L150-L172 |
yiisoft/yii-console | src/Controllers/CacheController.php | CacheController.notifyCachesCanBeCleared | private function notifyCachesCanBeCleared($caches)
{
$this->stdout("The following caches were found in the system:\n\n", Console::FG_YELLOW);
foreach ($caches as $name => $class) {
if ($this->canBeCleared($class)) {
$this->stdout("\t* $name ($class)\n", Console::FG_GREEN);
} else {
$this->stdout("\t* $name ($class) - can not be flushed via console\n", Console::FG_YELLOW);
}
}
$this->stdout("\n");
} | php | private function notifyCachesCanBeCleared($caches)
{
$this->stdout("The following caches were found in the system:\n\n", Console::FG_YELLOW);
foreach ($caches as $name => $class) {
if ($this->canBeCleared($class)) {
$this->stdout("\t* $name ($class)\n", Console::FG_GREEN);
} else {
$this->stdout("\t* $name ($class) - can not be flushed via console\n", Console::FG_YELLOW);
}
}
$this->stdout("\n");
} | [
"private",
"function",
"notifyCachesCanBeCleared",
"(",
"$",
"caches",
")",
"{",
"$",
"this",
"->",
"stdout",
"(",
"\"The following caches were found in the system:\\n\\n\"",
",",
"Console",
"::",
"FG_YELLOW",
")",
";",
"foreach",
"(",
"$",
"caches",
"as",
"$",
"name",
"=>",
"$",
"class",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"canBeCleared",
"(",
"$",
"class",
")",
")",
"{",
"$",
"this",
"->",
"stdout",
"(",
"\"\\t* $name ($class)\\n\"",
",",
"Console",
"::",
"FG_GREEN",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"stdout",
"(",
"\"\\t* $name ($class) - can not be flushed via console\\n\"",
",",
"Console",
"::",
"FG_YELLOW",
")",
";",
"}",
"}",
"$",
"this",
"->",
"stdout",
"(",
"\"\\n\"",
")",
";",
"}"
] | Notifies user that given caches are found and can be flushed.
@param array $caches array of cache component classes | [
"Notifies",
"user",
"that",
"given",
"caches",
"are",
"found",
"and",
"can",
"be",
"flushed",
"."
] | train | https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Controllers/CacheController.php#L178-L191 |
yiisoft/yii-console | src/Controllers/CacheController.php | CacheController.confirmClear | private function confirmClear($cachesNames)
{
$this->stdout("The following cache components will be flushed:\n\n", Console::FG_YELLOW);
foreach ($cachesNames as $name) {
$this->stdout("\t* $name \n", Console::FG_GREEN);
}
return $this->confirm("\nFlush above cache components?");
} | php | private function confirmClear($cachesNames)
{
$this->stdout("The following cache components will be flushed:\n\n", Console::FG_YELLOW);
foreach ($cachesNames as $name) {
$this->stdout("\t* $name \n", Console::FG_GREEN);
}
return $this->confirm("\nFlush above cache components?");
} | [
"private",
"function",
"confirmClear",
"(",
"$",
"cachesNames",
")",
"{",
"$",
"this",
"->",
"stdout",
"(",
"\"The following cache components will be flushed:\\n\\n\"",
",",
"Console",
"::",
"FG_YELLOW",
")",
";",
"foreach",
"(",
"$",
"cachesNames",
"as",
"$",
"name",
")",
"{",
"$",
"this",
"->",
"stdout",
"(",
"\"\\t* $name \\n\"",
",",
"Console",
"::",
"FG_GREEN",
")",
";",
"}",
"return",
"$",
"this",
"->",
"confirm",
"(",
"\"\\nFlush above cache components?\"",
")",
";",
"}"
] | Prompts user with confirmation if caches should be cleared.
@param array $cachesNames
@return bool | [
"Prompts",
"user",
"with",
"confirmation",
"if",
"caches",
"should",
"be",
"cleared",
"."
] | train | https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Controllers/CacheController.php#L241-L250 |
yiisoft/yii-jquery | src/Validators/Client/CaptchaClientValidator.php | CaptchaClientValidator.getClientOptions | public function getClientOptions($validator, $model, $attribute)
{
$captcha = $validator->createCaptchaAction();
$code = $captcha->getVerifyCode(false);
$hash = $captcha->generateValidationHash($validator->caseSensitive ? $code : strtolower($code));
$options = [
'hash' => $hash,
'hashKey' => 'yiiCaptcha/' . $captcha->getUniqueId(),
'caseSensitive' => $validator->caseSensitive,
'message' => $validator->formatMessage($validator->message, [
'attribute' => $model->getAttributeLabel($attribute),
]),
];
if ($validator->skipOnEmpty) {
$options['skipOnEmpty'] = 1;
}
return $options;
} | php | public function getClientOptions($validator, $model, $attribute)
{
$captcha = $validator->createCaptchaAction();
$code = $captcha->getVerifyCode(false);
$hash = $captcha->generateValidationHash($validator->caseSensitive ? $code : strtolower($code));
$options = [
'hash' => $hash,
'hashKey' => 'yiiCaptcha/' . $captcha->getUniqueId(),
'caseSensitive' => $validator->caseSensitive,
'message' => $validator->formatMessage($validator->message, [
'attribute' => $model->getAttributeLabel($attribute),
]),
];
if ($validator->skipOnEmpty) {
$options['skipOnEmpty'] = 1;
}
return $options;
} | [
"public",
"function",
"getClientOptions",
"(",
"$",
"validator",
",",
"$",
"model",
",",
"$",
"attribute",
")",
"{",
"$",
"captcha",
"=",
"$",
"validator",
"->",
"createCaptchaAction",
"(",
")",
";",
"$",
"code",
"=",
"$",
"captcha",
"->",
"getVerifyCode",
"(",
"false",
")",
";",
"$",
"hash",
"=",
"$",
"captcha",
"->",
"generateValidationHash",
"(",
"$",
"validator",
"->",
"caseSensitive",
"?",
"$",
"code",
":",
"strtolower",
"(",
"$",
"code",
")",
")",
";",
"$",
"options",
"=",
"[",
"'hash'",
"=>",
"$",
"hash",
",",
"'hashKey'",
"=>",
"'yiiCaptcha/'",
".",
"$",
"captcha",
"->",
"getUniqueId",
"(",
")",
",",
"'caseSensitive'",
"=>",
"$",
"validator",
"->",
"caseSensitive",
",",
"'message'",
"=>",
"$",
"validator",
"->",
"formatMessage",
"(",
"$",
"validator",
"->",
"message",
",",
"[",
"'attribute'",
"=>",
"$",
"model",
"->",
"getAttributeLabel",
"(",
"$",
"attribute",
")",
",",
"]",
")",
",",
"]",
";",
"if",
"(",
"$",
"validator",
"->",
"skipOnEmpty",
")",
"{",
"$",
"options",
"[",
"'skipOnEmpty'",
"]",
"=",
"1",
";",
"}",
"return",
"$",
"options",
";",
"}"
] | Returns the client-side validation options.
@param \Yiisoft\Yii\Captcha\CaptchaValidator $validator the server-side validator.
@param \yii\base\Model $model the model being validated
@param string $attribute the attribute name being validated
@return array the client-side validation options | [
"Returns",
"the",
"client",
"-",
"side",
"validation",
"options",
"."
] | train | https://github.com/yiisoft/yii-jquery/blob/1c257928cba2b46d267e90771652abe2b0e2cfcb/src/Validators/Client/CaptchaClientValidator.php#L41-L59 |
yiisoft/yii-jquery | src/ActiveFormClientScript.php | ActiveFormClientScript.defaultClientValidatorMap | protected function defaultClientValidatorMap()
{
return [
\yii\validators\BooleanValidator::class => \Yiisoft\Yii\JQuery\Validators\Client\BooleanValidator::class,
\yii\validators\CompareValidator::class => \Yiisoft\Yii\JQuery\Validators\Client\CompareValidator::class,
\yii\validators\EmailValidator::class => \Yiisoft\Yii\JQuery\Validators\Client\EmailValidator::class,
\yii\validators\FilterValidator::class => \Yiisoft\Yii\JQuery\Validators\Client\FilterValidator::class,
\yii\validators\IpValidator::class => \Yiisoft\Yii\JQuery\Validators\Client\IpValidator::class,
\yii\validators\NumberValidator::class => \Yiisoft\Yii\JQuery\Validators\Client\NumberValidator::class,
\yii\validators\RangeValidator::class => \Yiisoft\Yii\JQuery\Validators\Client\RangeValidator::class,
\yii\validators\RegularExpressionValidator::class => \Yiisoft\Yii\JQuery\Validators\Client\RegularExpressionValidator::class,
\yii\validators\RequiredValidator::class => \Yiisoft\Yii\JQuery\Validators\Client\RequiredValidator::class,
\yii\validators\StringValidator::class => \Yiisoft\Yii\JQuery\Validators\Client\StringValidator::class,
\yii\validators\UrlValidator::class => \Yiisoft\Yii\JQuery\Validators\Client\UrlValidator::class,
\yii\validators\ImageValidator::class => \Yiisoft\Yii\JQuery\Validators\Client\ImageValidator::class,
\yii\validators\FileValidator::class => \Yiisoft\Yii\JQuery\Validators\Client\FileValidator::class,
\Yiisoft\Yii\Captcha\CaptchaValidator::class => \Yiisoft\Yii\JQuery\Validators\Client\CaptchaClientValidator::class,
];
} | php | protected function defaultClientValidatorMap()
{
return [
\yii\validators\BooleanValidator::class => \Yiisoft\Yii\JQuery\Validators\Client\BooleanValidator::class,
\yii\validators\CompareValidator::class => \Yiisoft\Yii\JQuery\Validators\Client\CompareValidator::class,
\yii\validators\EmailValidator::class => \Yiisoft\Yii\JQuery\Validators\Client\EmailValidator::class,
\yii\validators\FilterValidator::class => \Yiisoft\Yii\JQuery\Validators\Client\FilterValidator::class,
\yii\validators\IpValidator::class => \Yiisoft\Yii\JQuery\Validators\Client\IpValidator::class,
\yii\validators\NumberValidator::class => \Yiisoft\Yii\JQuery\Validators\Client\NumberValidator::class,
\yii\validators\RangeValidator::class => \Yiisoft\Yii\JQuery\Validators\Client\RangeValidator::class,
\yii\validators\RegularExpressionValidator::class => \Yiisoft\Yii\JQuery\Validators\Client\RegularExpressionValidator::class,
\yii\validators\RequiredValidator::class => \Yiisoft\Yii\JQuery\Validators\Client\RequiredValidator::class,
\yii\validators\StringValidator::class => \Yiisoft\Yii\JQuery\Validators\Client\StringValidator::class,
\yii\validators\UrlValidator::class => \Yiisoft\Yii\JQuery\Validators\Client\UrlValidator::class,
\yii\validators\ImageValidator::class => \Yiisoft\Yii\JQuery\Validators\Client\ImageValidator::class,
\yii\validators\FileValidator::class => \Yiisoft\Yii\JQuery\Validators\Client\FileValidator::class,
\Yiisoft\Yii\Captcha\CaptchaValidator::class => \Yiisoft\Yii\JQuery\Validators\Client\CaptchaClientValidator::class,
];
} | [
"protected",
"function",
"defaultClientValidatorMap",
"(",
")",
"{",
"return",
"[",
"\\",
"yii",
"\\",
"validators",
"\\",
"BooleanValidator",
"::",
"class",
"=>",
"\\",
"Yiisoft",
"\\",
"Yii",
"\\",
"JQuery",
"\\",
"Validators",
"\\",
"Client",
"\\",
"BooleanValidator",
"::",
"class",
",",
"\\",
"yii",
"\\",
"validators",
"\\",
"CompareValidator",
"::",
"class",
"=>",
"\\",
"Yiisoft",
"\\",
"Yii",
"\\",
"JQuery",
"\\",
"Validators",
"\\",
"Client",
"\\",
"CompareValidator",
"::",
"class",
",",
"\\",
"yii",
"\\",
"validators",
"\\",
"EmailValidator",
"::",
"class",
"=>",
"\\",
"Yiisoft",
"\\",
"Yii",
"\\",
"JQuery",
"\\",
"Validators",
"\\",
"Client",
"\\",
"EmailValidator",
"::",
"class",
",",
"\\",
"yii",
"\\",
"validators",
"\\",
"FilterValidator",
"::",
"class",
"=>",
"\\",
"Yiisoft",
"\\",
"Yii",
"\\",
"JQuery",
"\\",
"Validators",
"\\",
"Client",
"\\",
"FilterValidator",
"::",
"class",
",",
"\\",
"yii",
"\\",
"validators",
"\\",
"IpValidator",
"::",
"class",
"=>",
"\\",
"Yiisoft",
"\\",
"Yii",
"\\",
"JQuery",
"\\",
"Validators",
"\\",
"Client",
"\\",
"IpValidator",
"::",
"class",
",",
"\\",
"yii",
"\\",
"validators",
"\\",
"NumberValidator",
"::",
"class",
"=>",
"\\",
"Yiisoft",
"\\",
"Yii",
"\\",
"JQuery",
"\\",
"Validators",
"\\",
"Client",
"\\",
"NumberValidator",
"::",
"class",
",",
"\\",
"yii",
"\\",
"validators",
"\\",
"RangeValidator",
"::",
"class",
"=>",
"\\",
"Yiisoft",
"\\",
"Yii",
"\\",
"JQuery",
"\\",
"Validators",
"\\",
"Client",
"\\",
"RangeValidator",
"::",
"class",
",",
"\\",
"yii",
"\\",
"validators",
"\\",
"RegularExpressionValidator",
"::",
"class",
"=>",
"\\",
"Yiisoft",
"\\",
"Yii",
"\\",
"JQuery",
"\\",
"Validators",
"\\",
"Client",
"\\",
"RegularExpressionValidator",
"::",
"class",
",",
"\\",
"yii",
"\\",
"validators",
"\\",
"RequiredValidator",
"::",
"class",
"=>",
"\\",
"Yiisoft",
"\\",
"Yii",
"\\",
"JQuery",
"\\",
"Validators",
"\\",
"Client",
"\\",
"RequiredValidator",
"::",
"class",
",",
"\\",
"yii",
"\\",
"validators",
"\\",
"StringValidator",
"::",
"class",
"=>",
"\\",
"Yiisoft",
"\\",
"Yii",
"\\",
"JQuery",
"\\",
"Validators",
"\\",
"Client",
"\\",
"StringValidator",
"::",
"class",
",",
"\\",
"yii",
"\\",
"validators",
"\\",
"UrlValidator",
"::",
"class",
"=>",
"\\",
"Yiisoft",
"\\",
"Yii",
"\\",
"JQuery",
"\\",
"Validators",
"\\",
"Client",
"\\",
"UrlValidator",
"::",
"class",
",",
"\\",
"yii",
"\\",
"validators",
"\\",
"ImageValidator",
"::",
"class",
"=>",
"\\",
"Yiisoft",
"\\",
"Yii",
"\\",
"JQuery",
"\\",
"Validators",
"\\",
"Client",
"\\",
"ImageValidator",
"::",
"class",
",",
"\\",
"yii",
"\\",
"validators",
"\\",
"FileValidator",
"::",
"class",
"=>",
"\\",
"Yiisoft",
"\\",
"Yii",
"\\",
"JQuery",
"\\",
"Validators",
"\\",
"Client",
"\\",
"FileValidator",
"::",
"class",
",",
"\\",
"Yiisoft",
"\\",
"Yii",
"\\",
"Captcha",
"\\",
"CaptchaValidator",
"::",
"class",
"=>",
"\\",
"Yiisoft",
"\\",
"Yii",
"\\",
"JQuery",
"\\",
"Validators",
"\\",
"Client",
"\\",
"CaptchaClientValidator",
"::",
"class",
",",
"]",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii-jquery/blob/1c257928cba2b46d267e90771652abe2b0e2cfcb/src/ActiveFormClientScript.php#L41-L59 |
yiisoft/yii-jquery | src/ActiveFormClientScript.php | ActiveFormClientScript.getFieldClientOptions | protected function getFieldClientOptions($field)
{
$options = parent::getFieldClientOptions($field);
// only get the options that are different from the default ones (set in yii.activeForm.js)
return array_diff_assoc($options, [
'validateOnChange' => true,
'validateOnBlur' => true,
'validateOnType' => false,
'validationDelay' => 500,
'encodeError' => true,
'error' => '.help-block',
'updateAriaInvalid' => true,
]);
} | php | protected function getFieldClientOptions($field)
{
$options = parent::getFieldClientOptions($field);
// only get the options that are different from the default ones (set in yii.activeForm.js)
return array_diff_assoc($options, [
'validateOnChange' => true,
'validateOnBlur' => true,
'validateOnType' => false,
'validationDelay' => 500,
'encodeError' => true,
'error' => '.help-block',
'updateAriaInvalid' => true,
]);
} | [
"protected",
"function",
"getFieldClientOptions",
"(",
"$",
"field",
")",
"{",
"$",
"options",
"=",
"parent",
"::",
"getFieldClientOptions",
"(",
"$",
"field",
")",
";",
"// only get the options that are different from the default ones (set in yii.activeForm.js)",
"return",
"array_diff_assoc",
"(",
"$",
"options",
",",
"[",
"'validateOnChange'",
"=>",
"true",
",",
"'validateOnBlur'",
"=>",
"true",
",",
"'validateOnType'",
"=>",
"false",
",",
"'validationDelay'",
"=>",
"500",
",",
"'encodeError'",
"=>",
"true",
",",
"'error'",
"=>",
"'.help-block'",
",",
"'updateAriaInvalid'",
"=>",
"true",
",",
"]",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii-jquery/blob/1c257928cba2b46d267e90771652abe2b0e2cfcb/src/ActiveFormClientScript.php#L77-L91 |
yiisoft/yii-jquery | src/ActiveFormClientScript.php | ActiveFormClientScript.getClientOptions | protected function getClientOptions()
{
$options = parent::getClientOptions();
// only get the options that are different from the default ones (set in yii.activeForm.js)
return array_diff_assoc($options, [
'encodeErrorSummary' => true,
'errorSummary' => '.error-summary',
'validateOnSubmit' => true,
'errorCssClass' => 'has-error',
'successCssClass' => 'has-success',
'validatingCssClass' => 'validating',
'ajaxParam' => 'ajax',
'ajaxDataType' => 'json',
'scrollToError' => true,
'scrollToErrorOffset' => 0,
'validationStateOn' => ActiveForm::VALIDATION_STATE_ON_CONTAINER,
]);
} | php | protected function getClientOptions()
{
$options = parent::getClientOptions();
// only get the options that are different from the default ones (set in yii.activeForm.js)
return array_diff_assoc($options, [
'encodeErrorSummary' => true,
'errorSummary' => '.error-summary',
'validateOnSubmit' => true,
'errorCssClass' => 'has-error',
'successCssClass' => 'has-success',
'validatingCssClass' => 'validating',
'ajaxParam' => 'ajax',
'ajaxDataType' => 'json',
'scrollToError' => true,
'scrollToErrorOffset' => 0,
'validationStateOn' => ActiveForm::VALIDATION_STATE_ON_CONTAINER,
]);
} | [
"protected",
"function",
"getClientOptions",
"(",
")",
"{",
"$",
"options",
"=",
"parent",
"::",
"getClientOptions",
"(",
")",
";",
"// only get the options that are different from the default ones (set in yii.activeForm.js)",
"return",
"array_diff_assoc",
"(",
"$",
"options",
",",
"[",
"'encodeErrorSummary'",
"=>",
"true",
",",
"'errorSummary'",
"=>",
"'.error-summary'",
",",
"'validateOnSubmit'",
"=>",
"true",
",",
"'errorCssClass'",
"=>",
"'has-error'",
",",
"'successCssClass'",
"=>",
"'has-success'",
",",
"'validatingCssClass'",
"=>",
"'validating'",
",",
"'ajaxParam'",
"=>",
"'ajax'",
",",
"'ajaxDataType'",
"=>",
"'json'",
",",
"'scrollToError'",
"=>",
"true",
",",
"'scrollToErrorOffset'",
"=>",
"0",
",",
"'validationStateOn'",
"=>",
"ActiveForm",
"::",
"VALIDATION_STATE_ON_CONTAINER",
",",
"]",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii-jquery/blob/1c257928cba2b46d267e90771652abe2b0e2cfcb/src/ActiveFormClientScript.php#L96-L114 |
yiisoft/yii-jquery | src/Validators/Client/NumberValidator.php | NumberValidator.getClientOptions | public function getClientOptions($validator, $model, $attribute)
{
$label = $model->getAttributeLabel($attribute);
$options = [
'pattern' => new JsExpression($validator->integerOnly ? $validator->integerPattern : $validator->numberPattern),
'message' => $validator->formatMessage($validator->message, [
'attribute' => $label,
]),
];
if ($validator->min !== null) {
// ensure numeric value to make javascript comparison equal to PHP comparison
// https://github.com/yiisoft/yii2/issues/3118
$options['min'] = is_string($validator->min) ? (float) $validator->min : $validator->min;
$options['tooSmall'] = $validator->formatMessage($validator->tooSmall, [
'attribute' => $label,
'min' => $validator->min,
]);
}
if ($validator->max !== null) {
// ensure numeric value to make javascript comparison equal to PHP comparison
// https://github.com/yiisoft/yii2/issues/3118
$options['max'] = is_string($validator->max) ? (float) $validator->max : $validator->max;
$options['tooBig'] = $validator->formatMessage($validator->tooBig, [
'attribute' => $label,
'max' => $validator->max,
]);
}
if ($validator->skipOnEmpty) {
$options['skipOnEmpty'] = 1;
}
return $options;
} | php | public function getClientOptions($validator, $model, $attribute)
{
$label = $model->getAttributeLabel($attribute);
$options = [
'pattern' => new JsExpression($validator->integerOnly ? $validator->integerPattern : $validator->numberPattern),
'message' => $validator->formatMessage($validator->message, [
'attribute' => $label,
]),
];
if ($validator->min !== null) {
// ensure numeric value to make javascript comparison equal to PHP comparison
// https://github.com/yiisoft/yii2/issues/3118
$options['min'] = is_string($validator->min) ? (float) $validator->min : $validator->min;
$options['tooSmall'] = $validator->formatMessage($validator->tooSmall, [
'attribute' => $label,
'min' => $validator->min,
]);
}
if ($validator->max !== null) {
// ensure numeric value to make javascript comparison equal to PHP comparison
// https://github.com/yiisoft/yii2/issues/3118
$options['max'] = is_string($validator->max) ? (float) $validator->max : $validator->max;
$options['tooBig'] = $validator->formatMessage($validator->tooBig, [
'attribute' => $label,
'max' => $validator->max,
]);
}
if ($validator->skipOnEmpty) {
$options['skipOnEmpty'] = 1;
}
return $options;
} | [
"public",
"function",
"getClientOptions",
"(",
"$",
"validator",
",",
"$",
"model",
",",
"$",
"attribute",
")",
"{",
"$",
"label",
"=",
"$",
"model",
"->",
"getAttributeLabel",
"(",
"$",
"attribute",
")",
";",
"$",
"options",
"=",
"[",
"'pattern'",
"=>",
"new",
"JsExpression",
"(",
"$",
"validator",
"->",
"integerOnly",
"?",
"$",
"validator",
"->",
"integerPattern",
":",
"$",
"validator",
"->",
"numberPattern",
")",
",",
"'message'",
"=>",
"$",
"validator",
"->",
"formatMessage",
"(",
"$",
"validator",
"->",
"message",
",",
"[",
"'attribute'",
"=>",
"$",
"label",
",",
"]",
")",
",",
"]",
";",
"if",
"(",
"$",
"validator",
"->",
"min",
"!==",
"null",
")",
"{",
"// ensure numeric value to make javascript comparison equal to PHP comparison",
"// https://github.com/yiisoft/yii2/issues/3118",
"$",
"options",
"[",
"'min'",
"]",
"=",
"is_string",
"(",
"$",
"validator",
"->",
"min",
")",
"?",
"(",
"float",
")",
"$",
"validator",
"->",
"min",
":",
"$",
"validator",
"->",
"min",
";",
"$",
"options",
"[",
"'tooSmall'",
"]",
"=",
"$",
"validator",
"->",
"formatMessage",
"(",
"$",
"validator",
"->",
"tooSmall",
",",
"[",
"'attribute'",
"=>",
"$",
"label",
",",
"'min'",
"=>",
"$",
"validator",
"->",
"min",
",",
"]",
")",
";",
"}",
"if",
"(",
"$",
"validator",
"->",
"max",
"!==",
"null",
")",
"{",
"// ensure numeric value to make javascript comparison equal to PHP comparison",
"// https://github.com/yiisoft/yii2/issues/3118",
"$",
"options",
"[",
"'max'",
"]",
"=",
"is_string",
"(",
"$",
"validator",
"->",
"max",
")",
"?",
"(",
"float",
")",
"$",
"validator",
"->",
"max",
":",
"$",
"validator",
"->",
"max",
";",
"$",
"options",
"[",
"'tooBig'",
"]",
"=",
"$",
"validator",
"->",
"formatMessage",
"(",
"$",
"validator",
"->",
"tooBig",
",",
"[",
"'attribute'",
"=>",
"$",
"label",
",",
"'max'",
"=>",
"$",
"validator",
"->",
"max",
",",
"]",
")",
";",
"}",
"if",
"(",
"$",
"validator",
"->",
"skipOnEmpty",
")",
"{",
"$",
"options",
"[",
"'skipOnEmpty'",
"]",
"=",
"1",
";",
"}",
"return",
"$",
"options",
";",
"}"
] | Returns the client-side validation options.
@param \yii\validators\NumberValidator $validator the server-side validator.
@param \yii\base\Model $model the model being validated
@param string $attribute the attribute name being validated
@return array the client-side validation options | [
"Returns",
"the",
"client",
"-",
"side",
"validation",
"options",
"."
] | train | https://github.com/yiisoft/yii-jquery/blob/1c257928cba2b46d267e90771652abe2b0e2cfcb/src/Validators/Client/NumberValidator.php#L43-L77 |
yiisoft/yii-console | src/Controllers/ServeController.php | ServeController.actionIndex | public function actionIndex($address = 'localhost')
{
$documentRoot = $this->app->getAlias($this->docroot);
if (strpos($address, ':') === false) {
$address = $address . ':' . $this->port;
}
if (!is_dir($documentRoot)) {
$this->stdout("Document root \"$documentRoot\" does not exist.\n", Console::FG_RED);
return self::EXIT_CODE_NO_DOCUMENT_ROOT;
}
if ($this->isAddressTaken($address)) {
$this->stdout("http://$address is taken by another process.\n", Console::FG_RED);
return self::EXIT_CODE_ADDRESS_TAKEN_BY_ANOTHER_PROCESS;
}
if ($this->router !== null && !file_exists($this->router)) {
$this->stdout("Routing file \"$this->router\" does not exist.\n", Console::FG_RED);
return self::EXIT_CODE_NO_ROUTING_FILE;
}
$this->stdout("Server started on http://{$address}/\n");
$this->stdout("Document root is \"{$documentRoot}\"\n");
if ($this->router) {
$this->stdout("Routing file is \"$this->router\"\n");
}
$this->stdout("Quit the server with CTRL-C or COMMAND-C.\n");
passthru('"' . PHP_BINARY . '"' . " -S {$address} -t \"{$documentRoot}\" $this->router");
} | php | public function actionIndex($address = 'localhost')
{
$documentRoot = $this->app->getAlias($this->docroot);
if (strpos($address, ':') === false) {
$address = $address . ':' . $this->port;
}
if (!is_dir($documentRoot)) {
$this->stdout("Document root \"$documentRoot\" does not exist.\n", Console::FG_RED);
return self::EXIT_CODE_NO_DOCUMENT_ROOT;
}
if ($this->isAddressTaken($address)) {
$this->stdout("http://$address is taken by another process.\n", Console::FG_RED);
return self::EXIT_CODE_ADDRESS_TAKEN_BY_ANOTHER_PROCESS;
}
if ($this->router !== null && !file_exists($this->router)) {
$this->stdout("Routing file \"$this->router\" does not exist.\n", Console::FG_RED);
return self::EXIT_CODE_NO_ROUTING_FILE;
}
$this->stdout("Server started on http://{$address}/\n");
$this->stdout("Document root is \"{$documentRoot}\"\n");
if ($this->router) {
$this->stdout("Routing file is \"$this->router\"\n");
}
$this->stdout("Quit the server with CTRL-C or COMMAND-C.\n");
passthru('"' . PHP_BINARY . '"' . " -S {$address} -t \"{$documentRoot}\" $this->router");
} | [
"public",
"function",
"actionIndex",
"(",
"$",
"address",
"=",
"'localhost'",
")",
"{",
"$",
"documentRoot",
"=",
"$",
"this",
"->",
"app",
"->",
"getAlias",
"(",
"$",
"this",
"->",
"docroot",
")",
";",
"if",
"(",
"strpos",
"(",
"$",
"address",
",",
"':'",
")",
"===",
"false",
")",
"{",
"$",
"address",
"=",
"$",
"address",
".",
"':'",
".",
"$",
"this",
"->",
"port",
";",
"}",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"documentRoot",
")",
")",
"{",
"$",
"this",
"->",
"stdout",
"(",
"\"Document root \\\"$documentRoot\\\" does not exist.\\n\"",
",",
"Console",
"::",
"FG_RED",
")",
";",
"return",
"self",
"::",
"EXIT_CODE_NO_DOCUMENT_ROOT",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"isAddressTaken",
"(",
"$",
"address",
")",
")",
"{",
"$",
"this",
"->",
"stdout",
"(",
"\"http://$address is taken by another process.\\n\"",
",",
"Console",
"::",
"FG_RED",
")",
";",
"return",
"self",
"::",
"EXIT_CODE_ADDRESS_TAKEN_BY_ANOTHER_PROCESS",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"router",
"!==",
"null",
"&&",
"!",
"file_exists",
"(",
"$",
"this",
"->",
"router",
")",
")",
"{",
"$",
"this",
"->",
"stdout",
"(",
"\"Routing file \\\"$this->router\\\" does not exist.\\n\"",
",",
"Console",
"::",
"FG_RED",
")",
";",
"return",
"self",
"::",
"EXIT_CODE_NO_ROUTING_FILE",
";",
"}",
"$",
"this",
"->",
"stdout",
"(",
"\"Server started on http://{$address}/\\n\"",
")",
";",
"$",
"this",
"->",
"stdout",
"(",
"\"Document root is \\\"{$documentRoot}\\\"\\n\"",
")",
";",
"if",
"(",
"$",
"this",
"->",
"router",
")",
"{",
"$",
"this",
"->",
"stdout",
"(",
"\"Routing file is \\\"$this->router\\\"\\n\"",
")",
";",
"}",
"$",
"this",
"->",
"stdout",
"(",
"\"Quit the server with CTRL-C or COMMAND-C.\\n\"",
")",
";",
"passthru",
"(",
"'\"'",
".",
"PHP_BINARY",
".",
"'\"'",
".",
"\" -S {$address} -t \\\"{$documentRoot}\\\" $this->router\"",
")",
";",
"}"
] | Runs PHP built-in web server.
@param string $address address to serve on. Either "host" or "host:port".
@return int | [
"Runs",
"PHP",
"built",
"-",
"in",
"web",
"server",
"."
] | train | https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Controllers/ServeController.php#L51-L82 |
yiisoft/yii-jquery | src/Validators/Client/IpValidator.php | IpValidator.build | public function build($validator, $model, $attribute, $view)
{
ValidationAsset::register($view);
$options = $this->getClientOptions($validator, $model, $attribute);
return 'yii.validation.ip(value, messages, ' . Json::htmlEncode($options) . ');';
} | php | public function build($validator, $model, $attribute, $view)
{
ValidationAsset::register($view);
$options = $this->getClientOptions($validator, $model, $attribute);
return 'yii.validation.ip(value, messages, ' . Json::htmlEncode($options) . ');';
} | [
"public",
"function",
"build",
"(",
"$",
"validator",
",",
"$",
"model",
",",
"$",
"attribute",
",",
"$",
"view",
")",
"{",
"ValidationAsset",
"::",
"register",
"(",
"$",
"view",
")",
";",
"$",
"options",
"=",
"$",
"this",
"->",
"getClientOptions",
"(",
"$",
"validator",
",",
"$",
"model",
",",
"$",
"attribute",
")",
";",
"return",
"'yii.validation.ip(value, messages, '",
".",
"Json",
"::",
"htmlEncode",
"(",
"$",
"options",
")",
".",
"');'",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii-jquery/blob/1c257928cba2b46d267e90771652abe2b0e2cfcb/src/Validators/Client/IpValidator.php#L31-L36 |
yiisoft/yii-jquery | src/Validators/Client/IpValidator.php | IpValidator.getClientOptions | public function getClientOptions($validator, $model, $attribute)
{
$messages = [
'ipv6NotAllowed' => $validator->ipv6NotAllowed,
'ipv4NotAllowed' => $validator->ipv4NotAllowed,
'message' => $validator->message,
'noSubnet' => $validator->noSubnet,
'hasSubnet' => $validator->hasSubnet,
];
foreach ($messages as &$message) {
$message = $validator->formatMessage($message, [
'attribute' => $model->getAttributeLabel($attribute),
]);
}
$options = [
'ipv4Pattern' => new JsExpression(Html::escapeJsRegularExpression($validator->ipv4Pattern)),
'ipv6Pattern' => new JsExpression(Html::escapeJsRegularExpression($validator->ipv6Pattern)),
'messages' => $messages,
'ipv4' => (bool) $validator->ipv4,
'ipv6' => (bool) $validator->ipv6,
'ipParsePattern' => new JsExpression(Html::escapeJsRegularExpression($validator->getIpParsePattern())),
'negation' => $validator->negation,
'subnet' => $validator->subnet,
];
if ($validator->skipOnEmpty) {
$options['skipOnEmpty'] = 1;
}
return $options;
} | php | public function getClientOptions($validator, $model, $attribute)
{
$messages = [
'ipv6NotAllowed' => $validator->ipv6NotAllowed,
'ipv4NotAllowed' => $validator->ipv4NotAllowed,
'message' => $validator->message,
'noSubnet' => $validator->noSubnet,
'hasSubnet' => $validator->hasSubnet,
];
foreach ($messages as &$message) {
$message = $validator->formatMessage($message, [
'attribute' => $model->getAttributeLabel($attribute),
]);
}
$options = [
'ipv4Pattern' => new JsExpression(Html::escapeJsRegularExpression($validator->ipv4Pattern)),
'ipv6Pattern' => new JsExpression(Html::escapeJsRegularExpression($validator->ipv6Pattern)),
'messages' => $messages,
'ipv4' => (bool) $validator->ipv4,
'ipv6' => (bool) $validator->ipv6,
'ipParsePattern' => new JsExpression(Html::escapeJsRegularExpression($validator->getIpParsePattern())),
'negation' => $validator->negation,
'subnet' => $validator->subnet,
];
if ($validator->skipOnEmpty) {
$options['skipOnEmpty'] = 1;
}
return $options;
} | [
"public",
"function",
"getClientOptions",
"(",
"$",
"validator",
",",
"$",
"model",
",",
"$",
"attribute",
")",
"{",
"$",
"messages",
"=",
"[",
"'ipv6NotAllowed'",
"=>",
"$",
"validator",
"->",
"ipv6NotAllowed",
",",
"'ipv4NotAllowed'",
"=>",
"$",
"validator",
"->",
"ipv4NotAllowed",
",",
"'message'",
"=>",
"$",
"validator",
"->",
"message",
",",
"'noSubnet'",
"=>",
"$",
"validator",
"->",
"noSubnet",
",",
"'hasSubnet'",
"=>",
"$",
"validator",
"->",
"hasSubnet",
",",
"]",
";",
"foreach",
"(",
"$",
"messages",
"as",
"&",
"$",
"message",
")",
"{",
"$",
"message",
"=",
"$",
"validator",
"->",
"formatMessage",
"(",
"$",
"message",
",",
"[",
"'attribute'",
"=>",
"$",
"model",
"->",
"getAttributeLabel",
"(",
"$",
"attribute",
")",
",",
"]",
")",
";",
"}",
"$",
"options",
"=",
"[",
"'ipv4Pattern'",
"=>",
"new",
"JsExpression",
"(",
"Html",
"::",
"escapeJsRegularExpression",
"(",
"$",
"validator",
"->",
"ipv4Pattern",
")",
")",
",",
"'ipv6Pattern'",
"=>",
"new",
"JsExpression",
"(",
"Html",
"::",
"escapeJsRegularExpression",
"(",
"$",
"validator",
"->",
"ipv6Pattern",
")",
")",
",",
"'messages'",
"=>",
"$",
"messages",
",",
"'ipv4'",
"=>",
"(",
"bool",
")",
"$",
"validator",
"->",
"ipv4",
",",
"'ipv6'",
"=>",
"(",
"bool",
")",
"$",
"validator",
"->",
"ipv6",
",",
"'ipParsePattern'",
"=>",
"new",
"JsExpression",
"(",
"Html",
"::",
"escapeJsRegularExpression",
"(",
"$",
"validator",
"->",
"getIpParsePattern",
"(",
")",
")",
")",
",",
"'negation'",
"=>",
"$",
"validator",
"->",
"negation",
",",
"'subnet'",
"=>",
"$",
"validator",
"->",
"subnet",
",",
"]",
";",
"if",
"(",
"$",
"validator",
"->",
"skipOnEmpty",
")",
"{",
"$",
"options",
"[",
"'skipOnEmpty'",
"]",
"=",
"1",
";",
"}",
"return",
"$",
"options",
";",
"}"
] | Returns the client-side validation options.
@param \yii\validators\IpValidator $validator the server-side validator.
@param \yii\base\Model $model the model being validated
@param string $attribute the attribute name being validated
@return array the client-side validation options | [
"Returns",
"the",
"client",
"-",
"side",
"validation",
"options",
"."
] | train | https://github.com/yiisoft/yii-jquery/blob/1c257928cba2b46d267e90771652abe2b0e2cfcb/src/Validators/Client/IpValidator.php#L45-L75 |
yiisoft/yii-jquery | src/Validators/Client/RequiredValidator.php | RequiredValidator.getClientOptions | public function getClientOptions($validator, $model, $attribute)
{
$options = [];
if ($validator->requiredValue !== null) {
$options['message'] = $validator->formatMessage($validator->message, [
'requiredValue' => $validator->requiredValue,
]);
$options['requiredValue'] = $validator->requiredValue;
} else {
$options['message'] = $validator->message;
}
if ($validator->strict) {
$options['strict'] = 1;
}
$options['message'] = $validator->formatMessage($options['message'], [
'attribute' => $model->getAttributeLabel($attribute),
]);
return $options;
} | php | public function getClientOptions($validator, $model, $attribute)
{
$options = [];
if ($validator->requiredValue !== null) {
$options['message'] = $validator->formatMessage($validator->message, [
'requiredValue' => $validator->requiredValue,
]);
$options['requiredValue'] = $validator->requiredValue;
} else {
$options['message'] = $validator->message;
}
if ($validator->strict) {
$options['strict'] = 1;
}
$options['message'] = $validator->formatMessage($options['message'], [
'attribute' => $model->getAttributeLabel($attribute),
]);
return $options;
} | [
"public",
"function",
"getClientOptions",
"(",
"$",
"validator",
",",
"$",
"model",
",",
"$",
"attribute",
")",
"{",
"$",
"options",
"=",
"[",
"]",
";",
"if",
"(",
"$",
"validator",
"->",
"requiredValue",
"!==",
"null",
")",
"{",
"$",
"options",
"[",
"'message'",
"]",
"=",
"$",
"validator",
"->",
"formatMessage",
"(",
"$",
"validator",
"->",
"message",
",",
"[",
"'requiredValue'",
"=>",
"$",
"validator",
"->",
"requiredValue",
",",
"]",
")",
";",
"$",
"options",
"[",
"'requiredValue'",
"]",
"=",
"$",
"validator",
"->",
"requiredValue",
";",
"}",
"else",
"{",
"$",
"options",
"[",
"'message'",
"]",
"=",
"$",
"validator",
"->",
"message",
";",
"}",
"if",
"(",
"$",
"validator",
"->",
"strict",
")",
"{",
"$",
"options",
"[",
"'strict'",
"]",
"=",
"1",
";",
"}",
"$",
"options",
"[",
"'message'",
"]",
"=",
"$",
"validator",
"->",
"formatMessage",
"(",
"$",
"options",
"[",
"'message'",
"]",
",",
"[",
"'attribute'",
"=>",
"$",
"model",
"->",
"getAttributeLabel",
"(",
"$",
"attribute",
")",
",",
"]",
")",
";",
"return",
"$",
"options",
";",
"}"
] | Returns the client-side validation options.
@param \yii\validators\RequiredValidator $validator the server-side validator.
@param \yii\base\Model $model the model being validated
@param string $attribute the attribute name being validated
@return array the client-side validation options | [
"Returns",
"the",
"client",
"-",
"side",
"validation",
"options",
"."
] | train | https://github.com/yiisoft/yii-jquery/blob/1c257928cba2b46d267e90771652abe2b0e2cfcb/src/Validators/Client/RequiredValidator.php#L41-L61 |
yiisoft/yii-console | src/Controllers/AssetController.php | AssetController.getAssetManager | public function getAssetManager()
{
if (!is_object($this->_assetManager)) {
$options = $this->_assetManager;
if (empty($options['__class'])) {
$options['__class'] = AssetManager::class;
}
if (!isset($options['basePath'])) {
throw new Exception("Please specify 'basePath' for the 'assetManager' option.");
}
if (!isset($options['baseUrl'])) {
throw new Exception("Please specify 'baseUrl' for the 'assetManager' option.");
}
if (!isset($options['forceCopy'])) {
$options['forceCopy'] = true;
}
$this->_assetManager = $this->app->createObject($options);
}
return $this->_assetManager;
} | php | public function getAssetManager()
{
if (!is_object($this->_assetManager)) {
$options = $this->_assetManager;
if (empty($options['__class'])) {
$options['__class'] = AssetManager::class;
}
if (!isset($options['basePath'])) {
throw new Exception("Please specify 'basePath' for the 'assetManager' option.");
}
if (!isset($options['baseUrl'])) {
throw new Exception("Please specify 'baseUrl' for the 'assetManager' option.");
}
if (!isset($options['forceCopy'])) {
$options['forceCopy'] = true;
}
$this->_assetManager = $this->app->createObject($options);
}
return $this->_assetManager;
} | [
"public",
"function",
"getAssetManager",
"(",
")",
"{",
"if",
"(",
"!",
"is_object",
"(",
"$",
"this",
"->",
"_assetManager",
")",
")",
"{",
"$",
"options",
"=",
"$",
"this",
"->",
"_assetManager",
";",
"if",
"(",
"empty",
"(",
"$",
"options",
"[",
"'__class'",
"]",
")",
")",
"{",
"$",
"options",
"[",
"'__class'",
"]",
"=",
"AssetManager",
"::",
"class",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"options",
"[",
"'basePath'",
"]",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"Please specify 'basePath' for the 'assetManager' option.\"",
")",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"options",
"[",
"'baseUrl'",
"]",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"Please specify 'baseUrl' for the 'assetManager' option.\"",
")",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"options",
"[",
"'forceCopy'",
"]",
")",
")",
"{",
"$",
"options",
"[",
"'forceCopy'",
"]",
"=",
"true",
";",
"}",
"$",
"this",
"->",
"_assetManager",
"=",
"$",
"this",
"->",
"app",
"->",
"createObject",
"(",
"$",
"options",
")",
";",
"}",
"return",
"$",
"this",
"->",
"_assetManager",
";",
"}"
] | Returns the asset manager instance.
@throws Exception on invalid configuration.
@return AssetManager asset manager instance. | [
"Returns",
"the",
"asset",
"manager",
"instance",
"."
] | train | https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Controllers/AssetController.php#L145-L167 |
yiisoft/yii-console | src/Controllers/AssetController.php | AssetController.loadTargets | protected function loadTargets($targets, $bundles)
{
// build the dependency order of bundles
$registered = [];
foreach ($bundles as $name => $bundle) {
$this->registerBundle($bundles, $name, $registered);
}
$bundleOrders = array_combine(array_keys($registered), range(0, count($bundles) - 1));
// fill up the target which has empty 'depends'.
$referenced = [];
foreach ($targets as $name => $target) {
if (empty($target['depends'])) {
if (!isset($all)) {
$all = $name;
} else {
throw new Exception("Only one target can have empty 'depends' option. Found two now: $all, $name");
}
} else {
foreach ($target['depends'] as $bundle) {
if (!isset($referenced[$bundle])) {
$referenced[$bundle] = $name;
} else {
throw new Exception("Target '{$referenced[$bundle]}' and '$name' cannot contain the bundle '$bundle' at the same time.");
}
}
}
}
if (isset($all)) {
$targets[$all]['depends'] = array_diff(array_keys($registered), array_keys($referenced));
}
// adjust the 'depends' order for each target according to the dependency order of bundles
// create an AssetBundle object for each target
foreach ($targets as $name => $target) {
if (!isset($target['basePath'])) {
throw new Exception("Please specify 'basePath' for the '$name' target.");
}
if (!isset($target['baseUrl'])) {
throw new Exception("Please specify 'baseUrl' for the '$name' target.");
}
usort($target['depends'], function ($a, $b) use ($bundleOrders) {
if ($bundleOrders[$a] == $bundleOrders[$b]) {
return 0;
}
return $bundleOrders[$a] > $bundleOrders[$b] ? 1 : -1;
});
if (!isset($target['__class'])) {
$target['__class'] = $name;
}
$targets[$name] = $this->app->createObject($target);
}
return $targets;
} | php | protected function loadTargets($targets, $bundles)
{
// build the dependency order of bundles
$registered = [];
foreach ($bundles as $name => $bundle) {
$this->registerBundle($bundles, $name, $registered);
}
$bundleOrders = array_combine(array_keys($registered), range(0, count($bundles) - 1));
// fill up the target which has empty 'depends'.
$referenced = [];
foreach ($targets as $name => $target) {
if (empty($target['depends'])) {
if (!isset($all)) {
$all = $name;
} else {
throw new Exception("Only one target can have empty 'depends' option. Found two now: $all, $name");
}
} else {
foreach ($target['depends'] as $bundle) {
if (!isset($referenced[$bundle])) {
$referenced[$bundle] = $name;
} else {
throw new Exception("Target '{$referenced[$bundle]}' and '$name' cannot contain the bundle '$bundle' at the same time.");
}
}
}
}
if (isset($all)) {
$targets[$all]['depends'] = array_diff(array_keys($registered), array_keys($referenced));
}
// adjust the 'depends' order for each target according to the dependency order of bundles
// create an AssetBundle object for each target
foreach ($targets as $name => $target) {
if (!isset($target['basePath'])) {
throw new Exception("Please specify 'basePath' for the '$name' target.");
}
if (!isset($target['baseUrl'])) {
throw new Exception("Please specify 'baseUrl' for the '$name' target.");
}
usort($target['depends'], function ($a, $b) use ($bundleOrders) {
if ($bundleOrders[$a] == $bundleOrders[$b]) {
return 0;
}
return $bundleOrders[$a] > $bundleOrders[$b] ? 1 : -1;
});
if (!isset($target['__class'])) {
$target['__class'] = $name;
}
$targets[$name] = $this->app->createObject($target);
}
return $targets;
} | [
"protected",
"function",
"loadTargets",
"(",
"$",
"targets",
",",
"$",
"bundles",
")",
"{",
"// build the dependency order of bundles",
"$",
"registered",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"bundles",
"as",
"$",
"name",
"=>",
"$",
"bundle",
")",
"{",
"$",
"this",
"->",
"registerBundle",
"(",
"$",
"bundles",
",",
"$",
"name",
",",
"$",
"registered",
")",
";",
"}",
"$",
"bundleOrders",
"=",
"array_combine",
"(",
"array_keys",
"(",
"$",
"registered",
")",
",",
"range",
"(",
"0",
",",
"count",
"(",
"$",
"bundles",
")",
"-",
"1",
")",
")",
";",
"// fill up the target which has empty 'depends'.",
"$",
"referenced",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"targets",
"as",
"$",
"name",
"=>",
"$",
"target",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"target",
"[",
"'depends'",
"]",
")",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"all",
")",
")",
"{",
"$",
"all",
"=",
"$",
"name",
";",
"}",
"else",
"{",
"throw",
"new",
"Exception",
"(",
"\"Only one target can have empty 'depends' option. Found two now: $all, $name\"",
")",
";",
"}",
"}",
"else",
"{",
"foreach",
"(",
"$",
"target",
"[",
"'depends'",
"]",
"as",
"$",
"bundle",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"referenced",
"[",
"$",
"bundle",
"]",
")",
")",
"{",
"$",
"referenced",
"[",
"$",
"bundle",
"]",
"=",
"$",
"name",
";",
"}",
"else",
"{",
"throw",
"new",
"Exception",
"(",
"\"Target '{$referenced[$bundle]}' and '$name' cannot contain the bundle '$bundle' at the same time.\"",
")",
";",
"}",
"}",
"}",
"}",
"if",
"(",
"isset",
"(",
"$",
"all",
")",
")",
"{",
"$",
"targets",
"[",
"$",
"all",
"]",
"[",
"'depends'",
"]",
"=",
"array_diff",
"(",
"array_keys",
"(",
"$",
"registered",
")",
",",
"array_keys",
"(",
"$",
"referenced",
")",
")",
";",
"}",
"// adjust the 'depends' order for each target according to the dependency order of bundles",
"// create an AssetBundle object for each target",
"foreach",
"(",
"$",
"targets",
"as",
"$",
"name",
"=>",
"$",
"target",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"target",
"[",
"'basePath'",
"]",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"Please specify 'basePath' for the '$name' target.\"",
")",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"target",
"[",
"'baseUrl'",
"]",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"Please specify 'baseUrl' for the '$name' target.\"",
")",
";",
"}",
"usort",
"(",
"$",
"target",
"[",
"'depends'",
"]",
",",
"function",
"(",
"$",
"a",
",",
"$",
"b",
")",
"use",
"(",
"$",
"bundleOrders",
")",
"{",
"if",
"(",
"$",
"bundleOrders",
"[",
"$",
"a",
"]",
"==",
"$",
"bundleOrders",
"[",
"$",
"b",
"]",
")",
"{",
"return",
"0",
";",
"}",
"return",
"$",
"bundleOrders",
"[",
"$",
"a",
"]",
">",
"$",
"bundleOrders",
"[",
"$",
"b",
"]",
"?",
"1",
":",
"-",
"1",
";",
"}",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"target",
"[",
"'__class'",
"]",
")",
")",
"{",
"$",
"target",
"[",
"'__class'",
"]",
"=",
"$",
"name",
";",
"}",
"$",
"targets",
"[",
"$",
"name",
"]",
"=",
"$",
"this",
"->",
"app",
"->",
"createObject",
"(",
"$",
"target",
")",
";",
"}",
"return",
"$",
"targets",
";",
"}"
] | Creates full list of output asset bundles.
@param array $targets output asset bundles configuration.
@param \yii\web\AssetBundle[] $bundles list of source asset bundles.
@return \yii\web\AssetBundle[] list of output asset bundles.
@throws Exception on failure. | [
"Creates",
"full",
"list",
"of",
"output",
"asset",
"bundles",
"."
] | train | https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Controllers/AssetController.php#L282-L337 |
yiisoft/yii-console | src/Controllers/AssetController.php | AssetController.saveTargets | protected function saveTargets($targets, $bundleFile)
{
$array = [];
foreach ($targets as $name => $target) {
if (isset($this->targets[$name])) {
$array[$name] = array_merge($this->targets[$name], [
'__class' => get_class($target),
'sourcePath' => null,
'basePath' => $this->targets[$name]['basePath'],
'baseUrl' => $this->targets[$name]['baseUrl'],
'js' => $target->js,
'css' => $target->css,
'depends' => [],
]);
} else {
if ($this->isBundleExternal($target)) {
$array[$name] = $this->composeBundleConfig($target);
} else {
$array[$name] = [
'sourcePath' => null,
'js' => [],
'css' => [],
'depends' => $target->depends,
];
}
}
}
$array = VarDumper::export($array);
$version = date('Y-m-d H:i:s');
$bundleFileContent = <<<EOD
<?php
/**
* This file is generated by the "yii {$this->id}" command.
* DO NOT MODIFY THIS FILE DIRECTLY.
* @version {$version}
*/
return {$array};
EOD;
if (!file_put_contents($bundleFile, $bundleFileContent, LOCK_EX)) {
throw new Exception("Unable to write output bundle configuration at '{$bundleFile}'.");
}
$this->stdout("Output bundle configuration created at '{$bundleFile}'.\n", Console::FG_GREEN);
} | php | protected function saveTargets($targets, $bundleFile)
{
$array = [];
foreach ($targets as $name => $target) {
if (isset($this->targets[$name])) {
$array[$name] = array_merge($this->targets[$name], [
'__class' => get_class($target),
'sourcePath' => null,
'basePath' => $this->targets[$name]['basePath'],
'baseUrl' => $this->targets[$name]['baseUrl'],
'js' => $target->js,
'css' => $target->css,
'depends' => [],
]);
} else {
if ($this->isBundleExternal($target)) {
$array[$name] = $this->composeBundleConfig($target);
} else {
$array[$name] = [
'sourcePath' => null,
'js' => [],
'css' => [],
'depends' => $target->depends,
];
}
}
}
$array = VarDumper::export($array);
$version = date('Y-m-d H:i:s');
$bundleFileContent = <<<EOD
<?php
/**
* This file is generated by the "yii {$this->id}" command.
* DO NOT MODIFY THIS FILE DIRECTLY.
* @version {$version}
*/
return {$array};
EOD;
if (!file_put_contents($bundleFile, $bundleFileContent, LOCK_EX)) {
throw new Exception("Unable to write output bundle configuration at '{$bundleFile}'.");
}
$this->stdout("Output bundle configuration created at '{$bundleFile}'.\n", Console::FG_GREEN);
} | [
"protected",
"function",
"saveTargets",
"(",
"$",
"targets",
",",
"$",
"bundleFile",
")",
"{",
"$",
"array",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"targets",
"as",
"$",
"name",
"=>",
"$",
"target",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"targets",
"[",
"$",
"name",
"]",
")",
")",
"{",
"$",
"array",
"[",
"$",
"name",
"]",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"targets",
"[",
"$",
"name",
"]",
",",
"[",
"'__class'",
"=>",
"get_class",
"(",
"$",
"target",
")",
",",
"'sourcePath'",
"=>",
"null",
",",
"'basePath'",
"=>",
"$",
"this",
"->",
"targets",
"[",
"$",
"name",
"]",
"[",
"'basePath'",
"]",
",",
"'baseUrl'",
"=>",
"$",
"this",
"->",
"targets",
"[",
"$",
"name",
"]",
"[",
"'baseUrl'",
"]",
",",
"'js'",
"=>",
"$",
"target",
"->",
"js",
",",
"'css'",
"=>",
"$",
"target",
"->",
"css",
",",
"'depends'",
"=>",
"[",
"]",
",",
"]",
")",
";",
"}",
"else",
"{",
"if",
"(",
"$",
"this",
"->",
"isBundleExternal",
"(",
"$",
"target",
")",
")",
"{",
"$",
"array",
"[",
"$",
"name",
"]",
"=",
"$",
"this",
"->",
"composeBundleConfig",
"(",
"$",
"target",
")",
";",
"}",
"else",
"{",
"$",
"array",
"[",
"$",
"name",
"]",
"=",
"[",
"'sourcePath'",
"=>",
"null",
",",
"'js'",
"=>",
"[",
"]",
",",
"'css'",
"=>",
"[",
"]",
",",
"'depends'",
"=>",
"$",
"target",
"->",
"depends",
",",
"]",
";",
"}",
"}",
"}",
"$",
"array",
"=",
"VarDumper",
"::",
"export",
"(",
"$",
"array",
")",
";",
"$",
"version",
"=",
"date",
"(",
"'Y-m-d H:i:s'",
")",
";",
"$",
"bundleFileContent",
"=",
" <<<EOD\n<?php\n/**\n * This file is generated by the \"yii {$this->id}\" command.\n * DO NOT MODIFY THIS FILE DIRECTLY.\n * @version {$version}\n */\nreturn {$array};\nEOD",
";",
"if",
"(",
"!",
"file_put_contents",
"(",
"$",
"bundleFile",
",",
"$",
"bundleFileContent",
",",
"LOCK_EX",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"Unable to write output bundle configuration at '{$bundleFile}'.\"",
")",
";",
"}",
"$",
"this",
"->",
"stdout",
"(",
"\"Output bundle configuration created at '{$bundleFile}'.\\n\"",
",",
"Console",
"::",
"FG_GREEN",
")",
";",
"}"
] | Saves new asset bundles configuration.
@param \yii\web\AssetBundle[] $targets list of asset bundles to be saved.
@param string $bundleFile output file name.
@throws Exception on failure. | [
"Saves",
"new",
"asset",
"bundles",
"configuration",
"."
] | train | https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Controllers/AssetController.php#L460-L502 |
yiisoft/yii-console | src/Controllers/AssetController.php | AssetController.actionTemplate | public function actionTemplate($configFile)
{
$jsCompressor = VarDumper::export($this->jsCompressor);
$cssCompressor = VarDumper::export($this->cssCompressor);
$template = <<<EOD
<?php
/**
* Configuration file for the "yii asset" console command.
*/
// In the console environment, some path aliases may not exist. Please define these:
// \$this->app->setAlias('@webroot', __DIR__ . '/../web');
// \$this->app->setAlias('@web', '/');
return [
// Adjust command/callback for JavaScript files compressing:
'jsCompressor' => {$jsCompressor},
// Adjust command/callback for CSS files compressing:
'cssCompressor' => {$cssCompressor},
// Whether to delete asset source after compression:
'deleteSource' => false,
// The list of asset bundles to compress:
'bundles' => [
// 'app\assets\AppAsset',
// \yii\web\YiiAsset::class,
// \yii\web\JqueryAsset::class,
],
// Asset bundle for compression output:
'targets' => [
'all' => [
'__class' => \yii\web\AssetBundle::class,
'basePath' => '@webroot/assets',
'baseUrl' => '@web/assets',
'js' => 'js/all-{hash}.js',
'css' => 'css/all-{hash}.css',
],
],
// Asset manager configuration:
'assetManager' => [
//'basePath' => '@webroot/assets',
//'baseUrl' => '@web/assets',
],
];
EOD;
if (file_exists($configFile)) {
if (!$this->confirm("File '{$configFile}' already exists. Do you wish to overwrite it?")) {
return ExitCode::OK;
}
}
if (!file_put_contents($configFile, $template, LOCK_EX)) {
throw new Exception("Unable to write template file '{$configFile}'.");
}
$this->stdout("Configuration file template created at '{$configFile}'.\n\n", Console::FG_GREEN);
return ExitCode::OK;
} | php | public function actionTemplate($configFile)
{
$jsCompressor = VarDumper::export($this->jsCompressor);
$cssCompressor = VarDumper::export($this->cssCompressor);
$template = <<<EOD
<?php
/**
* Configuration file for the "yii asset" console command.
*/
// In the console environment, some path aliases may not exist. Please define these:
// \$this->app->setAlias('@webroot', __DIR__ . '/../web');
// \$this->app->setAlias('@web', '/');
return [
// Adjust command/callback for JavaScript files compressing:
'jsCompressor' => {$jsCompressor},
// Adjust command/callback for CSS files compressing:
'cssCompressor' => {$cssCompressor},
// Whether to delete asset source after compression:
'deleteSource' => false,
// The list of asset bundles to compress:
'bundles' => [
// 'app\assets\AppAsset',
// \yii\web\YiiAsset::class,
// \yii\web\JqueryAsset::class,
],
// Asset bundle for compression output:
'targets' => [
'all' => [
'__class' => \yii\web\AssetBundle::class,
'basePath' => '@webroot/assets',
'baseUrl' => '@web/assets',
'js' => 'js/all-{hash}.js',
'css' => 'css/all-{hash}.css',
],
],
// Asset manager configuration:
'assetManager' => [
//'basePath' => '@webroot/assets',
//'baseUrl' => '@web/assets',
],
];
EOD;
if (file_exists($configFile)) {
if (!$this->confirm("File '{$configFile}' already exists. Do you wish to overwrite it?")) {
return ExitCode::OK;
}
}
if (!file_put_contents($configFile, $template, LOCK_EX)) {
throw new Exception("Unable to write template file '{$configFile}'.");
}
$this->stdout("Configuration file template created at '{$configFile}'.\n\n", Console::FG_GREEN);
return ExitCode::OK;
} | [
"public",
"function",
"actionTemplate",
"(",
"$",
"configFile",
")",
"{",
"$",
"jsCompressor",
"=",
"VarDumper",
"::",
"export",
"(",
"$",
"this",
"->",
"jsCompressor",
")",
";",
"$",
"cssCompressor",
"=",
"VarDumper",
"::",
"export",
"(",
"$",
"this",
"->",
"cssCompressor",
")",
";",
"$",
"template",
"=",
" <<<EOD\n<?php\n/**\n * Configuration file for the \"yii asset\" console command.\n */\n\n// In the console environment, some path aliases may not exist. Please define these:\n// \\$this->app->setAlias('@webroot', __DIR__ . '/../web');\n// \\$this->app->setAlias('@web', '/');\n\nreturn [\n // Adjust command/callback for JavaScript files compressing:\n 'jsCompressor' => {$jsCompressor},\n // Adjust command/callback for CSS files compressing:\n 'cssCompressor' => {$cssCompressor},\n // Whether to delete asset source after compression:\n 'deleteSource' => false,\n // The list of asset bundles to compress:\n 'bundles' => [\n // 'app\\assets\\AppAsset',\n // \\yii\\web\\YiiAsset::class,\n // \\yii\\web\\JqueryAsset::class,\n ],\n // Asset bundle for compression output:\n 'targets' => [\n 'all' => [\n '__class' => \\yii\\web\\AssetBundle::class,\n 'basePath' => '@webroot/assets',\n 'baseUrl' => '@web/assets',\n 'js' => 'js/all-{hash}.js',\n 'css' => 'css/all-{hash}.css',\n ],\n ],\n // Asset manager configuration:\n 'assetManager' => [\n //'basePath' => '@webroot/assets',\n //'baseUrl' => '@web/assets',\n ],\n];\nEOD",
";",
"if",
"(",
"file_exists",
"(",
"$",
"configFile",
")",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"confirm",
"(",
"\"File '{$configFile}' already exists. Do you wish to overwrite it?\"",
")",
")",
"{",
"return",
"ExitCode",
"::",
"OK",
";",
"}",
"}",
"if",
"(",
"!",
"file_put_contents",
"(",
"$",
"configFile",
",",
"$",
"template",
",",
"LOCK_EX",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"Unable to write template file '{$configFile}'.\"",
")",
";",
"}",
"$",
"this",
"->",
"stdout",
"(",
"\"Configuration file template created at '{$configFile}'.\\n\\n\"",
",",
"Console",
"::",
"FG_GREEN",
")",
";",
"return",
"ExitCode",
"::",
"OK",
";",
"}"
] | Creates template of configuration file for [[actionCompress]].
@param string $configFile output file name.
@return int CLI exit code
@throws Exception on failure. | [
"Creates",
"template",
"of",
"configuration",
"file",
"for",
"[[",
"actionCompress",
"]]",
"."
] | train | https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Controllers/AssetController.php#L692-L748 |
yiisoft/yii-console | src/Controller.php | Controller.getActionOptionsHelp | public function getActionOptionsHelp($action)
{
$optionNames = $this->options($action->id);
if (empty($optionNames)) {
return [];
}
$class = new \ReflectionClass($this);
$options = [];
foreach ($class->getProperties() as $property) {
$name = $property->getName();
if (!in_array($name, $optionNames, true)) {
continue;
}
$defaultValue = $property->getValue($this);
$tags = $this->parseDocCommentTags($property);
// Display camelCase options in kebab-case
$name = InflectorHelper::camel2id($name, '-', true);
if (isset($tags['var']) || isset($tags['property'])) {
$doc = $tags['var'] ?? $tags['property'];
if (is_array($doc)) {
$doc = reset($doc);
}
if (preg_match('/^(\S+)(.*)/s', $doc, $matches)) {
$type = $matches[1];
$comment = $matches[2];
} else {
$type = null;
$comment = $doc;
}
$options[$name] = [
'type' => $type,
'default' => $defaultValue,
'comment' => $comment,
];
} else {
$options[$name] = [
'type' => null,
'default' => $defaultValue,
'comment' => '',
];
}
}
return $options;
} | php | public function getActionOptionsHelp($action)
{
$optionNames = $this->options($action->id);
if (empty($optionNames)) {
return [];
}
$class = new \ReflectionClass($this);
$options = [];
foreach ($class->getProperties() as $property) {
$name = $property->getName();
if (!in_array($name, $optionNames, true)) {
continue;
}
$defaultValue = $property->getValue($this);
$tags = $this->parseDocCommentTags($property);
// Display camelCase options in kebab-case
$name = InflectorHelper::camel2id($name, '-', true);
if (isset($tags['var']) || isset($tags['property'])) {
$doc = $tags['var'] ?? $tags['property'];
if (is_array($doc)) {
$doc = reset($doc);
}
if (preg_match('/^(\S+)(.*)/s', $doc, $matches)) {
$type = $matches[1];
$comment = $matches[2];
} else {
$type = null;
$comment = $doc;
}
$options[$name] = [
'type' => $type,
'default' => $defaultValue,
'comment' => $comment,
];
} else {
$options[$name] = [
'type' => null,
'default' => $defaultValue,
'comment' => '',
];
}
}
return $options;
} | [
"public",
"function",
"getActionOptionsHelp",
"(",
"$",
"action",
")",
"{",
"$",
"optionNames",
"=",
"$",
"this",
"->",
"options",
"(",
"$",
"action",
"->",
"id",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"optionNames",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"class",
"=",
"new",
"\\",
"ReflectionClass",
"(",
"$",
"this",
")",
";",
"$",
"options",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"class",
"->",
"getProperties",
"(",
")",
"as",
"$",
"property",
")",
"{",
"$",
"name",
"=",
"$",
"property",
"->",
"getName",
"(",
")",
";",
"if",
"(",
"!",
"in_array",
"(",
"$",
"name",
",",
"$",
"optionNames",
",",
"true",
")",
")",
"{",
"continue",
";",
"}",
"$",
"defaultValue",
"=",
"$",
"property",
"->",
"getValue",
"(",
"$",
"this",
")",
";",
"$",
"tags",
"=",
"$",
"this",
"->",
"parseDocCommentTags",
"(",
"$",
"property",
")",
";",
"// Display camelCase options in kebab-case",
"$",
"name",
"=",
"InflectorHelper",
"::",
"camel2id",
"(",
"$",
"name",
",",
"'-'",
",",
"true",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"tags",
"[",
"'var'",
"]",
")",
"||",
"isset",
"(",
"$",
"tags",
"[",
"'property'",
"]",
")",
")",
"{",
"$",
"doc",
"=",
"$",
"tags",
"[",
"'var'",
"]",
"??",
"$",
"tags",
"[",
"'property'",
"]",
";",
"if",
"(",
"is_array",
"(",
"$",
"doc",
")",
")",
"{",
"$",
"doc",
"=",
"reset",
"(",
"$",
"doc",
")",
";",
"}",
"if",
"(",
"preg_match",
"(",
"'/^(\\S+)(.*)/s'",
",",
"$",
"doc",
",",
"$",
"matches",
")",
")",
"{",
"$",
"type",
"=",
"$",
"matches",
"[",
"1",
"]",
";",
"$",
"comment",
"=",
"$",
"matches",
"[",
"2",
"]",
";",
"}",
"else",
"{",
"$",
"type",
"=",
"null",
";",
"$",
"comment",
"=",
"$",
"doc",
";",
"}",
"$",
"options",
"[",
"$",
"name",
"]",
"=",
"[",
"'type'",
"=>",
"$",
"type",
",",
"'default'",
"=>",
"$",
"defaultValue",
",",
"'comment'",
"=>",
"$",
"comment",
",",
"]",
";",
"}",
"else",
"{",
"$",
"options",
"[",
"$",
"name",
"]",
"=",
"[",
"'type'",
"=>",
"null",
",",
"'default'",
"=>",
"$",
"defaultValue",
",",
"'comment'",
"=>",
"''",
",",
"]",
";",
"}",
"}",
"return",
"$",
"options",
";",
"}"
] | Returns the help information for the options for the action.
The returned value should be an array. The keys are the option names, and the values are
the corresponding help information. Each value must be an array of the following structure:
- type: string, the PHP type of this argument.
- default: string, the default value of this argument
- comment: string, the comment of this argument
The default implementation will return the help information extracted from the doc-comment of
the properties corresponding to the action options.
@param Action $action
@return array the help information of the action options | [
"Returns",
"the",
"help",
"information",
"for",
"the",
"options",
"for",
"the",
"action",
"."
] | train | https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Controller.php#L535-L582 |
yiisoft/yii-jquery | src/Validators/Client/CompareValidator.php | CompareValidator.getClientOptions | public function getClientOptions($validator, $model, $attribute)
{
$options = [
'operator' => $validator->operator,
'type' => $validator->type,
];
if ($validator->compareValue !== null) {
$options['compareValue'] = $validator->compareValue;
$compareLabel = $compareValue = $compareValueOrAttribute = $validator->compareValue;
} else {
$compareAttribute = $validator->compareAttribute === null ? $attribute . '_repeat' : $validator->compareAttribute;
$compareValue = $model->getAttributeLabel($compareAttribute);
$options['compareAttribute'] = Html::getInputId($model, $compareAttribute);
$compareLabel = $compareValueOrAttribute = $model->getAttributeLabel($compareAttribute);
}
if ($validator->skipOnEmpty) {
$options['skipOnEmpty'] = 1;
}
$options['message'] = $validator->formatMessage($validator->message, [
'attribute' => $model->getAttributeLabel($attribute),
'compareAttribute' => $compareLabel,
'compareValue' => $compareValue,
'compareValueOrAttribute' => $compareValueOrAttribute,
]);
return $options;
} | php | public function getClientOptions($validator, $model, $attribute)
{
$options = [
'operator' => $validator->operator,
'type' => $validator->type,
];
if ($validator->compareValue !== null) {
$options['compareValue'] = $validator->compareValue;
$compareLabel = $compareValue = $compareValueOrAttribute = $validator->compareValue;
} else {
$compareAttribute = $validator->compareAttribute === null ? $attribute . '_repeat' : $validator->compareAttribute;
$compareValue = $model->getAttributeLabel($compareAttribute);
$options['compareAttribute'] = Html::getInputId($model, $compareAttribute);
$compareLabel = $compareValueOrAttribute = $model->getAttributeLabel($compareAttribute);
}
if ($validator->skipOnEmpty) {
$options['skipOnEmpty'] = 1;
}
$options['message'] = $validator->formatMessage($validator->message, [
'attribute' => $model->getAttributeLabel($attribute),
'compareAttribute' => $compareLabel,
'compareValue' => $compareValue,
'compareValueOrAttribute' => $compareValueOrAttribute,
]);
return $options;
} | [
"public",
"function",
"getClientOptions",
"(",
"$",
"validator",
",",
"$",
"model",
",",
"$",
"attribute",
")",
"{",
"$",
"options",
"=",
"[",
"'operator'",
"=>",
"$",
"validator",
"->",
"operator",
",",
"'type'",
"=>",
"$",
"validator",
"->",
"type",
",",
"]",
";",
"if",
"(",
"$",
"validator",
"->",
"compareValue",
"!==",
"null",
")",
"{",
"$",
"options",
"[",
"'compareValue'",
"]",
"=",
"$",
"validator",
"->",
"compareValue",
";",
"$",
"compareLabel",
"=",
"$",
"compareValue",
"=",
"$",
"compareValueOrAttribute",
"=",
"$",
"validator",
"->",
"compareValue",
";",
"}",
"else",
"{",
"$",
"compareAttribute",
"=",
"$",
"validator",
"->",
"compareAttribute",
"===",
"null",
"?",
"$",
"attribute",
".",
"'_repeat'",
":",
"$",
"validator",
"->",
"compareAttribute",
";",
"$",
"compareValue",
"=",
"$",
"model",
"->",
"getAttributeLabel",
"(",
"$",
"compareAttribute",
")",
";",
"$",
"options",
"[",
"'compareAttribute'",
"]",
"=",
"Html",
"::",
"getInputId",
"(",
"$",
"model",
",",
"$",
"compareAttribute",
")",
";",
"$",
"compareLabel",
"=",
"$",
"compareValueOrAttribute",
"=",
"$",
"model",
"->",
"getAttributeLabel",
"(",
"$",
"compareAttribute",
")",
";",
"}",
"if",
"(",
"$",
"validator",
"->",
"skipOnEmpty",
")",
"{",
"$",
"options",
"[",
"'skipOnEmpty'",
"]",
"=",
"1",
";",
"}",
"$",
"options",
"[",
"'message'",
"]",
"=",
"$",
"validator",
"->",
"formatMessage",
"(",
"$",
"validator",
"->",
"message",
",",
"[",
"'attribute'",
"=>",
"$",
"model",
"->",
"getAttributeLabel",
"(",
"$",
"attribute",
")",
",",
"'compareAttribute'",
"=>",
"$",
"compareLabel",
",",
"'compareValue'",
"=>",
"$",
"compareValue",
",",
"'compareValueOrAttribute'",
"=>",
"$",
"compareValueOrAttribute",
",",
"]",
")",
";",
"return",
"$",
"options",
";",
"}"
] | Returns the client-side validation options.
@param \yii\validators\CompareValidator $validator the server-side validator.
@param \yii\base\Model $model the model being validated
@param string $attribute the attribute name being validated
@return array the client-side validation options | [
"Returns",
"the",
"client",
"-",
"side",
"validation",
"options",
"."
] | train | https://github.com/yiisoft/yii-jquery/blob/1c257928cba2b46d267e90771652abe2b0e2cfcb/src/Validators/Client/CompareValidator.php#L42-L71 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.