Example #1
0
 public function getLocale()
 {
     if (!$this->locale instanceof Locale) {
         $this->locale = Locale::parse($this->locale);
     }
     return $this->locale;
 }
 /**
  * @param string $locale The locale identifier.
  *
  * @return \Openl10n\Domain\Project\Model\Language
  *
  * @throws NotFoundHttpException If the entity is not found
  */
 protected function findLanguageOr404(Project $project, $locale)
 {
     $language = $this->get('openl10n.repository.language')->findOneByProject($project, Locale::parse($locale));
     if (null === $language) {
         throw $this->createNotFoundException(sprintf('Project "%s" has no locale "%s"', $project->getSlug(), $locale));
     }
     return $language;
 }
Example #3
0
 public function __construct(Slug $slug)
 {
     $this->slug = $slug;
     // Default attributes
     $this->name = new Name((string) $slug);
     $this->defaultLocale = Locale::parse(self::DEFAULT_LOCALE);
     $this->languages = new ArrayCollection();
 }
 function it_should_create_language(LanguageRepository $languageRepository, EventDispatcherInterface $eventDispatcher, Project $project, Language $language, CreateLanguageAction $action)
 {
     $action->getProject()->willReturn($project);
     $action->getLocale()->willReturn('fr_FR');
     $languageRepository->createNew($project, Argument::exact(Locale::parse('fr_FR')))->willReturn($language);
     $languageRepository->save($language)->shouldBeCalled();
     $this->execute($action)->shouldReturn($language);
 }
 public function execute(CreateLanguageAction $action)
 {
     $project = $action->getProject();
     $locale = Locale::parse($action->getLocale());
     $language = $this->languageRepository->createNew($project, $locale);
     $this->languageRepository->save($language);
     return $language;
 }
 /**
  * Construct with a list of locales.
  *
  * @param array $locales List of Locale objects
  */
 public function __construct(array $locales = array())
 {
     $this->locales = array_map(function ($locale) {
         if ($locale instanceof Locale) {
             return $locale;
         }
         return Locale::parse($locale);
     }, $locales);
 }
 function it_can_edit_user_profile(UserRepository $userRepository, EventDispatcherInterface $eventDispatcher, User $user, EditProfileAction $action)
 {
     $action->getUser()->willReturn($user);
     $action->getDisplayName()->willReturn('John Doe');
     $action->getPreferredLocale()->willReturn('fr_FR');
     $action->getEmail()->willReturn('*****@*****.**');
     $user->setName(Argument::exact(new Name('John Doe')))->willReturn($user)->shouldBeCalled();
     $user->setEmail(Argument::exact(new Email('*****@*****.**')))->willReturn($user)->shouldBeCalled();
     $user->setPreferredLocale(Argument::exact(Locale::parse('fr_Fr')))->willReturn($user)->shouldBeCalled();
     $userRepository->save($user)->shouldBeCalled();
     $this->execute($action);
 }
 function it_should_edit_project(ProjectRepository $projectRepository, EventDispatcherInterface $eventDispatcher, Project $project, EditProjectAction $action)
 {
     $action->getProject()->willReturn($project);
     $action->getName()->willReturn('Foo Bar');
     $action->getDefaultLocale()->willReturn('fr_FR');
     $action->getDescription()->willReturn('Description');
     $project->setName(Argument::exact(new Name('Foo Bar')))->shouldBeCalled();
     $project->setDefaultLocale(Argument::exact(Locale::parse('fr_FR')))->shouldBeCalled();
     $project->setDescription(Argument::exact('Description'))->shouldBeCalled();
     $projectRepository->save($project)->shouldBeCalled();
     $eventDispatcher->dispatch(EditProjectEvent::NAME, Argument::type('Openl10n\\Domain\\Project\\Application\\Event\\EditProjectEvent'))->shouldBeCalled();
     $this->execute($action)->shouldReturn($project);
 }
 function it_should_edit_translation(TranslationRepository $translationRepository, EventDispatcherInterface $eventDispatcher, Key $key, Phrase $phrase, EditTranslationPhraseAction $action)
 {
     $locale = Locale::parse('en');
     $action->getKey()->willReturn($key);
     $action->getLocale()->willReturn($locale);
     $action->getText()->willReturn('foobar');
     $action->isApproved()->willReturn(true);
     $key->hasPhrase($locale)->willReturn(true);
     $key->getPhrase($locale)->willReturn($phrase);
     $phrase->setText('foobar')->shouldBeCalled();
     $phrase->setApproved(true)->shouldBeCalled();
     $translationRepository->savePhrase($phrase)->shouldBeCalled();
     $this->execute($action)->shouldReturn($phrase);
 }
 public function execute(CreateProjectAction $action)
 {
     $name = new Name($action->getName());
     $slug = new Slug($action->getSlug());
     $locale = Locale::parse($action->getDefaultLocale());
     $description = $action->getDescription();
     $project = $this->projectRepository->createNew($slug);
     $project->setName($name);
     $project->setDefaultLocale($locale);
     $project->setDescription($description);
     $this->projectRepository->save($project);
     $this->eventDispatcher->dispatch(CreateProjectEvent::NAME, new CreateProjectEvent($project));
     return $project;
 }
 public function execute(EditProjectAction $action)
 {
     $name = new Name($action->getName());
     $locale = Locale::parse($action->getDefaultLocale());
     $description = $action->getDescription();
     $project = $action->getProject();
     $oldProject = clone $project;
     $project->setName($name);
     $project->setDefaultLocale($locale);
     $project->setDescription($description);
     $this->projectRepository->save($project);
     $this->eventDispatcher->dispatch(EditProjectEvent::NAME, new EditProjectEvent($project, $oldProject));
     return $project;
 }
 public function execute(RegisterUserAction $action)
 {
     $username = new Username($action->getUsername());
     $password = $action->getPassword();
     $email = new Email($action->getEmail());
     $displayName = new Name($action->getDisplayName());
     $preferredLocale = Locale::parse($action->getPreferredLocale());
     $user = $this->userRepository->createNew($username);
     $user->setName($displayName)->setEmail($email)->setPreferredLocale($preferredLocale);
     $encoder = $this->encoderFactory->getEncoder($user);
     $salt = md5(uniqid(null, true));
     $password = $encoder->encodePassword($password, $salt);
     $credentials = $this->credentialsRepository->createNew($user, $password, $salt);
     $this->userRepository->save($user);
     $this->credentialsRepository->save($credentials);
     return $user;
 }
 function it_execute_action(UserRepository $userRepository, CredentialsRepository $credentialsRepository, EncoderFactoryInterface $encoderFactory, EventDispatcherInterface $eventDispatcher, PasswordEncoderInterface $passwordEncoder, User $user, Credentials $credentials, RegisterUserAction $action)
 {
     // Mocks
     $action->getUsername()->willReturn('mattketmo');
     $action->getDisplayName()->willReturn('Matthieu Moquet');
     $action->getEmail()->willReturn('*****@*****.**');
     $action->getPassword()->willReturn('super_passw0rd');
     $action->getPreferredLocale()->willReturn('fr_FR');
     $encoderFactory->getEncoder($user)->willReturn($passwordEncoder);
     $passwordEncoder->encodePassword('super_passw0rd', Argument::type('string'))->willReturn('encoded_password==');
     $userRepository->createNew(Argument::exact(new Username('mattketmo')))->willReturn($user);
     $credentialsRepository->createNew($user, 'encoded_password==', Argument::type('string'))->shouldBeCalled()->willReturn($credentials);
     $user->setName(Argument::exact(new Name('Matthieu Moquet')))->shouldBeCalled()->willReturn($user);
     $user->setEmail(Argument::exact(new Email('*****@*****.**')))->shouldBeCalled()->willReturn($user);
     $user->setPreferredLocale(Argument::exact(Locale::parse('fr_FR')))->shouldBeCalled()->willReturn($user);
     $userRepository->save($user)->shouldBeCalled();
     $credentialsRepository->save($credentials)->shouldBeCalled();
     $this->execute($action)->shouldReturn($user);
 }
 public function execute(ExportTranslationFileAction $action)
 {
     $resource = $action->getResource();
     $project = $resource->getProject();
     $locale = Locale::parse($action->getLocale());
     $format = $action->getFormat() ?: pathinfo($resource->getPathname(), PATHINFO_EXTENSION);
     // Dump translations has a messages array according to given options
     $translations = $this->translationRepository->findByResource($resource);
     $messages = array();
     foreach ($translations as $translation) {
         $key = $translation->getIdentifier();
         $phrase = $translation->getPhrase($locale);
         // Ignore non approved phrase if reviewed option is set
         if (null !== $phrase && $action->hasOptionReviewed() && !$phrase->isApproved()) {
             $phrase = null;
         }
         // Fallback on default locale if option is set
         if (null === $phrase && $action->hasOptionFallbackLocale()) {
             $phrase = $translation->getPhrase($project->getDefaultLocale());
         }
         if (null !== $phrase) {
             // If phrase is valid, get text
             $text = $phrase->getText();
         } elseif ($action->hasOptionFallbackKey()) {
             // If phrase is not set, and has key fallback, then use key as text
             $text = $key;
         } else {
             // If phrase is not set, ignore it
             continue;
         }
         $messages[$key] = $text;
     }
     // Export messages into a MessageCatalogue
     $catalogue = new MessageCatalogue($locale, array((string) 'messages' => $messages));
     // Dump to file
     $directory = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'export_' . mt_rand(0, 99999);
     $this->translationDumper->dumpMessages($catalogue, $directory, $format);
     $filename = 'messages' . '.' . $locale . '.' . $format;
     $filepath = $directory . DIRECTORY_SEPARATOR . $filename;
     return new File($filepath);
 }
 private function createPhrase($keyRef, $locale, $phrase)
 {
     return (new Phrase($this->getReference('key-' . $keyRef), Locale::parse($locale)))->setText($phrase['text'])->setApproved($phrase['is_approved']);
 }
 public function execute(EditProfileAction $action)
 {
     $user = $action->getUser();
     $user->setName(new Name($action->getDisplayName()))->setEmail(new Email($action->getEmail()))->setPreferredLocale(Locale::parse($action->getPreferredLocale()));
     $this->userRepository->save($user);
 }
 public function execute(ImportTranslationFileAction $action)
 {
     $resource = $action->getResource();
     $locale = Locale::parse($action->getLocale());
     //
     // First upload translation file and extract message from it.
     //
     $file = $this->fileUploader->upload($action->getFile());
     $catalogue = $this->translationLoader->loadMessages($file, $locale, 'messages');
     $messages = $catalogue->all('messages');
     // Index messages by hashing their keys.
     // This solves a problem when keys are too long, eg. when keys are
     // the phrase in the default language.
     $messageKeys = array_keys($messages);
     $messageHash = array_map(function ($key) {
         return (string) new Hash($key);
     }, $messageKeys);
     $messagesIndex = array_combine($messageHash, $messageKeys);
     //
     // Extract all translations of the specific resource by hydrating the given locale
     //
     $specifications = new ResourceLocaleSpecification($resource, $locale);
     $translationPager = $this->translationRepository->findSatisfying($specifications);
     $translationPager->setMaxPerPage(99999);
     //
     // Iterate over existing translations
     //
     foreach ($translationPager as $translationKey) {
         $keyIdentifier = (string) $translationKey->getHash();
         if (!isset($messagesIndex[$keyIdentifier])) {
             // If current translation is not part of the file then clean it
             // if option was specified.
             // Note: the erase option should only be done with the project's default locale,
             // otherwise you may delete all translations which have not been translated yet.
             if ($action->hasOptionClean()) {
                 $deleteKeyAction = new DeleteTranslationKeyAction($translationKey);
                 $this->deleteTranslationKeyProcessor->execute($deleteKeyAction);
             }
             continue;
         }
         // Get phrase and mark translation as treated
         $newPhrase = $messages[$messagesIndex[$keyIdentifier]];
         unset($messages[$messagesIndex[$keyIdentifier]]);
         // Compare it to current phrase
         $phrase = $translationKey->getPhrase($locale);
         if (null === $phrase || $newPhrase !== (string) $phrase->getText() && $action->hasOptionErase()) {
             // If phrase doesn't exist yet or is different, then edit it.
             $editPhraseAction = new EditTranslationPhraseAction($translationKey, $locale);
             $editPhraseAction->setText($newPhrase);
             $editPhraseAction->setApproved($action->hasOptionReviewed());
             $this->editTranslationPhraseProcessor->execute($editPhraseAction);
         } elseif ($action->hasOptionReviewed() && !$phrase->isApproved()) {
             // If reviewed option is set, then automatically mark translation
             // phrase as approved, without updating its text.
             $editPhraseAction = new EditTranslationPhraseAction($translationKey, $locale);
             $editPhraseAction->setApproved(true);
             $this->editTranslationPhraseProcessor->execute($editPhraseAction);
         }
     }
     //
     // Save the other phrases (ie. new translations)
     //
     foreach ($messages as $key => $phrase) {
         // Create the translation key
         $createKeyAction = new CreateTranslationKeyAction();
         $createKeyAction->setResource($resource);
         $createKeyAction->setIdentifier($key);
         $key = $this->createTranslationKeyProcessor->execute($createKeyAction);
         // Edit the text of the translation for given locale
         $editPhraseAction = new EditTranslationPhraseAction($key, $locale);
         $editPhraseAction->setText($phrase);
         $editPhraseAction->setApproved($action->hasOptionReviewed());
         $this->editTranslationPhraseProcessor->execute($editPhraseAction);
     }
     // Finally remove temporary file.
     $this->fileUploader->remove($file);
     return $resource;
 }
 /**
  * Delete a translation phrase.
  *
  * @ApiDoc(
  *     description="Delete a translation phrase",
  *     statusCodes={
  *         204="Returned when successful",
  *         403="Returned when the user is not authorized",
  *         404="Returned when translation or phrase does not exist"
  *     },
  *     requirements={
  *         { "name"="translation", "dataType"="integer", "required"=true, "description"="Translation's id" },
  *         { "name"="locale", "dataType"="string", "required"=true }
  *     },
  * )
  * @Rest\View(statusCode=204)
  */
 public function deletePhrasesAction($translation, $locale)
 {
     $translationKey = $this->findTranslationOr404($translation);
     $translationPhrase = $translationKey->getPhrase(Locale::parse($locale));
     if (null === $translationPhrase) {
         throw $this->createNotFoundException(sprintf('Unable to find a "%s" phrase for translation #%s', $locale, $translationKey->getId()));
     }
     $action = new DeleteTranslationPhraseAction($translationPhrase);
     $this->get('openl10n.processor.delete_translation_phrase')->execute($action);
 }
 /**
  * Retrieve a translation commit.
  *
  * @ApiDoc(
  *     description="Get a translation commit",
  *     statusCodes={
  *         200="Returned when successful",
  *         403="Returned when the user is not authorized",
  *         404="Returned when the translation with given id does not exist"
  *     },
  *     requirements={
  *         { "name"="source", "dataType"="string", "required"=true, "description"="Source locale" },
  *         { "name"="target", "dataType"="string", "required"=true, "description"="Target locale" },
  *         { "name"="translation", "dataType"="integer", "required"=true, "description"="Translation's id" }
  *     },
  *     output="Openl10n\Bundle\ApiBundle\Facade\TranslationCommit"
  * )
  * @Rest\View
  * @Rest\Get("/translation_commits/{source}/{target}/{translation}")
  */
 public function getAction($source, $target, $translation)
 {
     $translation = $this->findTranslationOr404($translation);
     $source = Locale::parse($source);
     $target = Locale::parse($target);
     return new TranslationCommitFacade($translation, $source, $target);
 }
