Skip to content

Commit

Permalink
need to dev a php sdk for bing translator...
Browse files Browse the repository at this point in the history
  • Loading branch information
potsky committed Jan 11, 2016
1 parent 44fc67c commit bea4be8
Show file tree
Hide file tree
Showing 11 changed files with 369 additions and 64 deletions.
6 changes: 3 additions & 3 deletions phpunit.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
backupStaticAttributes="false"
bootstrap="tests/bootstrap.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
convertErrorsToExceptions="false"
convertNoticesToExceptions="false"
convertWarningsToExceptions="false"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,16 @@ public function __construct( Repository $configRepository )
*/
public function fire()
{
$success = $this->manager->deleteBackupFiles( $this->lang_folder_path , (int)$this->option( 'days' ) , $this->option( 'dry-run' ) );
$days = (int)$this->option( 'days' );

if ( $days < 0 )
{
$this->writeError( "days option cannot be negative" );

return self::ERROR;
}

$success = $this->manager->deleteBackupFiles( $this->lang_folder_path , $days , $this->option( 'dry-run' ) );

return ( $success === true ) ? self::SUCCESS : self::ERROR;
}
Expand Down
63 changes: 8 additions & 55 deletions src/Potsky/LaravelLocalizationHelpers/Command/LocalizationFind.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ public function __construct( Repository $configRepository )
*/
public function fire()
{

$lemma = $this->argument( 'lemma' );
$folders = $this->manager->getPath( $this->folders );

Expand All @@ -80,67 +79,21 @@ public function fire()
////////////////////////////////
// Parse all lemmas from code //
////////////////////////////////
$files = array();
$files = $this->manager->findLemma( $lemma , $folders , $this->trans_methods , $this->option( 'regex' ) , $this->option( 'short' ) );

foreach ( $folders as $path )
{
foreach ( $this->manager->getFilesWithExtension( $path ) as $php_file_path => $dumb )
{
foreach ( $this->manager->extractTranslationFromPhpFile( $php_file_path , $this->trans_methods ) as $k => $v )
{
$real_value = eval( "return $k;" );
$found = false;

if ( $this->option( 'regex' ) )
{
try
{
$r = preg_match( $lemma , $real_value );
}
catch ( \Exception $e )
{
$this->writeLine( "<error>The argument is not a valid regular expression:</error>" . str_replace( 'preg_match():' , '' , $e->getMessage() ) );
die();
}
if ( $r === 1 )
{
$found = true;
}
else if ( $r === false )
{
$this->writeError( "The argument is not a valid regular expression" );
die();
}
}
else
{
if ( strpos( $real_value , $lemma ) )
{
$found = true;
}
}


if ( $found === true )
{
if ( $this->option( 'short' ) )
{
$php_file_path = $this->manager->getShortPath( $php_file_path );
}
$files[] = $php_file_path;
break;
}
}
}
}

if ( count( $files ) > 0 )
if ( ( is_array( $files ) ) && ( count( $files ) > 0 ) )
{
$this->writeLine( 'Lemma <info>' . $lemma . '</info> has been found in:' );
foreach ( $files as $file )
{
$this->writeLine( ' <info>' . $file . '</info>' );
}

return self::SUCCESS;
}
else
{
return self::ERROR;
}
}

Expand Down
85 changes: 83 additions & 2 deletions src/Potsky/LaravelLocalizationHelpers/Factory/Localization.php
Original file line number Diff line number Diff line change
Expand Up @@ -193,8 +193,9 @@ public function extractTranslationFromPhpFile( $path , $trans_methods )
/**
* Extract all translations from the provided folders
*
* @param array $folders a list of folder to search in
* @param array $trans_methods an array of regex to catch
* @param array $folders a list of folder to search in
* @param array $trans_methods an array of regex to catch
* @param string $php_file_extension default is php
*
* @return array
*/
Expand Down Expand Up @@ -317,6 +318,11 @@ public function getBackupFiles( $lang_directory )

