code
stringlengths
15
9.96M
docstring
stringlengths
1
10.1k
func_name
stringlengths
1
124
language
stringclasses
1 value
repo
stringlengths
7
63
path
stringlengths
6
186
url
stringlengths
50
236
license
stringclasses
4 values
public function dimension($worksheetIndex = 0) { if (($ws = $this->worksheet($worksheetIndex)) === false) { return [0, 0]; } /* @var SimpleXMLElement $ws */ $ref = (string)$ws->dimension['ref']; if (SimpleXLSX::strpos($ref, ':') !== false) { $d = explode(':', $ref); $idx = $this->getIndex($d[1]); return [$idx[0] + 1, $idx[1] + 1]; } /* if ( $ref !== '' ) { // 0.6.8 $index = $this->getIndex( $ref ); return [ $index[0] + 1, $index[1] + 1 ]; } */ // slow method $maxC = $maxR = 0; $iR = -1; foreach ($ws->sheetData->row as $row) { $iR++; $iC = -1; foreach ($row->c as $c) { $iC++; $idx = $this->getIndex((string)$c['r']); $x = $idx[0]; $y = $idx[1]; if ($x > -1) { if ($x > $maxC) { $maxC = $x; } if ($y > $maxR) { $maxR = $y; } } else { if ($iC > $maxC) { $maxC = $iC; } if ($iR > $maxR) { $maxR = $iR; } } } } return [$maxC + 1, $maxR + 1]; }
returns [numCols,numRows] of worksheet @param int $worksheetIndex @return array
dimension
php
shuchkin/simplexlsx
src/SimpleXLSX.php
https://github.com/shuchkin/simplexlsx/blob/master/src/SimpleXLSX.php
MIT
public function readRows($worksheetIndex = 0, $limit = 0) { if (($ws = $this->worksheet($worksheetIndex)) === false) { return; } $dim = $this->dimension($worksheetIndex); $numCols = $dim[0]; $numRows = $dim[1]; $emptyRow = []; for ($i = 0; $i < $numCols; $i++) { $emptyRow[] = ''; } $curR = 0; $_limit = $limit; /* @var SimpleXMLElement $ws */ foreach ($ws->sheetData->row as $row) { $r = $emptyRow; $curC = 0; foreach ($row->c as $c) { // detect skipped cols $idx = $this->getIndex((string)$c['r']); $x = $idx[0]; $y = $idx[1]; if ($x > -1) { $curC = $x; while ($curR < $y) { yield $emptyRow; $curR++; $_limit--; if ($_limit === 0) { return; } } } $r[$curC] = $this->value($c); $curC++; } yield $r; $curR++; $_limit--; if ($_limit === 0) { return; } } while ($curR < $numRows) { yield $emptyRow; $curR++; $_limit--; if ($_limit === 0) { return; } } }
@param $worksheetIndex @param $limit @return \Generator
readRows
php
shuchkin/simplexlsx
src/SimpleXLSX.php
https://github.com/shuchkin/simplexlsx/blob/master/src/SimpleXLSX.php
MIT
public function readRowsEx($worksheetIndex = 0, $limit = 0) { if (!$this->rowsExReader) { require_once __DIR__ . '/SimpleXLSXEx.php'; $this->rowsExReader = new SimpleXLSXEx($this); } return $this->rowsExReader->readRowsEx($worksheetIndex, $limit); }
@param $worksheetIndex @param $limit @return \Generator|null
readRowsEx
php
shuchkin/simplexlsx
src/SimpleXLSX.php
https://github.com/shuchkin/simplexlsx/blob/master/src/SimpleXLSX.php
MIT
public function getCell($worksheetIndex = 0, $cell = 'A1') { if (($ws = $this->worksheet($worksheetIndex)) === false) { return false; } if (is_array($cell)) { $cell = SimpleXLSX::num2name($cell[0]) . $cell[1];// [3,21] -> D21 } if (is_string($cell)) { $result = $ws->sheetData->xpath("row/c[@r='" . $cell . "']"); if (count($result)) { return $this->value($result[0]); } } return null; }
Returns cell value VERY SLOW! Use ->rows() or ->rowsEx() @param int $worksheetIndex @param string|array $cell ref or coords, D12 or [3,12] @return mixed Returns NULL if not found
getCell
php
shuchkin/simplexlsx
src/SimpleXLSX.php
https://github.com/shuchkin/simplexlsx/blob/master/src/SimpleXLSX.php
MIT
public function __construct( public readonly string $alias, public readonly array $queuesToConsume, public readonly int $memoryLimit, public readonly int $timeout, ) {}
@param array<int, string> $queuesToConsume
__construct
php
NativePHP/laravel
src/DTOs/QueueConfig.php
https://github.com/NativePHP/laravel/blob/master/src/DTOs/QueueConfig.php
MIT
protected function createDoctrineMappingDriver(ContainerBuilder $container, $driverId, $driverClass) { $driverDefinition = new Definition($driverClass, [ [realpath(__DIR__.'/../Resources/config/model') => 'Lexik\Bundle\TranslationBundle\Model'], SimplifiedXmlDriver::DEFAULT_FILE_EXTENSION, true ]); $driverDefinition->setPublic(false); $container->setDefinition($driverId, $driverDefinition); }
Add a driver to load mapping of model classes. @param string $driverId @param string $driverClass
createDoctrineMappingDriver
php
lexik/LexikTranslationBundle
DependencyInjection/LexikTranslationExtension.php
https://github.com/lexik/LexikTranslationBundle/blob/master/DependencyInjection/LexikTranslationExtension.php
MIT
protected function buildDevServicesDefinition(ContainerBuilder $container) { $container ->getDefinition('lexik_translation.data_grid.request_handler') ->addMethodCall('setProfiler', [new Reference('profiler')]); $tokenFinderDefinition = new Definition(); $tokenFinderDefinition->setClass($container->getParameter('lexik_translation.token_finder.class')); $tokenFinderDefinition->setArguments([new Reference('profiler'), new Parameter('lexik_translation.token_finder.limit')]); $container->setDefinition($container->getParameter('lexik_translation.token_finder.class'), $tokenFinderDefinition); }
Load dev tools.
buildDevServicesDefinition
php
lexik/LexikTranslationBundle
DependencyInjection/LexikTranslationExtension.php
https://github.com/lexik/LexikTranslationBundle/blob/master/DependencyInjection/LexikTranslationExtension.php
MIT
public function translationsTablesExist() { /** @var EntityManager $em */ $em = $this->getManager(); $connection = $em->getConnection(); // listDatabases() is not available for SQLite if (!$connection->getDriver() instanceof SQLiteDriver) { // init a tmp connection without dbname/path/url in case it does not exist yet $params = $connection->getParams(); if (isset($params['master'])) { $params = $params['master']; } unset($params['dbname'], $params['path'], $params['url']); try { $configuration = new Configuration(); if (class_exists(DefaultSchemaManagerFactory::class)) { $configuration->setSchemaManagerFactory(new DefaultSchemaManagerFactory()); } $tmpConnection = DriverManager::getConnection($params, $configuration); $schemaManager = method_exists($tmpConnection, 'createSchemaManager') ? $tmpConnection->createSchemaManager() : $tmpConnection->getSchemaManager(); $dbExists = in_array($connection->getDatabase(), $schemaManager->listDatabases()); $tmpConnection->close(); } catch (ConnectionException|\Exception) { $dbExists = false; } if (!$dbExists) { return false; } } // checks tables exist $tables = [ $em->getClassMetadata($this->getModelClass('trans_unit'))->getTableName(), $em->getClassMetadata($this->getModelClass('translation'))->getTableName(), ]; $schemaManager = method_exists($connection, 'createSchemaManager') ? $connection->createSchemaManager() : $connection->getSchemaManager(); return $schemaManager->tablesExist($tables); }
Returns true if translation tables exist. @return boolean
translationsTablesExist
php
lexik/LexikTranslationBundle
Storage/DoctrineORMStorage.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Storage/DoctrineORMStorage.php
MIT
protected function getTranslationRepository() { return $this->getManager()->getRepository($this->classes['translation']); }
Returns the TransUnit repository. @return object
getTranslationRepository
php
lexik/LexikTranslationBundle
Storage/DoctrineORMStorage.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Storage/DoctrineORMStorage.php
MIT
public function getAllDomainsByLocale() { return $this->createQueryBuilder('tu') ->select('te.locale, tu.domain') ->leftJoin('tu.translations', 'te') ->where('te.id is not null') ->addGroupBy('te.locale') ->addGroupBy('tu.domain') ->getQuery() ->getArrayResult(); }
Returns all domain available in database. @return array
getAllDomainsByLocale
php
lexik/LexikTranslationBundle
Entity/TransUnitRepository.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Entity/TransUnitRepository.php
MIT
protected function getORMStorage(EntityManager $em) { $registryMock = $this->getDoctrineRegistryMock($em); $storage = new DoctrineORMStorage($registryMock, 'default', [ 'trans_unit' => self::ENTITY_TRANS_UNIT_CLASS, 'translation' => self::ENTITY_TRANSLATION_CLASS, 'file' => self::ENTITY_FILE_CLASS, ]); return $storage; }
Create a storage class form doctrine ORM. @return DoctrineORMStorage
getORMStorage
php
lexik/LexikTranslationBundle
Tests/Unit/BaseUnitTestCase.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Tests/Unit/BaseUnitTestCase.php
MIT
protected function getDoctrineRegistryMock($om) { $registryMock = $this->getMockBuilder(ManagerRegistry::class) ->setConstructorArgs( [ 'registry', [], [], 'default', 'default', 'proxy', ] ) ->getMock(); $registryMock ->expects($this->any()) ->method('getManager') ->will($this->returnValue($om)); return $registryMock; }
@param $om @return MockObject
getDoctrineRegistryMock
php
lexik/LexikTranslationBundle
Tests/Unit/BaseUnitTestCase.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Tests/Unit/BaseUnitTestCase.php
MIT
protected function getMockSqliteEntityManager($mockCustomHydrator = false) { $cache = new ArrayAdapter(); // xml driver $xmlDriver = new SimplifiedXmlDriver( [ __DIR__ . '/../../Resources/config/model' => 'Lexik\Bundle\TranslationBundle\Model', __DIR__ . '/../../Resources/config/doctrine' => 'Lexik\Bundle\TranslationBundle\Entity', ] ); $config = Setup::createAttributeMetadataConfiguration( [ __DIR__ . '/../../Model', __DIR__ . '/../../Entity', ], false, null, null ); $config->setMetadataDriverImpl($xmlDriver); $config->setMetadataCache($cache); $config->setQueryCache($cache); $config->setProxyDir(sys_get_temp_dir()); $config->setProxyNamespace('Proxy'); $config->setAutoGenerateProxyClasses(true); $config->setClassMetadataFactoryName(DoctrineClassMetadataFactory::class); $config->setDefaultRepositoryClassName(EntityRepository::class); if ($mockCustomHydrator) { $config->setCustomHydrationModes( [ 'SingleColumnArrayHydrator' => SingleColumnArrayHydrator::class, ] ); } $conn = [ 'driver' => 'pdo_sqlite', 'memory' => true, ]; $connection = DriverManager::getConnection($conn); $em = new EntityManager($connection, $config); return $em; }
EntityManager mock object together with annotation mapping driver and pdo_sqlite database in memory @return EntityManager
getMockSqliteEntityManager
php
lexik/LexikTranslationBundle
Tests/Unit/BaseUnitTestCase.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Tests/Unit/BaseUnitTestCase.php
MIT
protected function assertDatabaseEntries($em, $expected) { $number = $em->getRepository(self::ENTITY_TRANS_UNIT_CLASS) ->createQueryBuilder('tu') ->select('COUNT(tu.id)') ->getQuery() ->getSingleScalarResult(); $this->assertEquals($expected, $number); $number = $em->getRepository(self::ENTITY_TRANSLATION_CLASS) ->createQueryBuilder('t') ->select('COUNT(t.id)') ->getQuery() ->getSingleScalarResult(); $this->assertEquals($expected * 2, $number); $number = $em->getRepository(self::ENTITY_FILE_CLASS) ->createQueryBuilder('f') ->select('COUNT(f.id)') ->getQuery() ->getSingleScalarResult(); $this->assertEquals($expected, $number); }
Counts the number of entries in each tables. @param EntityManager $em @param int $expected
assertDatabaseEntries
php
lexik/LexikTranslationBundle
Tests/Unit/Translation/Importer/FileImporterTest.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Tests/Unit/Translation/Importer/FileImporterTest.php
MIT
private function getReflectionMethod($name) { $class = new \ReflectionClass(DataGridRequestHandler::class); $method = $class->getMethod($name); $method->setAccessible(true); return $method; }
@return \ReflectionMethod
getReflectionMethod
php
lexik/LexikTranslationBundle
Tests/Unit/Util/DataGrid/DataGridRequestHandlerTest.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Tests/Unit/Util/DataGrid/DataGridRequestHandlerTest.php
MIT
private function getDataGridRequestHandler() { $transUnitManagerMock = $this->getMockBuilder(TransUnitManager::class) ->disableOriginalConstructor() ->getMock(); $fileManagerMock = $this->getMockBuilder(FileManagerInterface::class) ->disableOriginalConstructor() ->getMock(); $storageMock = $this->getMockBuilder(StorageInterface::class) ->disableOriginalConstructor() ->getMock(); $localeManager = new LocaleManager([]); return new DataGridRequestHandler($transUnitManagerMock, $fileManagerMock, $storageMock, $localeManager); }
@return DataGridRequestHandler
getDataGridRequestHandler
php
lexik/LexikTranslationBundle
Tests/Unit/Util/DataGrid/DataGridRequestHandlerTest.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Tests/Unit/Util/DataGrid/DataGridRequestHandlerTest.php
MIT
public function __construct() { $this->domain = 'messages'; $this->translations = new ArrayCollection(); }
Construct.
__construct
php
lexik/LexikTranslationBundle
Model/TransUnit.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Model/TransUnit.php
MIT
public function setLocale($locale) { $this->locale = $locale; $this->content = ''; }
Set locale @param string $locale
setLocale
php
lexik/LexikTranslationBundle
Model/Translation.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Model/Translation.php
MIT
public function getLocale() { return $this->locale; }
Get locale @return string
getLocale
php
lexik/LexikTranslationBundle
Model/Translation.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Model/Translation.php
MIT
public function setContent($content) { $this->content = $content; }
Set content @param string $content
setContent
php
lexik/LexikTranslationBundle
Model/Translation.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Model/Translation.php
MIT
public function getContent() { return $this->content; }
Get content @return string
getContent
php
lexik/LexikTranslationBundle
Model/Translation.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Model/Translation.php
MIT
public function getFile() { return $this->file; }
Get file @return File
getFile
php
lexik/LexikTranslationBundle
Model/Translation.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Model/Translation.php
MIT
public function getCreatedAt() { return $this->createdAt; }
Get createdAt @return datetime $createdAt
getCreatedAt
php
lexik/LexikTranslationBundle
Model/Translation.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Model/Translation.php
MIT
public function getUpdatedAt() { return $this->updatedAt; }
Get updatedAt @return datetime $updatedAt
getUpdatedAt
php
lexik/LexikTranslationBundle
Model/Translation.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Model/Translation.php
MIT
public function isModifiedManually() { return $this->modifiedManually; }
@return bool
isModifiedManually
php
lexik/LexikTranslationBundle
Model/Translation.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Model/Translation.php
MIT
public function setModifiedManually($modifiedManually) { $this->modifiedManually = $modifiedManually; }
@param bool $modifiedManually
setModifiedManually
php
lexik/LexikTranslationBundle
Model/Translation.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Model/Translation.php
MIT
public function __construct( protected TransUnitManagerInterface $transUnitManager, protected FileManagerInterface $fileManager, protected StorageInterface $storage, protected LocaleManagerInterface $localeManager, protected string $rootDir, ) { }
@param string $rootDir
__construct
php
lexik/LexikTranslationBundle
Form/Handler/TransUnitFormHandler.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Form/Handler/TransUnitFormHandler.php
MIT
protected function invalidateSystemCacheForFile($path) { if (ini_get('apc.enabled') && function_exists('apc_delete_file')) { if (apc_exists($path) && !apc_delete_file($path)) { throw new \RuntimeException(sprintf('Failed to clear APC Cache for file %s', $path)); } } elseif ('cli' === php_sapi_name() ? ini_get('opcache.enable_cli') : ini_get('opcache.enable')) { if (function_exists("opcache_invalidate") && !opcache_invalidate($path, true)) { throw new \RuntimeException(sprintf('Failed to clear OPCache for file %s', $path)); } } }
@param string $path @throws \RuntimeException
invalidateSystemCacheForFile
php
lexik/LexikTranslationBundle
Translation/Translator.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Translation/Translator.php
MIT
public function getFormats() { $allFormats = []; foreach ($this->loaderIds as $id => $formats) { foreach ($formats as $format) { if ('database' !== $format) { $allFormats[] = $format; } } } return $allFormats; }
Returns all translations file formats. @return array
getFormats
php
lexik/LexikTranslationBundle
Translation/Translator.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Translation/Translator.php
MIT
public function getLoader($format) { $loader = null; $i = 0; $ids = array_keys($this->loaderIds); while ($i < count($ids) && null === $loader) { if (in_array($format, $this->loaderIds[$ids[$i]])) { $loader = $this->container->get($ids[$i]); } $i++; } if (!($loader instanceof LoaderInterface)) { throw new \RuntimeException(sprintf('No loader found for "%s" format.', $format)); } return $loader; }
Returns a loader according to the given format. @param string $format @throws \RuntimeException @return LoaderInterface
getLoader
php
lexik/LexikTranslationBundle
Translation/Translator.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Translation/Translator.php
MIT
protected function createXmlDocument() { $dom = new \DOMDocument('1.0', 'utf-8'); $dom->formatOutput = true; return $dom; }
Create a new xml document. @return \DOMDocument
createXmlDocument
php
lexik/LexikTranslationBundle
Translation/Exporter/XliffExporter.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Translation/Exporter/XliffExporter.php
MIT
protected function addRootNodes(\DOMDocument $dom, $targetLanguage = null) { $xliff = $dom->appendChild($dom->createElement('xliff')); $xliff->appendChild(new \DOMAttr('xmlns', 'urn:oasis:names:tc:xliff:document:1.2')); $xliff->appendChild(new \DOMAttr('version', '1.2')); $fileNode = $xliff->appendChild($dom->createElement('file')); $fileNode->appendChild(new \DOMAttr('source-language', 'en')); $fileNode->appendChild(new \DOMAttr('datatype', 'plaintext')); $fileNode->appendChild(new \DOMAttr('original', 'file.ext')); if (!is_null($targetLanguage)) { $fileNode->appendChild(new \DOMAttr('target-language', $targetLanguage)); } $bodyNode = $fileNode->appendChild($dom->createElement('body')); return $bodyNode; }
Add root nodes to a document. @param string|null $targetLanguage @return \DOMElement
addRootNodes
php
lexik/LexikTranslationBundle
Translation/Exporter/XliffExporter.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Translation/Exporter/XliffExporter.php
MIT
protected function createTranslationNode(\DOMDocument $dom, $id, $key, $value) { $translationNode = $dom->createElement('trans-unit'); $translationNode->appendChild(new \DOMAttr('id', $id)); /** * @see http://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html#approved */ if ($value != '') { $translationNode->appendChild(new \DOMAttr('approved', 'yes')); } $source = $dom->createElement('source'); $source->appendChild($dom->createCDATASection($key)); $translationNode->appendChild($source); $target = $dom->createElement('target'); $target->appendChild($dom->createCDATASection($value)); $translationNode->appendChild($target); return $translationNode; }
Create a new trans-unit node. @param int $id @param string $key @param string $value @return \DOMElement
createTranslationNode
php
lexik/LexikTranslationBundle
Translation/Exporter/XliffExporter.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Translation/Exporter/XliffExporter.php
MIT
public function getExporters() { return $this->exporters; }
@return array
getExporters
php
lexik/LexikTranslationBundle
Translation/Exporter/ExporterCollector.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Translation/Exporter/ExporterCollector.php
MIT
public function addExporter($id, ExporterInterface $exporter) { $this->exporters[$id] = $exporter; }
@param string $id
addExporter
php
lexik/LexikTranslationBundle
Translation/Exporter/ExporterCollector.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Translation/Exporter/ExporterCollector.php
MIT
public function getByFormat($format) { foreach ($this->getExporters() as $exporter) { if ($exporter->support($format)) { return $exporter; } } throw new \RuntimeException(sprintf('No exporter found for "%s" format.', $format)); }
Returns an exporter that support the given format. @param string $format @return ExporterInterface @throws \RuntimeException
getByFormat
php
lexik/LexikTranslationBundle
Translation/Exporter/ExporterCollector.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Translation/Exporter/ExporterCollector.php
MIT
public function export($format, $file, $translations) { foreach ($this->getExporters() as $exporter) { if ($exporter->support($format)) { return $exporter->export($file, $translations); } } throw new \RuntimeException(sprintf('No exporter found for "%s" format.', $format)); }
@param string $format @param string $file @param array $translations @return bool @throws \RuntimeException
export
php
lexik/LexikTranslationBundle
Translation/Exporter/ExporterCollector.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Translation/Exporter/ExporterCollector.php
MIT
public function __construct( private $hierarchicalFormat = false ) { }
@param bool $hierarchicalFormat
__construct
php
lexik/LexikTranslationBundle
Translation/Exporter/JsonExporter.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Translation/Exporter/JsonExporter.php
MIT
protected function converterKeyToArray($key, mixed $value) { $keysTrad = preg_split("/\./", $key); return $this->convertArrayToArborescence($keysTrad, $value); }
@param string $key @return array
converterKeyToArray
php
lexik/LexikTranslationBundle
Translation/Exporter/JsonExporter.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Translation/Exporter/JsonExporter.php
MIT
protected function convertArrayToArborescence(mixed $arrayIn, mixed $endValue) { $lenArray = is_countable($arrayIn) ? count($arrayIn) : 0; if ($lenArray == 0) { return $endValue; } $firstKey = array_key_first($arrayIn); $firstValue = $arrayIn[$firstKey]; unset($arrayIn[$firstKey]); return [$firstValue => $this->convertArrayToArborescence($arrayIn, $endValue)]; }
@return array
convertArrayToArborescence
php
lexik/LexikTranslationBundle
Translation/Exporter/JsonExporter.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Translation/Exporter/JsonExporter.php
MIT
public function __construct( private readonly StorageInterface $storage, ) { }
Construct.
__construct
php
lexik/LexikTranslationBundle
Translation/Loader/DatabaseLoader.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Translation/Loader/DatabaseLoader.php
MIT
public function __construct( private array $loaders, private readonly StorageInterface $storage, private readonly TransUnitManagerInterface $transUnitManager, private readonly FileManagerInterface $fileManager, ) { $this->caseInsensitiveInsert = false; $this->skippedKeys = []; }
Construct.
__construct
php
lexik/LexikTranslationBundle
Translation/Importer/FileImporter.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Translation/Importer/FileImporter.php
MIT
public function setCaseInsensitiveInsert($value) { $this->caseInsensitiveInsert = (bool)$value; }
@param boolean $value
setCaseInsensitiveInsert
php
lexik/LexikTranslationBundle
Translation/Importer/FileImporter.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Translation/Importer/FileImporter.php
MIT
public function getSkippedKeys() { return $this->skippedKeys; }
@return array
getSkippedKeys
php
lexik/LexikTranslationBundle
Translation/Importer/FileImporter.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Translation/Importer/FileImporter.php
MIT
public function onGetDatabaseResources(GetDatabaseResourcesEvent $event) { // prevent errors on command such as cache:clear if doctrine schema has not been updated yet if (StorageInterface::STORAGE_ORM == $this->storageType && !$this->storage->translationsTablesExist()) { $resources = []; } else { $resources = $this->storage->getTransUnitDomainsByLocale(); } $event->setResources($resources); }
Query the database to get translation resources and set it on the event.
onGetDatabaseResources
php
lexik/LexikTranslationBundle
EventDispatcher/GetDatabaseResourcesListener.php
https://github.com/lexik/LexikTranslationBundle/blob/master/EventDispatcher/GetDatabaseResourcesListener.php
MIT
private function isCacheExpired() { if (empty($this->cacheInterval)) { return true; } $cache_file = $this->cacheDirectory.'/translations/cache_timestamp'; $cache_dir =$this->cacheDirectory.'/translations'; if ('\\' === DIRECTORY_SEPARATOR) { $cache_file = strtr($cache_file, '/', '\\'); $cache_dir = strtr($cache_dir, '/', '\\'); } if (!\is_dir($cache_dir)) { \mkdir($cache_dir); } if (!\file_exists($cache_file)) { \touch($cache_file); return true; } $expired = false; if ((\time() - \filemtime($cache_file)) > $this->cacheInterval) { \file_put_contents($cache_file, \time()); $expired = true; } return $expired; }
Checks if cache has expired @return boolean
isCacheExpired
php
lexik/LexikTranslationBundle
EventDispatcher/CleanTranslationCacheListener.php
https://github.com/lexik/LexikTranslationBundle/blob/master/EventDispatcher/CleanTranslationCacheListener.php
MIT
public function setResources($resources) { $this->resources = $resources; }
Set database resources. @param $resources
setResources
php
lexik/LexikTranslationBundle
EventDispatcher/Event/GetDatabaseResourcesEvent.php
https://github.com/lexik/LexikTranslationBundle/blob/master/EventDispatcher/Event/GetDatabaseResourcesEvent.php
MIT
public function getResources() { return $this->resources; }
Get database resources. @return array
getResources
php
lexik/LexikTranslationBundle
EventDispatcher/Event/GetDatabaseResourcesEvent.php
https://github.com/lexik/LexikTranslationBundle/blob/master/EventDispatcher/Event/GetDatabaseResourcesEvent.php
MIT
public function __construct(protected LocaleManagerInterface $localeManager, protected $storage) { }
Constructor. @param string $storage
__construct
php
lexik/LexikTranslationBundle
Util/DataGrid/DataGridFormatter.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Util/DataGrid/DataGridFormatter.php
MIT
public function createSingleResponse(mixed $transUnit) { return new JsonResponse($this->formatOne($transUnit)); }
Returns a JSON response with formatted data. @return \Symfony\Component\HttpFoundation\JsonResponse
createSingleResponse
php
lexik/LexikTranslationBundle
Util/DataGrid/DataGridFormatter.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Util/DataGrid/DataGridFormatter.php
MIT
public function setCreateMissing($createMissing) { $this->createMissing = (bool) $createMissing; }
@param bool $createMissing
setCreateMissing
php
lexik/LexikTranslationBundle
Util/DataGrid/DataGridRequestHandler.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Util/DataGrid/DataGridRequestHandler.php
MIT
public function setDefaultFileFormat($format) { $this->defaultFileFormat = $format; }
@param string $format
setDefaultFileFormat
php
lexik/LexikTranslationBundle
Util/DataGrid/DataGridRequestHandler.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Util/DataGrid/DataGridRequestHandler.php
MIT
public function getPage(Request $request) { $parameters = $this->fixParameters($request->query->all()); $transUnits = $this->storage->getTransUnitList( $this->localeManager->getLocales(), $request->query->get('rows', 20), $request->query->get('page', 1), $parameters ); $count = $this->storage->countTransUnits($this->localeManager->getLocales(), $parameters); return [$transUnits, $count]; }
Returns an array with the trans unit for the current page and the total of trans units @return array
getPage
php
lexik/LexikTranslationBundle
Util/DataGrid/DataGridRequestHandler.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Util/DataGrid/DataGridRequestHandler.php
MIT
public function getPageByToken(Request $request, $token) { [$transUnits, $count] = $this->getByToken($token); $parameters = $this->fixParameters($request->query->all()); return $this->filterTokenTranslations($transUnits, $count, $parameters); }
Returns an array with the trans unit for the current profile page. @param string $token @return array
getPageByToken
php
lexik/LexikTranslationBundle
Util/DataGrid/DataGridRequestHandler.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Util/DataGrid/DataGridRequestHandler.php
MIT
protected function checkCsrf($id = 'lexik-translation', $query = '_token') { if (!$this->tokenManager) { return; } if (!$this->isCsrfTokenValid($id, $this->requestStack->getCurrentRequest()->get($query))) { throw $this->createAccessDeniedException('Invalid CSRF token'); } }
Checks the validity of a CSRF token. @param string $id The id used when generating the token @param string $query
checkCsrf
php
lexik/LexikTranslationBundle
Util/Csrf/CsrfCheckerTrait.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Util/Csrf/CsrfCheckerTrait.php
MIT
public function find($ip = null, $url = null, $limit = null, $method = null, $start = null, $end = null) { $limit = $limit ?: $this->defaultLimit; return $this->profiler->find($ip, $url, $limit, $method, $start, $end); }
@param string $ip @param string $url @param int $limit @param string $method @param string $start @param string $end @return array
find
php
lexik/LexikTranslationBundle
Util/Profiler/TokenFinder.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Util/Profiler/TokenFinder.php
MIT
public function __construct( private readonly StorageInterface $storage, private $rootDir, ) { }
Construct. @param string $rootDir
__construct
php
lexik/LexikTranslationBundle
Manager/FileManager.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Manager/FileManager.php
MIT
protected function generateHash($name, $relativePath) { return md5($relativePath . DIRECTORY_SEPARATOR . $name); }
Returns the has for the given file. @param string $name @param string $relativePath @return string
generateHash
php
lexik/LexikTranslationBundle
Manager/FileManager.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Manager/FileManager.php
MIT
protected function getFileRelativePath($filePath) { $commonParts = []; // replace window \ to work with / $rootDir = (str_contains($this->rootDir, '\\')) ? str_replace('\\', '/', $this->rootDir) : $this->rootDir; $antiSlash = false; if (str_contains($filePath, '\\')) { $filePath = str_replace('\\', '/', $filePath); $antiSlash = true; } $rootDirParts = explode('/', $rootDir); $filePathParts = explode('/', $filePath); $i = 0; while ($i < count($rootDirParts)) { if (isset($rootDirParts[$i], $filePathParts[$i]) && $rootDirParts[$i] == $filePathParts[$i]) { $commonParts[] = $rootDirParts[$i]; } $i++; } $filePath = str_replace(implode('/', $commonParts) . '/', '', $filePath); $nbCommonParts = count($commonParts); $nbRootParts = count($rootDirParts); for ($i = $nbCommonParts; $i < $nbRootParts; $i++) { $filePath = '../' . $filePath; } return $antiSlash ? str_replace('/', '\\', $filePath) : $filePath; }
Returns the relative according to the kernel.root_dir value. @param string $filePath @return string
getFileRelativePath
php
lexik/LexikTranslationBundle
Manager/FileManager.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Manager/FileManager.php
MIT
public function __construct( protected array $managedLocales ) { }
Constructor
__construct
php
lexik/LexikTranslationBundle
Manager/LocaleManager.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Manager/LocaleManager.php
MIT
public function getLocales() { return $this->managedLocales; }
@return array
getLocales
php
lexik/LexikTranslationBundle
Manager/LocaleManager.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Manager/LocaleManager.php
MIT
public function getTranslationFile(TransUnitInterface &$transUnit, string $locale) { $file = null; foreach ($transUnit->getTranslations() as $translation) { if (null !== $file = $translation->getFile()) { break; } } //if we found a file if ($file !== null) { //make sure we got the correct file for this locale and domain $name = sprintf('%s.%s.%s', $file->getDomain(), $locale, $file->getExtention()); $file = $this->fileManager->getFor($name, $this->kernelRootDir . DIRECTORY_SEPARATOR . $file->getPath()); } return $file; }
Get the proper File for this TransUnit and locale
getTranslationFile
php
lexik/LexikTranslationBundle
Manager/TransUnitManager.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Manager/TransUnitManager.php
MIT
public function delete(TransUnitInterface $transUnit) { try { $this->storage->remove($transUnit); $this->storage->flush(); return true; } catch (\Exception) { return false; } }
@return bool
delete
php
lexik/LexikTranslationBundle
Manager/TransUnitManager.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Manager/TransUnitManager.php
MIT
public function deleteTranslation(TransUnitInterface $transUnit, $locale) { try { $translation = $transUnit->getTranslation($locale); $this->storage->remove($translation); $this->storage->flush(); return true; } catch (\Exception) { return false; } }
@param string $locale @return bool
deleteTranslation
php
lexik/LexikTranslationBundle
Manager/TransUnitManager.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Manager/TransUnitManager.php
MIT
public function listAction(Request $request) { [$transUnits, $count] = $this->dataGridRequestHandler->getPage($request); return $this->dataGridFormatter->createListResponse($transUnits, $count); }
@return \Symfony\Component\HttpFoundation\JsonResponse
listAction
php
lexik/LexikTranslationBundle
Controller/RestController.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Controller/RestController.php
MIT
public function listByProfileAction(Request $request, $token) { [$transUnits, $count] = $this->dataGridRequestHandler->getPageByToken($request, $token); return $this->dataGridFormatter->createListResponse($transUnits, $count); }
@param $token @return \Symfony\Component\HttpFoundation\JsonResponse
listByProfileAction
php
lexik/LexikTranslationBundle
Controller/RestController.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Controller/RestController.php
MIT
public function updateAction(Request $request, $id) { $this->checkCsrf(); $transUnit = $this->dataGridRequestHandler->updateFromRequest($id, $request); return $this->dataGridFormatter->createSingleResponse($transUnit); }
@param integer $id @return \Symfony\Component\HttpFoundation\JsonResponse @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
updateAction
php
lexik/LexikTranslationBundle
Controller/RestController.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Controller/RestController.php
MIT
public function deleteAction($id) { $this->checkCsrf(); $transUnit = $this->translationStorage->getTransUnitById($id); if (!$transUnit) { throw $this->createNotFoundException(sprintf('No TransUnit found for id "%s".', $id)); } $deleted = $this->transUnitManager->delete($transUnit); return new JsonResponse(['deleted' => $deleted], $deleted ? 200 : 400); }
@param integer $id @return \Symfony\Component\HttpFoundation\JsonResponse @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
deleteAction
php
lexik/LexikTranslationBundle
Controller/RestController.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Controller/RestController.php
MIT
public function deleteTranslationAction($id, $locale) { $this->checkCsrf(); $transUnit = $this->translationStorage->getTransUnitById($id); if (!$transUnit) { throw $this->createNotFoundException(sprintf('No TransUnit found for id "%s".', $id)); } $deleted = $this->transUnitManager->deleteTranslation($transUnit, $locale); return new JsonResponse(['deleted' => $deleted], $deleted ? 200 : 400); }
@param integer $id @param string $locale @return \Symfony\Component\HttpFoundation\JsonResponse @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
deleteTranslationAction
php
lexik/LexikTranslationBundle
Controller/RestController.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Controller/RestController.php
MIT
public function invalidateCacheAction(Request $request) { $this->lexikTranslator->removeLocalesCacheFiles($this->getManagedLocales()); $message = $this->translator->trans('translations.cache_removed', [], 'LexikTranslationBundle'); if ($request->isXmlHttpRequest()) { $this->checkCsrf(); return new JsonResponse(['message' => $message]); } $request->getSession()->getFlashBag()->add('success', $message); return $this->redirect($this->generateUrl('lexik_translation_grid')); }
Remove cache files for managed locales. @return \Symfony\Component\HttpFoundation\RedirectResponse
invalidateCacheAction
php
lexik/LexikTranslationBundle
Controller/TranslationController.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Controller/TranslationController.php
MIT
protected function getManagedLocales() { return $this->localeManager->getLocales(); }
Returns managed locales. @return array
getManagedLocales
php
lexik/LexikTranslationBundle
Controller/TranslationController.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Controller/TranslationController.php
MIT
public function getAllDomains() { $results = $this->createQueryBuilder() ->distinct('domain') ->sort('domain', 'asc') ->hydrate(false) ->getQuery() ->execute(); $domains = []; foreach ($results as $item) { $domains[] = $item; } sort($domains); return $domains; }
Returns all domain available in database. @return array
getAllDomains
php
lexik/LexikTranslationBundle
Document/TransUnitRepository.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Document/TransUnitRepository.php
MIT
public function getAllByLocaleAndDomain($locale, $domain) { $results = $this->createQueryBuilder() ->hydrate(false) ->field('domain')->equals($domain) ->field('translations.locale')->equals($locale) ->sort('key', 'asc') ->getQuery() ->execute(); $values = []; foreach ($results as $item) { $i = 0; $index = null; while ($i < $item['translations'] && null === $index) { if ($item['translations'][$i]['locale'] == $locale) { $index = $i; } $i++; } $item['translations'] = [$item['translations'][$i - 1]]; $values[] = $item; } return $values; }
Returns all trans unit with translations for the given domain and locale. @param string $locale @param string $domain @return array
getAllByLocaleAndDomain
php
lexik/LexikTranslationBundle
Document/TransUnitRepository.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Document/TransUnitRepository.php
MIT
public function getTranslationsForFile(ModelFile $file, $onlyUpdated) { $builder = $this->createQueryBuilder() ->hydrate(false) ->select('key', 'translations') ->field('translations.file.$id')->equals(new ObjectId($file->getId())) ->sort('translations.created_at', 'asc'); $results = $builder->getQuery()->execute(); $translations = []; foreach ($results as $result) { $content = null; $i = 0; while ($i < (is_countable($result['translations']) ? count($result['translations']) : 0) && null === $content) { if ($file->getLocale() == $result['translations'][$i]['locale']) { if ($onlyUpdated) { $updated = ($result['translations'][$i]['createdAt'] < $result['translations'][$i]['updatedAt']); $content = $updated ? $result['translations'][$i]['content'] : null; } else { $content = $result['translations'][$i]['content']; } } $i++; } if (null !== $content) { $translations[$result['key']] = $content; } } return $translations; }
Returns all translations for the given file. @param boolean $onlyUpdated @return array
getTranslationsForFile
php
lexik/LexikTranslationBundle
Document/TransUnitRepository.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Document/TransUnitRepository.php
MIT
protected function addTransUnitFilters(Builder $builder, ?array $filters = null) { if (isset($filters['_search']) && $filters['_search']) { if (!empty($filters['domain'])) { $regex = new Regex($filters['domain'], 'i'); $builder->addAnd($builder->expr()->field('domain')->equals($regex)); } if (!empty($filters['key'])) { $regex = new Regex($filters['key'], 'i'); $builder->addAnd($builder->expr()->field('key')->equals($regex)); } } }
Add conditions according to given filters.
addTransUnitFilters
php
lexik/LexikTranslationBundle
Document/TransUnitRepository.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Document/TransUnitRepository.php
MIT
protected function addTranslationFilter(Builder $builder, ?array $locales = null, ?array $filters = null) { if (null !== $locales) { $qb = $this->createQueryBuilder() ->hydrate(false) ->distinct('id') ->field('translations.locale')->in($locales); foreach ($locales as $locale) { if (!empty($filters[$locale])) { $regex = new Regex($filters[$locale], 'i'); $builder->addAnd( $builder->expr() ->field('translations.content')->equals($regex) ->field('translations.locale')->equals($locale) ); } } $ids = $qb->getQuery()->execute(); //$ids = iterator_to_array($ids); if (($ids === null ? 0 : count($ids)) > 0) { $builder->field('id')->in($ids); } } }
Add conditions according to given filters.
addTranslationFilter
php
lexik/LexikTranslationBundle
Document/TransUnitRepository.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Document/TransUnitRepository.php
MIT
public function getLatestTranslationUpdatedAt() { $result = $this->createQueryBuilder() ->hydrate(false) ->select('translations.updatedAt') ->sort('translations.updatedAt', 'desc') ->limit(1) ->getQuery() ->getSingleResult(); if (!isset($result['translations'], $result['translations'][0])) { return null; } return new \DateTime(date('Y-m-d H:i:s', $result['translations'][0]['updated_at']->sec)); }
@return \DateTime|null
getLatestTranslationUpdatedAt
php
lexik/LexikTranslationBundle
Document/TransUnitRepository.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Document/TransUnitRepository.php
MIT
public function countByDomains() { $reduce = <<<FCT function (obj, prev) { if (typeof(prev.count) == 'undefined') { prev.count = {}; } if (!prev.count.hasOwnProperty(obj.domain)) { prev.count[obj.domain] = 1; } else { prev.count[obj.domain]++; } } FCT; $results = $this->createQueryBuilder() ->group([], []) // @todo: group and reduce won't work anymore, but this method seems to be untested ->reduce($reduce) ->hydrate(false) ->getQuery() ->execute(); return $results[0]['count'] ?? []; }
@return array
countByDomains
php
lexik/LexikTranslationBundle
Document/TransUnitRepository.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Document/TransUnitRepository.php
MIT
public function countTranslationsByLocales($domain) { $reduce = <<<FCT function (obj, prev) { if (typeof(prev.count) == 'undefined') { prev.count = {}; } if (obj.translations) { obj.translations.forEach(function (translation) { if (!prev.count.hasOwnProperty(translation.locale)) { prev.count[translation.locale] = 1; } else { prev.count[translation.locale]++; } }); } } FCT; $results = $this->createQueryBuilder() ->field('domain')->equals($domain) ->group([], []) // @todo: won't work, untested ->reduce($reduce) ->hydrate(false) ->getQuery() ->execute(); return $results[0]['count'] ?? []; }
@param string $domain @return array
countTranslationsByLocales
php
lexik/LexikTranslationBundle
Document/TransUnitRepository.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Document/TransUnitRepository.php
MIT
protected function getFilesToExport() { $locales = $this->input->getOption('locales') ? explode(',', (string)$this->input->getOption('locales')) : []; $domains = $this->input->getOption('domains') ? explode(',', (string)$this->input->getOption('domains')) : []; return $this->storage->getFilesByLocalesAndDomains($locales, $domains); }
Returns all file to export. @return array
getFilesToExport
php
lexik/LexikTranslationBundle
Command/ExportTranslationsCommand.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Command/ExportTranslationsCommand.php
MIT
protected function exportFile(FileInterface $file) { $rootDir = $this->input->getOption('export-path') ? $this->input->getOption('export-path') . '/' : $this->projectDir; $this->output->writeln(sprintf('<info># Exporting "%s/%s":</info>', $file->getPath(), $file->getName())); $override = $this->input->getOption('override'); if (!$this->input->getOption('export-path')) { // we only export updated translations in case of the file is located in vendor/ if ($override) { $onlyUpdated = ('Resources/translations' !== $file->getPath()); } else { $onlyUpdated = (str_contains((string)$file->getPath(), 'vendor/')); } } else { $onlyUpdated = !$override; } $translations = $this->storage->getTranslationsFromFile($file, $onlyUpdated); if (count($translations) < 1) { $this->output->writeln('<comment>No translations to export.</comment>'); return; } $format = $this->input->getOption('format') ?: $file->getExtention(); // we don't write vendors file, translations will be exported in %kernel.root_dir%/Resources/translations if (str_contains((string)$file->getPath(), 'vendor/') || $override) { $outputPath = sprintf('%s/Resources/translations', $rootDir); } else { $outputPath = sprintf('%s/%s', $rootDir, $file->getPath()); } $this->output->writeln(sprintf('<info># OutputPath "%s":</info>', $outputPath)); // ensure the path exists if ($this->input->getOption('export-path')) { if (!$this->fileSystem->exists($outputPath)) { $this->fileSystem->mkdir($outputPath); } } $outputFile = sprintf('%s/%s.%s.%s', $outputPath, $file->getDomain(), $file->getLocale(), $format); $this->output->writeln(sprintf('<info># OutputFile "%s":</info>', $outputFile)); $translations = $this->mergeExistingTranslations($file, $outputFile, $translations); $this->doExport($outputFile, $translations, $format); }
Get translations to export and export translations into a file.
exportFile
php
lexik/LexikTranslationBundle
Command/ExportTranslationsCommand.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Command/ExportTranslationsCommand.php
MIT
protected function mergeExistingTranslations($file, $outputFile, $translations) { if (file_exists($outputFile)) { $extension = pathinfo($outputFile, PATHINFO_EXTENSION); $loader = $this->translator->getLoader($extension); $messageCatalogue = $loader->load($outputFile, $file->getLocale(), $file->getDomain()); $translations = array_merge($messageCatalogue->all($file->getDomain()), $translations); } return $translations; }
If the output file exists we merge existing translations with those from the database. @param FileInterface $file @param string $outputFile @param array $translations @return array
mergeExistingTranslations
php
lexik/LexikTranslationBundle
Command/ExportTranslationsCommand.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Command/ExportTranslationsCommand.php
MIT
protected function doExport($outputFile, $translations, $format) { $this->output->writeln(sprintf('<comment>Output file: %s</comment>', $outputFile)); $this->output->write(sprintf('<comment>%d translations to export: </comment>', count($translations))); try { $exported = $this->exporterCollector->export( $format, $outputFile, $translations ); $this->output->writeln($exported ? '<comment>success</comment>' : '<error>fail</error>'); } catch (\Exception $e) { $this->output->writeln(sprintf('<error>"%s"</error>', $e->getMessage())); } }
Export translations. @param string $outputFile @param array $translations @param string $format
doExport
php
lexik/LexikTranslationBundle
Command/ExportTranslationsCommand.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Command/ExportTranslationsCommand.php
MIT
public function __construct( private readonly TranslatorInterface $translator, private readonly LocaleManagerInterface $localeManager, private readonly FileImporter $fileImporter, ) { parent::__construct(); }
@param TranslatorInterface $translator
__construct
php
lexik/LexikTranslationBundle
Command/ImportTranslationsCommand.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Command/ImportTranslationsCommand.php
MIT
protected function checkOptions() { if ($this->input->getOption('only-vendors') && $this->input->getOption('globals')) { throw new LogicException('You cannot use "globals" and "only-vendors" at the same time.'); } if ($this->input->getOption('import-path') && ($this->input->getOption('globals') || $this->input->getOption('merge') || $this->input->getOption('only-vendors'))) { throw new LogicException('You cannot use "globals", "merge" or "only-vendors" and "import-path" at the same time.'); } }
Checks if given options are compatible.
checkOptions
php
lexik/LexikTranslationBundle
Command/ImportTranslationsCommand.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Command/ImportTranslationsCommand.php
MIT
protected function importTranslationFilesFromPath($path, array $locales, array $domains) { $finder = $this->findTranslationsFiles($path, $locales, $domains, false); $this->importTranslationFiles($finder); }
@param string $path
importTranslationFilesFromPath
php
lexik/LexikTranslationBundle
Command/ImportTranslationsCommand.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Command/ImportTranslationsCommand.php
MIT
protected function importAppTranslationFiles(array $locales, array $domains) { if (Kernel::MAJOR_VERSION >= 4) { $translationPath = $this->getApplication()->getKernel()->getProjectDir() . '/translations'; $finder = $this->findTranslationsFiles($translationPath, $locales, $domains, false); } else { $finder = $this->findTranslationsFiles($this->getApplication()->getKernel()->getRootDir(), $locales, $domains); } $this->importTranslationFiles($finder); }
Imports application translation files.
importAppTranslationFiles
php
lexik/LexikTranslationBundle
Command/ImportTranslationsCommand.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Command/ImportTranslationsCommand.php
MIT
protected function importBundleTranslationFiles(BundleInterface $bundle, $locales, $domains, $global = false) { $path = $bundle->getPath(); if ($global) { $kernel = $this->getApplication()->getKernel(); if (Kernel::MAJOR_VERSION >= 4) { $path = $kernel->getProjectDir() . '/app'; } else { $path = $kernel->getRootDir(); } $path .= '/Resources/' . $bundle->getName() . '/translations'; $this->output->writeln('<info>*** Importing ' . $bundle->getName() . '`s translation files from ' . $path . ' ***</info>'); } $this->output->writeln(sprintf('<info># %s:</info>', $bundle->getName())); $finder = $this->findTranslationsFiles($path, $locales, $domains); $this->importTranslationFiles($finder); }
Imports translation files form the specific bundles. @param array $locales @param array $domains @param boolean $global
importBundleTranslationFiles
php
lexik/LexikTranslationBundle
Command/ImportTranslationsCommand.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Command/ImportTranslationsCommand.php
MIT
protected function findTranslationsFiles($path, array $locales, array $domains, $autocompletePath = true) { $finder = null; if (preg_match('#^win#i', PHP_OS)) { $path = preg_replace('#' . preg_quote(DIRECTORY_SEPARATOR, '#') . '#', '/', $path); } if (true === $autocompletePath) { $dir = (str_starts_with((string) $path, $this->getApplication()->getKernel()->getProjectDir() . '/Resources')) ? $path : $path . '/Resources/translations'; } else { $dir = $path; } $this->output->writeln('<info>*** Using dir ' . $dir . ' to lookup translation files. ***</info>'); if (is_dir($dir)) { $finder = new Finder(); $finder->files() ->name($this->getFileNamePattern($locales, $domains)) ->in($dir); } return (null !== $finder && $finder->count() > 0) ? $finder : null; }
Return a Finder object if $path has a Resources/translations folder. @param string $path @return Finder
findTranslationsFiles
php
lexik/LexikTranslationBundle
Command/ImportTranslationsCommand.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Command/ImportTranslationsCommand.php
MIT
protected function getFileNamePattern(array $locales, array $domains) { $formats = $this->translator->getFormats(); if (count($domains)) { $regex = sprintf('/((%s)\.(%s)\.(%s))/', implode('|', $domains), implode('|', $locales), implode('|', $formats)); } else { $regex = sprintf('/(.*\.(%s)\.(%s))/', implode('|', $locales), implode('|', $formats)); } return $regex; }
@return string
getFileNamePattern
php
lexik/LexikTranslationBundle
Command/ImportTranslationsCommand.php
https://github.com/lexik/LexikTranslationBundle/blob/master/Command/ImportTranslationsCommand.php
MIT
public function __invoke() { if (! method_exists($this, $this->handleMethod)) { throw new RuntimeException(sprintf('`handle` method must be define in (%s)', __CLASS__)); } return app()->call([$this, $this->handleMethod]); }
Call this class.
__invoke
php
vuongxuongminh/laravel-async
src/Invocation.php
https://github.com/vuongxuongminh/laravel-async/blob/master/src/Invocation.php
MIT
public function __construct() { $this->registerComposerAutoload(); $app = $this->makeApplication(); $this->boot($app); }
Turn the light on.
__construct
php
vuongxuongminh/laravel-async
src/Runtime/RuntimeAutoload.php
https://github.com/vuongxuongminh/laravel-async/blob/master/src/Runtime/RuntimeAutoload.php
MIT
protected function getDefaultNamespace($rootNamespace) { return $rootNamespace . '\AsyncJobs'; }
Get the default namespace for the class. @param string $rootNamespace @return string
getDefaultNamespace
php
vuongxuongminh/laravel-async
src/Commands/JobMakeCommand.php
https://github.com/vuongxuongminh/laravel-async/blob/master/src/Commands/JobMakeCommand.php
MIT
public static function create($params = null, $options = null) { self::_validateParams($params); $url = static::classUrl(); list($response, $opts) = static::_staticRequest('post', $url, $params, $options); $obj = Util\Util::convertToStripeObject($response->json, $opts); $obj->setLastResponse($response); return $obj; }
Creates an AccountLink object that includes a single-use Stripe URL that the platform can redirect their user to in order to take them through the Connect Onboarding flow. @param null|array{account: string, collect?: string, collection_options?: array{fields?: string, future_requirements?: string}, expand?: string[], refresh_url?: string, return_url?: string, type: string} $params @param null|array|string $options @return AccountLink the created resource @throws Exception\ApiErrorException if the request fails
create
php
stripe/stripe-php
lib/AccountLink.php
https://github.com/stripe/stripe-php/blob/master/lib/AccountLink.php
MIT
public function getApiKey() { return $this->config['api_key']; }
Gets the API key used by the client to send requests. @return null|string the API key used by the client to send requests
getApiKey
php
stripe/stripe-php
lib/BaseStripeClient.php
https://github.com/stripe/stripe-php/blob/master/lib/BaseStripeClient.php
MIT
public function getClientId() { return $this->config['client_id']; }
Gets the client ID used by the client in OAuth requests. @return null|string the client ID used by the client in OAuth requests
getClientId
php
stripe/stripe-php
lib/BaseStripeClient.php
https://github.com/stripe/stripe-php/blob/master/lib/BaseStripeClient.php
MIT
public function getApiBase() { return $this->config['api_base']; }
Gets the base URL for Stripe's API. @return string the base URL for Stripe's API
getApiBase
php
stripe/stripe-php
lib/BaseStripeClient.php
https://github.com/stripe/stripe-php/blob/master/lib/BaseStripeClient.php
MIT
public function getConnectBase() { return $this->config['connect_base']; }
Gets the base URL for Stripe's OAuth API. @return string the base URL for Stripe's OAuth API
getConnectBase
php
stripe/stripe-php
lib/BaseStripeClient.php
https://github.com/stripe/stripe-php/blob/master/lib/BaseStripeClient.php
MIT
public function getFilesBase() { return $this->config['files_base']; }
Gets the base URL for Stripe's Files API. @return string the base URL for Stripe's Files API
getFilesBase
php
stripe/stripe-php
lib/BaseStripeClient.php
https://github.com/stripe/stripe-php/blob/master/lib/BaseStripeClient.php
MIT
public function getMeterEventsBase() { return $this->config['meter_events_base']; }
Gets the base URL for Stripe's Meter Events API. @return string the base URL for Stripe's Meter Events API
getMeterEventsBase
php
stripe/stripe-php
lib/BaseStripeClient.php
https://github.com/stripe/stripe-php/blob/master/lib/BaseStripeClient.php
MIT