/**
  * Initialize the saga. If an identifier is provided it will be used, otherwise a random UUID will be generated.
  * 
  * @param string $identifier
  */
 public function __construct($identifier = null)
 {
     $this->identifier = null === $identifier ? Uuid::uuid1()->toString() : $identifier;
     $this->associationValues = new AssociationValuesImpl();
     $this->inspector = new SagaMethodMessageHandlerInspector($this);
     $this->associationValues->add(new AssociationValue('sagaIdentifier', $this->identifier));
 }
Beispiel #2
0
 /**
  * 获取税务信息
  * @return mixed
  * @param Request $request
  * @author AndyLee <*****@*****.**>
  */
 public function getTaxList(Request $request)
 {
     $company = Company::find($request->session()->get('customer_id'));
     $start = new \DateTime($company->created_at);
     $end = new DateTime();
     $interval = DateInterval::createFromDateString('1 month');
     $period = new DatePeriod($start, $interval, $end);
     $card = [];
     foreach ($period as $dt) {
         $map = ['user_id' => $request->session()->get('company_id'), 'company_id' => $request->session()->get('customer_id'), 'flag' => $dt->format("Ym")];
         $tax = Tax::where($map)->first();
         if (empty($tax)) {
             $record = new Tax();
             $record->user_id = $request->session()->get('company_id');
             $record->company_id = $request->session()->get('customer_id');
             $record->operator_id = Auth::user()->id;
             $record->card_name = $dt->format("Ym") . '税务申报单';
             $record->finish_time = strtotime($dt->format('Y-m') . '-15');
             $record->uuid = Uuid::uuid1();
             $record->guoshui_status = 0;
             $record->dishui_status = 0;
             $record->flag = $dt->format("Ym");
             $record->save();
             $card[] = $record->toArray();
         } else {
             $card[] = $tax->toArray();
         }
     }
     $card = array_reverse($card);
     return view('customer.tax.index')->with('cards', $card);
 }
Beispiel #3
0
 /**
  * Generate ID
  * @return String
  */
 public function generateId($version = 4, $includeDash = false)
 {
     try {
         switch ($version) {
             case 1:
                 $uuid = Uuid::uuid1();
                 break;
             case 3:
                 $uuid = Uuid::uuid3(Uuid::NAMESPACE_DNS, php_uname('n'));
                 break;
             case 5:
                 $uuid = Uuid::uuid5(Uuid::NAMESPACE_DNS, php_uname('n'));
                 break;
             default:
                 $uuid = Uuid::uuid4();
                 break;
         }
         return $includeDash ? $uuid->toString() : str_replace('-', '', $uuid->toString());
     } catch (UnsatisfiedDependencyException $e) {
         // Some dependency was not met. Either the method cannot be called on a
         // 32-bit system, or it can, but it relies on Moontoast\Math to be present.
         echo 'Caught exception: ' . $e->getMessage() . "\n";
         exit;
     }
 }