public function deleteBackupFiles( $lang_folder_path , $days = 0 , $dryRun = false )
{
if ( $days < 0 )
{
return false;
}

try
{
$dir_lang = $this->getLangPath( $lang_folder_path );
Expand Down Expand Up @@ -405,6 +411,81 @@ public function isDateOlderThanDays( \DateTime $date , $days )
return ( $now->diff( $date )->format( '%a' ) >= $days );
}

/**
* Get the list of PHP code files where a lemma is defined
*
* @param string $lemma A lemma to search for or a regex to search for
* @param array $folders An array of folder to search for lemma in
* @param array $trans_methods An array of PHP lang functions
* @param bool|false $regex Is lemma a regex ?
* @param bool|false $shortOutput Output style for fiel paths
*
* @return array|false
*/
public function findLemma( $lemma , $folders , $trans_methods , $regex = false , $shortOutput = false )
{
$files = array();

foreach ( $folders as $path )
{
foreach ( $this->getFilesWithExtension( $path ) as $php_file_path => $dumb )
{
foreach ( $this->extractTranslationFromPhpFile( $php_file_path , $trans_methods ) as $k => $v )
{
$real_value = eval( "return $k;" );
$found = false;

if ( $regex )
{
try
{
$r = preg_match( $lemma , $real_value );
}
// Exception is thrown via command
catch ( \Exception $e )
{
$this->messageBag->writeError( "The argument is not a valid regular expression:" . str_replace( 'preg_match():' , '' , $e->getMessage() ) );

return false;
}
if ( $r === 1 )
{
$found = true;
}
// Normal behavior via method call
// @codeCoverageIgnoreStart
else if ( $r === false )
{
$this->messageBag->writeError( "The argument is not a valid regular expression" );

return false;
}
// @codeCoverageIgnoreEnd
}
else
{
if ( ! ( strpos( $real_value , $lemma ) === false ) )
{
$found = true;
}
}

if ( $found === true )
{
if ( $shortOutput === true )
{
$php_file_path = $this->getShortPath( $php_file_path );
}
$files[] = $php_file_path;
break;
}
}
}
}

return $files;
}

/**
* Return the date of a backup file
*
Expand Down
42 changes: 42 additions & 0 deletions src/Potsky/LaravelLocalizationHelpers/Factory/Translator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php namespace Potsky\LaravelLocalizationHelpers\Factory;

class Translator implements TranslatorInterface
{
/** @var TranslatorInterface */
protected $translator;

/**
* @param string $translator The translation service name
* @param array $config The configuration array for the translation service
*/
public function __construct( $translator , $config )
{
$class = 'Potsky\LaravelLocalizationHelpers\Factory\Translator' . $translator;
$translator = new $class( $config );

if ( ! $translator instanceof TranslatorInterface )
{
throw new Exception( 'Provided translator does not implement TranslatorInterface' );
}

$this->translator = $translator;
$this->config = $config;
}

public function translate( $word , $toLang , $fromLang = null )
{
return $this->translator->translate( $word , $toLang , $fromLang );
}

/**
* Return the used translator
*
* @return \Potsky\LaravelLocalizationHelpers\Factory\TranslatorInterface
*/
public function getTranslator()
{
return $this->translator;
}
}


Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?php namespace Potsky\LaravelLocalizationHelpers\Factory;

interface TranslatorInterface
{
public function translate( $word , $toLang , $fromLang = null );
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php namespace Potsky\LaravelLocalizationHelpers\Factory;

class TranslatorMicrosoft implements TranslatorInterface
{
protected $bingTranslator;

/**
* @param array $config
*/
public function __construct( $config )
{
if ( isset( $config[ 'api_key' ] ) )
{
$apiKey = $config[ 'api_key' ];
}
else if ( ( $apiKey = getenv( 'LLH_MICROSOFT_TRANSLATOR_API_KEY' ) ) === false )
{
throw new Exception( 'Please provide an API key for Microsoft Bing Translator service' );
}
}

/**
* @param string $word Sentence or word to translate
* @param string $toLang Target language
* @param null $fromLang Source language (if set to null, translator will try to guess)
*
* @return string|null The translated sentence or null if an error occurs
*/
public function translate( $word , $toLang , $fromLang = null )
{
try
{
$translation = $this->bingTranslator->translate( $word , $fromLang , $toLang );

if ( is_string( $translation ) )
{
return $translation;
}

return null;
}
catch ( Exception $e )
{
return null;
}
}
}


49 changes: 48 additions & 1 deletion src/config/config.php
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,53 @@
| when using option editor, package will use this command to open your files
|
*/
'editor_command_line' => '/Applications/Sublime\\ Text.app/Contents/SharedSupport/bin/subl'
'editor_command_line' => '/Applications/Sublime\\ Text.app/Contents/SharedSupport/bin/subl',


/*
|--------------------------------------------------------------------------
| Translator
|--------------------------------------------------------------------------
|
| Use the Microsoft translator by default. This is the only available translator now
|
*/
'translator' => 'Microsoft',

/*
|--------------------------------------------------------------------------
| Translator default language
|--------------------------------------------------------------------------
|
| Set the default language used in your PHP code. If set to null, the translator
| will try to guess it.
|
| The default language in your code is the language you use in this PHP line
| for example :
|
| trans( 'message.This is a message in english' );
|
| Supported languages are : ar, bg, ca, cs, da, de, el, en, es, et, fa, fi, fr,
| he, hi, ht, hu, id, it, ja, ko, lt, lv, ms, mww, nl, no, pl, pt, ro, ru, sk,
| sl, sv, th, tr, uk, ur, vi, zh-CHS, zh-CHT
|
*/
'translator_default_language' => null,

/*
|--------------------------------------------------------------------------
| Microsoft Bing Translator service
|--------------------------------------------------------------------------
|
| Package can automatically translate your lemma. Please create a free API
| key at this address : https://datamarket.azure.com/dataset/bing/microsofttranslator
|
| I never liked M$ but 2.000.000 chars per month is really interesting!
|
| If you don't want to set this API KEY here, you can set an environment
| parameter named LLH_MICROSOFT_TRANSLATOR_API_KEY
|
*/
'translator_microsoft_api_key' => null,

);
15 changes: 15 additions & 0 deletions tests/CommandClearTests.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,21 @@ public function testClean3Days()
$this->assertCount( 6 , glob( self::LANG_DIR_PATH . '/*/message*.php' ) );
}

/**
* Error when days is negative
*/
public function testErrorDaysNegative()
{
$output = new BufferedOutput;

/** @noinspection PhpVoidFunctionResultUsedInspection */
$return = Artisan::call( 'localization:clear' , array( '--days' => -3 ) , $output );
$this->assertEquals( 1 , $return );

$manager = new Localization( new MessageBag() );
$this->assertFalse( $manager->deleteBackupFiles( '' , -3 , true ) );
}

/**
* Nothing should be deleted
*/
Expand Down

0 comments on commit bea4be8

Please sign in to comment.