Example #20
0
 public function __construct(Username $username)
 {
     $this->username = $username;
     $this->name = new Name($username);
     $this->preferredLocale = Locale::parse('en');
 }
 /**
  * Test to delete an existing project.
  */
 public function testDeleteProjectLanguage()
 {
     $client = $this->getClient();
     $client->jsonRequest('DELETE', '/api/projects/foobar/languages/fr');
     $this->assertJsonResponse($client->getResponse(), Response::HTTP_NO_CONTENT);
     // Ensure project has been created
     $project = $this->get('openl10n.repository.project')->findOneBySlug(new Slug('foobar'));
     $language = $this->get('openl10n.repository.language')->findOneByProject($project, Locale::parse('fr'));
     $this->assertNull($language, 'Language "fr" should not exist after a DELETE in project "foobar"');
 }
 public function testDeleteTranslationPhrase()
 {
     $client = $this->getClient();
     $client->jsonRequest('DELETE', '/api/translations/1/phrases/fr');
     $this->assertJsonResponse($client->getResponse(), Response::HTTP_NO_CONTENT);
     // Here I'm force to clear the EntityManager to be sure the `Key::getPhrase()`
     // method refresh its relations.
     $this->get('doctrine.orm.entity_manager')->clear();
     $translation = $this->get('openl10n.repository.translation')->findOneById(1);
     $this->assertNull($translation->getPhrase(Locale::parse('fr')), 'French phrase of translation 1 should not exist anymore');
 }
 private function createProject($slug, array $data)
 {
     return (new Project(new Slug($slug)))->setName(new Name($data['name']))->setDefaultLocale(Locale::parse($data['locale']))->setDescription($data['description']);
 }
 /**
  * Delete a project language.
  *
  * @ApiDoc(
  *     description="Delete a project language",
  *     statusCodes={
  *         204="Returned when successful",
  *         403="Returned when the user is not authorized",
  *         404="Returned when project or locale does not exist"
  *     },
  *     requirements={
  *         { "name"="project", "dataType"="string", "required"=true, "description"="Project's slug" },
  *         { "name"="locale", "dataType"="string", "required"=true, "description"="Language's locale" }
  *     }
  * )
  * @Rest\View(statusCode=204)
  */
 public function deleteLanguagesAction($project, $locale)
 {
     $project = $this->findProjectOr404($project);
     $language = $this->findLanguageOr404($project, $locale);
     if ((string) $project->getDefaultLocale() === (string) Locale::parse($locale)) {
         return View::create(array('message' => 'You can not delete project default locale'), 400);
     }
     $action = new DeleteLanguageAction($language);
     $this->get('openl10n.processor.delete_language')->execute($action);
 }
 protected function transformLanguage($locale)
 {
     $facade = new LanguageFacade(Locale::parse($locale));
     return $facade;
 }
 public function testImportResourceWithVeryLongKey()
 {
     // Retrieve id of the "empty" resource in foobar project
     $emptyResource = $this->getResource('foobar', 'empty.en.json');
     $resourceId = $emptyResource->getId();
     $veryLongKey = str_repeat('Very Long Key.', 500);
     $veryLongValue = str_repeat('Very Long Value.', 500);
     // Create dummy json file
     $tempname = sys_get_temp_dir() . '/' . mt_rand(0, 9999) . '_dummy.en.json';
     $content = json_encode([$veryLongKey => $veryLongValue]);
     file_put_contents($tempname, $content);
     $uploadedFile = new UploadedFile($tempname, 'dummy.en.json', 'application/json', strlen($content));
     $client = $this->getClient();
     // Upload resource file
     $client->request('POST', '/api/resources/' . $resourceId . '/import', ['locale' => 'en'], ['file' => $uploadedFile]);
     $response = $client->getResponse();
     $this->assertEquals(Response::HTTP_NO_CONTENT, $response->getStatusCode());
     // Here I'm force to clear the EntityManager to be sure the `Key::getPhrase()`
     $this->get('doctrine.orm.entity_manager')->clear();
     // Assert content has been inserted in database
     $translationKeys = $this->get('openl10n.repository.translation')->findByResource($emptyResource);
     $this->assertCount(1, $translationKeys);
     $this->assertNotEquals($veryLongKey, $translationKeys[0]->getIdentifier(), 'The key is truncated in database');
     $expectedHash = (string) new Hash($veryLongKey);
     $this->assertEquals($expectedHash, $translationKeys[0]->getHash());
     $this->assertEquals($veryLongValue, $translationKeys[0]->getPhrase(Locale::parse('en'))->getText());
 }
 private function createLanguage($project, $locale)
 {
     return new Language($this->getReference('project-' . $project), Locale::parse($locale));
 }
Example #28
0
 private function createUser($username, $data)
 {
     return (new User(new Username($username)))->setName(new Name($data['name']))->setEmail(new Email($data['email']))->setPreferredLocale(Locale::parse($data['locale']));
 }