Beispiel #4
0
function handlePost($app, $request)
{
    // Timestamp & reverse-timestamp
    $odt = new DateTime('now', new DateTimeZone("Europe/Amsterdam"));
    $timestamp = $odt->format("Y-m-d H:i");
    $rtimestamp = $odt->format("siHdmY");
    try {
        $uuid1 = Uuid::uuid1();
        // Make sure the media file was uploaded without error
        $file = $request->files->get('mediaFile');
        if (!$file instanceof UploadedFile || $file->getError()) {
            throw new \InvalidArgumentException('The file is not valid.');
        }
        $ofilename = $rtimestamp . '-' . $file->getFilename();
        // create a thumbnail
        $image = $app['imagine']->open($file->getPathname());
        $tfilename = $rtimestamp . '-' . $file->getFilename() . '-thumb.jpeg';
        $tfilepath = $file->getPath() . '/' . $tfilename;
        $image->resize(new Box(200, 200))->save($tfilepath);
        // Upload the original media file to S3
        $ores = $app['aws.s3']->upload($app['env.orig'], $ofilename, fopen($file->getPathname(), 'r'), 'public-read');
        // upload the thumbnail
        $tres = $app['aws.s3']->upload($app['env.trans'], $tfilename, fopen($tfilepath, 'r'), 'public-read');
        // add file metadata
        $dynamoDbResult = $app['aws.ddb']->putItem(['TableName' => $app['env.table'], 'Item' => ['owner' => ['S' => 'PHP-User'], 'uid' => ['S' => $uuid1->toString()], 'timestamp' => ['S' => $timestamp], 'description' => ['S' => (string) $request->request->get('caption')], 'name' => ['S' => $file->getClientOriginalName()], 'source' => ['S' => $ofilename], 'thumbnail' => ['S' => $tfilename]]]);
        return array('type' => 'success', 'message' => 'File uploaded.');
    } catch (Exception $e) {
        // @TODO if something fails, rollback any object uploads
        return array('type' => 'error', 'message' => "Error uploading your photo:" . $e);
    }
}
 /**
  * @expectedException \OutOfBoundsException
  */
 public function testNextReadBeyondEnd()
 {
     $event1 = new GenericDomainEventMessage(Uuid::uuid1(), 0, new \stdClass(), new MetaData());
     $testSubject = new SimpleDomainEventStream(array($event1));
     $testSubject->next();
     $testSubject->next();
 }
 /**
  * Performs a new transaction.
  *
  * @param Cielo $cielo
  *
  * @return stdClass
  */
 public function performTransaction(Cielo $cielo)
 {
     $headers = ['MerchantId' => $cielo->getMerchantId(), 'MerchantKey' => $cielo->getMerchantKey(), 'RequestId' => $this->requestId];
     $json = ['MerchantOrderId' => Uuid::uuid1(), 'Customer' => $cielo->getCustomer()->toArray(), 'Payment' => $cielo->getPaymentMethod()->toArray()];
     $res = $this->perform->post('/1/sales', compact('headers', 'json'));
     return json_decode($res->getBody()->getContents());
 }
 /**
  * Creates the requested UUID
  *
  * @param int $version
  * @param string $namespace
  * @param string $name
  * @return Uuid
  */
 protected function createUuid($version, $namespace = null, $name = null)
 {
     switch ((int) $version) {
         case 1:
             $uuid = Uuid::uuid1();
             break;
         case 4:
             $uuid = Uuid::uuid4();
             break;
         case 3:
         case 5:
             $ns = $this->validateNamespace($namespace);
             if (empty($name)) {
                 throw new Exception('The name argument is required for version 3 or 5 UUIDs');
             }
             if ($version == 3) {
                 $uuid = Uuid::uuid3($ns, $name);
             } else {
                 $uuid = Uuid::uuid5($ns, $name);
             }
             break;
         default:
             throw new Exception('Invalid UUID version. Supported are version "1", "3", "4", and "5".');
     }
     return $uuid;
 }
Beispiel #8
0
 /**
  * Boot the Uuid trait for the model.
  *
  * @return void
  */
 public static function bootUuidForKey()
 {
     static::creating(function ($model) {
         $model->incrementing = false;
         $model->{$model->getKeyName()} = (string) Uuid::uuid1();
     });
 }
 /**
  * @param mixed $payload
  * @param MetaData $metaData
  * @param string|null $id
  * @param string|null $commandName
  */
 public function __construct($payload, MetaData $metaData = null, $id = null, $commandName = null)
 {
     $this->id = null === $id ? Uuid::uuid1()->toString() : $id;
     $this->commandName = null === $commandName ? get_class($payload) : $commandName;
     $this->payload = $payload;
     $this->metaData = null === $metaData ? MetaData::emptyInstance() : $metaData;
 }
 /**
  * @param ExportEventInterface $event
  * @throws CloseArchiveException
  * @throws OpenArchiveException
  * @throws UnavailableArchiveException
  */
 public function onCreateArchive(ExportEventInterface $event)
 {
     $archiveName = (string) Uuid::uuid1();
     $projectRootDir = realpath($this->projectRootDir);
     $archivePath = realpath($this->archiveDir) . '/' . $archiveName . '.zip';
     $archive = $this->openArchive($archivePath);
     foreach ($this->exportedCollection as $exportable) {
         if ($exportable instanceof ExportableInterface) {
             $exportPath = $projectRootDir . '/' . $exportable->getExportDestination();
             if (file_exists($exportPath)) {
                 $exportFile = new \SplFileObject($exportPath);
                 $archive->addFile($exportPath, $exportFile->getFilename());
             } else {
                 $this->logger->error(sprintf('Could not find export at "%s"', $exportPath));
                 // TODO Emit ErrorEvent to be handled later on for more robustness
                 continue;
             }
         }
     }
     $this->closeArchive($archive, $archivePath);
     if ($event instanceof JobAwareEventInterface) {
         if (!file_exists($archivePath)) {
             throw new UnavailableArchiveException(sprintf('Could not find archive at "%s"', $archivePath), UnavailableArchiveException::DEFAULT_CODE);
         }
         /** @var \WeavingTheWeb\Bundle\ApiBundle\Entity\Job $job */
         $job = $event->getJob();
         $archiveFile = new \SplFileObject($archivePath);
         $filename = str_replace('.zip', '', $archiveFile->getFilename());
         $router = $this->router;
         $getArchiveUrl = $this->router->generate('weaving_the_web_api_get_archive', ['filename' => $filename], $router::ABSOLUTE_PATH);
         $job->setOutput($getArchiveUrl);
     }
     $this->exportedCollection = [];
 }
Beispiel #11
0
 /**
  * generates a unique transaction ref used for init-ing transactions.
  *
  * @return mixed|null
  */
 public static function generateTransactionRef()
 {
     try {
         return str_replace('-', '', Uuid::uuid1()->toString());
     } catch (UnsatisfiedDependencyException $e) {
         return null;
     }
 }
 public function testRegisterCallbackInvokedWithAllRegisteredEvents()
 {
     $container = new EventContainer(Uuid::uuid1()->toString());
     $container->addEvent(MetaData::emptyInstance(), new Event());
     $this->assertFalse(current($container->getEventList())->getMetaData()->has("key"));
     $container->addEventRegistrationCallback(new TestEventRegistrationCallback());
     $this->assertEquals("value", current($container->getEventList())->getMetadata()->get("key"));
 }
 public function testResolveTarget_WithAnnotatedFields()
 {
     $aggregateIdentifier = Uuid::uuid1();
     $version = 1;
     $actual = $this->testSubject->resolveTarget(GenericCommandMessage::asCommandMessage(new FieldAnnotatedCommand($aggregateIdentifier, $version)));
     $this->assertEquals($aggregateIdentifier, $actual->getIdentifier());
     $this->assertEquals($version, $actual->getVersion());
 }
 /**
  * @param null|string $uuid
  *
  * @return $this
  */
 public function setUuid($uuid = null)
 {
     try {
         $this->uuid = $uuid instanceof Uuid ? $uuid : Uuid::fromString($uuid);
     } catch (\InvalidArgumentException $e) {
         $this->uuid = Uuid::uuid1();
     }
     return $this;
 }
 /**
  * @param mixed $payload
  * @param MetaData $metadata
  * @param string $id
  */
 public function __construct($payload, MetaData $metadata = null, $id = null)
 {
     if (!is_object($payload)) {
         throw new \InvalidArgumentException("Payload needs to be an object.");
     }
     $this->id = isset($id) ? $id : Uuid::uuid1()->toString();
     $this->metadata = isset($metadata) ? $metadata : MetaData::emptyInstance();
     $this->payload = $payload;
 }
 public function testLoadAggregate_NotFound()
 {
     $aggregateIdentifier = Uuid::uuid1()->toString();
     try {
         $this->testSubject->load($aggregateIdentifier);
         $this->fail("Expected AggregateNotFoundException");
     } catch (AggregateNotFoundException $ex) {
         $this->assertEquals($aggregateIdentifier, $ex->getAggregateId());
     }
 }
 public function testCommandReply()
 {
     $commandId1 = Uuid::uuid1()->toString();
     $commandId2 = Uuid::uuid1()->toString();
     $this->testSubject->writeCommandReply($commandId1, $commandId1);
     $data = $this->testSubject->readCommandReply($commandId1);
     $this->assertEquals($commandId1, $data[1]);
     $data = $this->testSubject->readCommandReply($commandId2, 1);
     $this->assertNull($data);
 }
Beispiel #18
0
 public function __construct($directory, $filename, $mimeType, FileCreator $fileCreator)
 {
     $this->id = Uuid::uuid1();
     $this->directory = $directory;
     $this->filename = $filename;
     $this->mimeType = $mimeType;
     $this->fileCreator = $fileCreator;
     $this->createdAt = new DateTime();
     $this->updatedAt = new DateTime();
 }
Beispiel #19
0
 /**
  * UUID v1 generator.
  *
  * @since 150424 Initial release.
  *
  * @param bool $optimize Optimize?
  *
  * @return string Version 1 UUID (32 bytes optimized).
  *                Or 36 bytes unoptimized; i.e., w/ dashes.
  */
 public function v1(bool $optimize = true) : string
 {
     $uuid = UuidGen::uuid1()->toString();
     if ($optimize) {
         // See: <http://jas.xyz/1ODZilT>
         $uuid = substr($uuid, 14, 4) . substr($uuid, 9, 4) . substr($uuid, 0, 8) . substr($uuid, 19, 4) . substr($uuid, 24);
     }
     return $uuid;
     // Possibly optimized now.
 }
 public function testLockFailsOnConcurrentModification()
 {
     $identifier = Uuid::uuid1()->toString();
     $aggregate1 = new StubAggregate($identifier);
     $aggregate2 = new StubAggregate($identifier);
     $manager = new OptimisticLockManager();
     $manager->obtainLock($aggregate1->getIdentifier());
     $manager->obtainLock($aggregate2->getIdentifier());
     $aggregate1->doSomething();
     $aggregate2->doSomething();
     $this->assertTrue($manager->validateLock($aggregate1));
     $this->assertFalse($manager->validateLock($aggregate2));
 }
Beispiel #21
0
 /**
  * Stock constructor.
  */
 public function __construct(Path $path)
 {
     /**
      * @TODO: sprawdzić czy uuid'y są jeszcze potrzebne!
      */
     $this->setUniqId(Uuid::uuid1());
     $this->setHash(Uuid::uuid1());
     $this->setPath($path->getPath());
     /**
      * @TODO: mkdir? Po co?
      */
     //        mkdir($this->getPath());
 }
 public function testFixtureApi_WhenEventIsPublishedToEventBus()
 {
     $aggregate1 = Uuid::uuid1()->toString();
     $aggregate2 = Uuid::uuid1()->toString();
     $fixture = new AnnotatedSagaTestFixture(StubSaga::class);
     $validator = $fixture->givenAggregate($aggregate1)->published(array(new TriggerSagaStartEvent($aggregate1), new TriggerExistingSagaEvent($aggregate1)))->whenAggregate($aggregate1)->publishes(new TriggerExistingSagaEvent($aggregate1));
     $validator->expectActiveSagas(1);
     $validator->expectAssociationWith("identifier", $aggregate1);
     $validator->expectNoAssociationWith("identifier", $aggregate2);
     //validator.expectScheduledEventMatching(Duration.standardMinutes(10),
     // Matchers.messageWithPayload(CoreMatchers.any(Object.class)));
     $validator->expectDispatchedCommandsEqualTo(array());
     $validator->expectPublishedEventsMatching(Matchers::listWithAnyOf(array(Matchers::messageWithPayload(CoreMatchers::any(SagaWasTriggeredEvent::class)))));
 }
 /**
 * Lorem ipsum.
 *
 * @param string $param1
 * @param bool   $param2 lorem ipsum
 * @param  string $param3 lorem ipsum
 *
 * @return int lorem ipsum
 */
 public function saveRevision(BaseCollection $old_data, $new_data = null, $options = [])
 {
     $table = $this->getRevisionsTableName();
     $entity = $this->collectionToRevisionEntity($old_data);
     $data = $entity->getData();
     $data = $this->filterFields($data);
     $uuid1 = Uuid::uuid1();
     $data['rev_id'] = $uuid1->toString();
     $data['rev_hash'] = $entity->hash();
     $data['rev_date'] = Date::now()->toSql();
     $data['rev_author'] = $this->user->getFullName();
     $status = $this->db->insert($table, $data);
     return $status;
 }
Beispiel #24
0
 /**
  * @covers ::__construct
  */
 public function testConstructWithId()
 {
     /**
      * @var Entity $entityMock
      */
     $entityMock = $this->getMockBuilder(Entity::class)->disableOriginalConstructor()->getMockForAbstractClass();
     $id = Uuid::uuid1()->toString();
     $modified = new \DateTime();
     $created = new \DateTime();
     $constructor = (new \ReflectionClass(Entity::class))->getConstructor();
     $constructor->invoke($entityMock, $id, $modified, $created);
     $this->assertSame($id, $entityMock->get('id'));
     $this->assertSame($modified, $entityMock->get('modified'));
     $this->assertSame($created, $entityMock->get('created'));
 }
 /**
  * @see \Omnipay\Common\Message\AbstractRequest::initialize()
  */
 public function initialize(array $parameters = array())
 {
     parent::initialize($parameters);
     if (!$this->getTransactionReference()) {
         /**
          * Generate the `orderID` string that we'll attempt to create/purchase
          *
          * That is to say, `orderID` generation happens here (not on the API server).
          * We should be careful not to generate duplicates. Especially since values cannot be reused.
          * (creating and deleting an order leaves a permanent trace on the server and makes said orderID non-reusable).
          */
         $this->setTransactionReference((string) \Ramsey\Uuid\Uuid::uuid1());
     }
     return $this;
 }
 public function testStreamDomainEventMessage()
 {
     $serializer = new JMSSerializer();
     $writer = new EventMessageWriter($serializer);
     $payload = new StreamPayload("string", 10, 15.5);
     $message = new GenericDomainEventMessage(Uuid::uuid1(), 1, $payload, new MetaData(array("metaKey" => "MetaValue")));
     $data = $writer->writeEventMessage($message);
     $reader = new EventMessageReader($serializer);
     $serializedMessage = $reader->readEventMessage($data);
     $this->assertTrue($serializedMessage instanceof DomainEventMessageInterface);
     $this->assertEquals($message->getIdentifier(), $serializedMessage->getIdentifier());
     $this->assertEquals($message->getPayloadType(), $serializedMessage->getPayloadType());
     $this->assertEquals($message->getTimestamp(), $serializedMessage->getTimestamp());
     $this->assertEquals($message->getMetaData(), $serializedMessage->getMetaData());
     $this->assertEquals($message->getPayload(), $serializedMessage->getPayload());
     $this->assertEquals($message->getAggregateIdentifier(), $serializedMessage->getAggregateIdentifier());
     $this->assertEquals($message->getScn(), $serializedMessage->getScn());
 }
 /**
  * Bootstrap any application services.
  *
  * @return void
  */
 public function boot()
 {
     Queue::failing(function (JobFailed $event) {
         Log::error('Error with Queue');
     });
     User::creating(function ($user) {
         return $user->token = str_random(12);
     });
     Board::creating(function ($board) {
         try {
             $uuid = Uuid::uuid1()->toString();
             $board->identifier = $uuid;
         } catch (UnsatisfiedDependencyException $e) {
             Log::error('UUID creation error => ' . $e);
             return response()->json('Error creating board', 500);
         }
     });
 }
 public function testAccessors()
 {
     $this->assertNull(self::$entityInitEnabled->getUuid());
     $this->assertFalse(self::$entityInitEnabled->hasUuid());
     $uuid = Uuid::uuid1();
     self::$entityInitEnabled->setUuid($uuid);
     $this->assertSame($uuid, self::$entityInitEnabled->getUuid());
     $this->assertTrue(self::$entityInitEnabled->hasUuid());
     self::$entityInitEnabled->clearUuid();
     $this->assertNull(self::$entityInitEnabled->getUuid());
     $this->assertFalse(self::$entityInitEnabled->hasUuid());
     $uuidString = Uuid::uuid1()->toString();
     self::$entityInitEnabled->setUuid($uuidString);
     $this->assertEquals($uuidString, self::$entityInitEnabled->getUuidString());
     $this->assertEquals(Uuid::fromString($uuidString), self::$entityInitEnabled->getUuid());
     $this->assertEquals(Uuid::fromString($uuidString)->getBytes(), self::$entityInitEnabled->getUuidBytes());
     $this->assertTrue(self::$entityInitEnabled->hasUuid());
     self::$entityInitEnabled->clearUuid();
     $this->assertNull(self::$entityInitEnabled->getUuid());
     $this->assertFalse(self::$entityInitEnabled->hasUuid());
     $uuidString = 'abcdefghijklmnopqrstuvwxyz0123456789';
     self::$entityInitEnabled->setUuid($uuidString);
     $this->assertNotEquals($uuidString, self::$entityInitEnabled->getUuidString());
 }
 public function __construct(ClientInterface $httpClient, HttpRequest $httpRequest)
 {
     parent::__construct($httpClient, $httpRequest);
     $this->generatedCardReference = (string) \Ramsey\Uuid\Uuid::uuid1();
 }
Beispiel #30
0
 /**
  * @see \Ramsey\Uuid\Uuid::uuid1()
  *
  * @param int|string $node
  * @param int $clockSeq
  * @return \Ramsey\Uuid\UuidInterface
  */
 public function uuid1($node = null, $clockSeq = null)
 {
     return \Ramsey\Uuid\Uuid::uuid1($node, $clockSeq);
 }