예제 #1
0
 /**
  * @param CM_Frontend_Render $render
  * @throws CM_Exception
  */
 public function __construct(CM_Frontend_Render $render)
 {
     parent::__construct($render);
     $this->addVariables();
     $file = new CM_File(DIR_PUBLIC . 'static/css/library/icon.less');
     if ($file->exists()) {
         $this->add($file->read());
     }
     foreach (array_reverse($render->getSite()->getModules()) as $moduleName) {
         foreach (array_reverse($render->getSite()->getThemes()) as $theme) {
             foreach (CM_Util::rglob('*.less', $render->getThemeDir(true, $theme, $moduleName) . 'css/') as $path) {
                 $file = new CM_File($path);
                 $this->add($file->read());
             }
         }
     }
     $viewClasses = CM_View_Abstract::getClassChildren(true);
     foreach ($viewClasses as $viewClassName) {
         $validModule = in_array(CM_Util::getNamespace($viewClassName), $render->getSite()->getModules());
         $validViewClass = $this->_isValidViewClass($viewClassName);
         if ($validModule && $validViewClass) {
             $asset = new CM_Asset_Css_View($this->_render, $viewClassName);
             $this->add($asset->_getContent());
         }
     }
 }
예제 #2
0
파일: Cli.php 프로젝트: cargomedia/cm
 public function iconRefresh()
 {
     /** @var CM_File[] $svgFileList */
     $svgFileList = array();
     foreach (CM_Bootloader::getInstance()->getModules() as $moduleName) {
         $iconPath = CM_Util::getModulePath($moduleName) . 'layout/default/resource/img/icon/';
         foreach (glob($iconPath . '*.svg') as $svgPath) {
             $svgFile = new CM_File($svgPath);
             $svgFileList[strtolower($svgFile->getFileName())] = $svgFile;
         }
     }
     if (0 === count($svgFileList)) {
         throw new CM_Exception_Invalid('Cannot process `0` icons');
     }
     $this->_getStreamOutput()->writeln('Processing ' . count($svgFileList) . ' unique icons...');
     $dirWork = CM_File::createTmpDir();
     $dirBuild = $dirWork->joinPath('/build');
     foreach ($svgFileList as $fontFile) {
         $fontFile->copyToFile($dirWork->joinPath($fontFile->getFileName()));
     }
     CM_Util::exec('fontcustom', array('compile', $dirWork->getPathOnLocalFilesystem(), '--no-hash', '--autowidth', '--font-name=icon-webfont', '--output=' . $dirBuild->getPathOnLocalFilesystem()));
     $cssFile = $dirBuild->joinPath('/icon-webfont.css');
     $less = preg_replace('/url\\("(?:.*?\\/)(.+?)(\\??#.+?)?"\\)/', 'url(urlFont("\\1") + "\\2")', $cssFile->read());
     CM_File::create(DIR_PUBLIC . 'static/css/library/icon.less', $less);
     foreach (glob($dirBuild->joinPath('/icon-webfont.*')->getPathOnLocalFilesystem()) as $fontPath) {
         $fontFile = new CM_File($fontPath);
         $fontFile->rename(DIR_PUBLIC . 'static/font/' . $fontFile->getFileName());
     }
     $dirWork->delete(true);
     $this->_getStreamOutput()->writeln('Created web-font and stylesheet.');
 }
예제 #3
0
 /**
  * @param CM_OutputStream_Interface $output
  * @param CM_File_Filesystem        $backupFilesystem
  */
 public function verifyExport(CM_OutputStream_Interface $output, CM_File_Filesystem $backupFilesystem)
 {
     $asserter = new S3Export_Asserter();
     $sourceFilesystem = $this->_getFilesystemOriginal();
     $filePaths = $this->_getRandomFiles($backupFilesystem, 100, 100000);
     foreach ($filePaths as $path) {
         $backupFile = new CM_File($path, $backupFilesystem);
         $sourceFile = new CM_File($path, $sourceFilesystem);
         $asserter->assertThat($sourceFile->exists(), function () use($output) {
             $output->write(".");
         }, function () use($output, $backupFile) {
             $output->writeln('E');
             $output->writeln("Integrity mismatch: Corresponding backup file does not exist for {$backupFile->getPath()}");
         });
         if ($sourceFile->exists()) {
             $asserter->assertThat($sourceFile->getHash() === $backupFile->getHash(), function () use($output) {
                 $output->write('.');
             }, function () use($output, $backupFile) {
                 $output->writeln('E');
                 $output->writeln("Integrity mismatch: Different hashes for {$backupFile->getPath()}");
             });
         }
     }
     $output->writeln('');
     $output->writeln(join(', ', ["Assertions run: {$asserter->getAssertionCount()}", "succeeded: {$asserter->getAssertionSuccessCount()}", "failed: {$asserter->getAssertionFailCount()}"]));
 }
예제 #4
0
파일: Cli.php 프로젝트: NicolasSchmutz/cm
 /**
  * @param int     $streamChannelId
  * @param CM_File $archiveSource
  */
 public function importVideoArchive($streamChannelId, CM_File $archiveSource)
 {
     $streamChannelArchive = new CM_Model_StreamChannelArchive_Video($streamChannelId);
     $archiveDestination = $streamChannelArchive->getVideo();
     $archiveDestination->ensureParentDirectory();
     $archiveSource->copyToFile($archiveDestination);
 }
예제 #5
0
 public function testGetSetRuntime()
 {
     $defaultTimeZoneBackup = date_default_timezone_get();
     $interval = '1 day';
     $timezone = new DateTimeZone('Europe/Berlin');
     $event1 = new CM_Clockwork_Event('foo', $interval);
     $event2 = new CM_Clockwork_Event('bar', $interval);
     $date1 = new DateTime('2014-10-31 08:00:00', $timezone);
     $date2 = new DateTime('2014-10-31 08:02:03', $timezone);
     $context = 'persistence-test';
     $storage = new CM_Clockwork_Storage_FileSystem($context);
     $serviceManager = CM_Service_Manager::getInstance();
     $storage->setServiceManager($serviceManager);
     $filepath = 'clockwork/' . md5($context) . '.json';
     $file = new CM_File($filepath, $serviceManager->getFilesystems()->getData());
     $this->assertFalse($file->exists());
     $this->assertFalse($file->getParentDirectory()->exists());
     $storage->setRuntime($event1, $date1);
     $this->assertTrue($file->getParentDirectory()->exists());
     $this->assertTrue($file->exists());
     $storage->setRuntime($event2, $date2);
     date_default_timezone_set('Antarctica/Vostok');
     $storage = new CM_Clockwork_Storage_FileSystem($context);
     $storage->setServiceManager($serviceManager);
     $this->assertEquals($date1, $storage->getLastRuntime($event1));
     $this->assertEquals($date2, $storage->getLastRuntime($event2));
     date_default_timezone_set($defaultTimeZoneBackup);
 }
예제 #6
0
파일: Upload.php 프로젝트: cargomedia/cm
 protected function _process()
 {
     $return = array();
     try {
         $fileInfo = reset($_FILES);
         if (empty($fileInfo)) {
             throw new CM_Exception('Invalid file upload');
         }
         if (isset($fileInfo['error']) && $fileInfo['error'] !== UPLOAD_ERR_OK) {
             throw new CM_Exception('File upload error: ' . self::$_uploadErrors[$fileInfo['error']]);
         }
         $fileTmp = new CM_File($fileInfo['tmp_name']);
         if ($fileTmp->getSize() > self::MAX_FILE_SIZE) {
             throw new CM_Exception_FormFieldValidation(new CM_I18n_Phrase('File too big'));
         }
         $file = CM_File_UserContent_Temp::create($fileInfo['name'], $fileTmp->read());
         $fileTmp->delete();
         $query = $this->_request->getQuery();
         $preview = null;
         if (isset($query['field'])) {
             $field = CM_FormField_File::factory($query['field'], ['name' => 'file']);
             $field->validateFile($file);
             $preview = $this->getRender()->fetchViewTemplate($field, 'preview', array('file' => $file));
         }
         $return['success'] = array('id' => $file->getUniqid(), 'preview' => $preview);
     } catch (CM_Exception_FormFieldValidation $ex) {
         $return['error'] = array('type' => get_class($ex), 'msg' => $ex->getMessagePublic($this->getRender()));
     }
     $this->_setContent(json_encode($return, JSON_HEX_TAG));
     // JSON decoding in IE-iframe needs JSON_HEX_TAG
 }
예제 #7
0
파일: Cli.php 프로젝트: NicolasSchmutz/cm
 /**
  * @param int|null $deployVersion
  */
 public function setDeployVersion($deployVersion = null)
 {
     $deployVersion = null !== $deployVersion ? (int) $deployVersion : time();
     $sourceCode = join(PHP_EOL, array('<?php', 'return function (CM_Config_Node $config) {', '    $config->deployVersion = ' . $deployVersion . ';', '};', ''));
     $targetPath = DIR_ROOT . 'resources/config/deploy.php';
     $configFile = new CM_File($targetPath);
     $configFile->ensureParentDirectory();
     $configFile->write($sourceCode);
 }
예제 #8
0
파일: Internal.php 프로젝트: cargomedia/cm
 /**
  * @param CM_Site_Abstract $site
  * @return string
  * @throws CM_Exception_Invalid
  */
 private function _getAppClassName(CM_Site_Abstract $site)
 {
     foreach ($site->getModules() as $moduleName) {
         $file = new CM_File(DIR_ROOT . CM_Bootloader::getInstance()->getModulePath($moduleName) . 'library/' . $moduleName . '/App.js');
         if ($file->exists()) {
             return $moduleName . '_App';
         }
     }
     throw new CM_Exception_Invalid('No App class found');
 }
예제 #9
0
파일: Css.php 프로젝트: NicolasSchmutz/cm
 public function addVariables()
 {
     foreach (array_reverse($this->_render->getSite()->getModules()) as $moduleName) {
         foreach (array_reverse($this->_render->getSite()->getThemes()) as $theme) {
             $file = new CM_File($this->_render->getThemeDir(true, $theme, $moduleName) . 'variables.less');
             if ($file->exists()) {
                 $this->add($file->read());
             }
         }
     }
 }
예제 #10
0
 public function setUp()
 {
     CM_Db_Db::exec('ALTER TABLE cm_model_location_ip AUTO_INCREMENT = 1');
     CM_Db_Db::exec('ALTER TABLE cm_model_location_zip AUTO_INCREMENT = 1');
     CM_Db_Db::exec('ALTER TABLE cm_model_location_city AUTO_INCREMENT = 1');
     CM_Db_Db::exec('ALTER TABLE cm_model_location_state AUTO_INCREMENT = 1');
     CM_Db_Db::exec('ALTER TABLE cm_model_location_country AUTO_INCREMENT = 1');
     $this->_errorStream = new CM_OutputStream_Null();
     $file = new CM_File('/CM_OutputStream_File-' . uniqid(), CM_Service_Manager::getInstance()->getFilesystems()->getTmp());
     $file->truncate();
     $this->_outputStream = new CM_OutputStream_File($file);
 }
예제 #11
0
파일: Factory.php 프로젝트: cargomedia/cm
 /**
  * @param string      $path
  * @param string|null $formatMessage
  * @param string|null $formatDate
  * @param int|null    $minLevel
  * @return CM_Log_Handler_Stream
  */
 public function createFileHandler($path, $formatMessage = null, $formatDate = null, $minLevel = null)
 {
     $path = (string) $path;
     $formatMessage = null !== $formatMessage ? (string) $formatMessage : $formatMessage;
     $formatDate = null !== $formatDate ? (string) $formatDate : $formatDate;
     $filesystem = $this->getServiceManager()->getFilesystems()->getData();
     $file = new CM_File($path, $filesystem);
     $file->ensureParentDirectory();
     $stream = new CM_OutputStream_File($file);
     $formatter = new CM_Log_Formatter_Text($formatMessage, $formatDate);
     return $this->_createStreamHandler($stream, $formatter, $minLevel);
 }
 /**
  * @param CM_File_Filesystem $filesystem
  */
 protected function _fillFilesystemWithRandomFiles(CM_File_Filesystem $filesystem)
 {
     $faker = Faker\Factory::create();
     for ($i = 0; $i < 20; $i++) {
         $directory = $faker->lexify('????????' . $i);
         for ($j = 0; $j < 10; $j++) {
             $path = $faker->lexify('????????' . $j);
             $content = $faker->paragraph(10);
             $file = new CM_File($directory . '/' . $path, $filesystem);
             $file->ensureParentDirectory();
             $file->write($content);
         }
     }
 }
예제 #13
0
 public function __construct(CM_Frontend_Render $render)
 {
     parent::__construct($render);
     $extensions = array('css', 'less');
     foreach (array_reverse($render->getSite()->getModules()) as $moduleName) {
         $libraryPath = DIR_ROOT . CM_Bootloader::getInstance()->getModulePath($moduleName) . 'client-vendor/';
         foreach ($extensions as $extension) {
             foreach (CM_Util::rglob('*.' . $extension, $libraryPath) as $path) {
                 $file = new CM_File($path);
                 $this->add($file->read());
             }
         }
     }
 }
예제 #14
0
파일: CliTest.php 프로젝트: cargomedia/cm
 public function testImportVideoThumbnail()
 {
     $testFile1 = CM_File::create('test1.png', 'foo1', CM_Service_Manager::getInstance()->getFilesystems()->getTmp());
     $testFile2 = CM_File::create('test2.png', 'foo2', CM_Service_Manager::getInstance()->getFilesystems()->getTmp());
     $cli = new CM_MediaStreams_Cli();
     // streamchannel exists
     /** @var CM_Model_StreamChannel_Media $streamChannel */
     $streamChannel = CMTest_TH::createStreamChannel(null, null, 'foobar');
     $this->assertCount(0, $streamChannel->getThumbnails());
     $cli->importVideoThumbnail('foobar', $testFile1, 1234);
     $this->assertCount(1, $streamChannel->getThumbnails());
     /** @var CM_StreamChannel_Thumbnail $thumbnail */
     $thumbnail = $streamChannel->getThumbnails()->getItem(0);
     $this->assertSame(1234, $thumbnail->getCreateStamp());
     $this->assertSame('foo1', $thumbnail->getFile()->read());
     // archive exists
     $archive = CM_Model_StreamChannelArchive_Media::createStatic(['streamChannel' => $streamChannel]);
     $streamChannel->delete();
     $cli->importVideoThumbnail('foobar', $testFile2, 1235);
     $this->assertCount(2, $streamChannel->getThumbnails());
     /** @var CM_StreamChannel_Thumbnail $thumbnail */
     $thumbnail = $archive->getThumbnails()->getItem(1);
     $this->assertSame(1235, $thumbnail->getCreateStamp());
     $this->assertSame('foo2', $thumbnail->getFile()->read());
 }
예제 #15
0
function smarty_function_load(array $params, Smarty_Internal_Template $template)
{
    /** @var CM_Frontend_Render $render */
    $render = $template->smarty->getTemplateVars('render');
    $namespace = isset($params['namespace']) ? $params['namespace'] : null;
    $parse = isset($params['parse']) ? (bool) $params['parse'] : true;
    if ($parse) {
        $tplPath = $render->getLayoutPath($params['file'], $namespace);
        $params = array_merge($template->getTemplateVars(), $params);
        return $render->fetchTemplate($tplPath, $params);
    } else {
        $tplPath = $render->getLayoutPath($params['file'], $namespace, null, true);
        $file = new CM_File($tplPath);
        return $file->read();
    }
}
예제 #16
0
파일: Cli.php 프로젝트: cargomedia/cm
 /**
  * @param string $namespace
  */
 private function _dbToFileSql($namespace)
 {
     $namespace = (string) $namespace;
     $tables = CM_Db_Db::exec("SHOW TABLES LIKE ?", array(strtolower($namespace) . '_%'))->fetchAllColumn();
     sort($tables);
     $dump = CM_Db_Db::getDump($tables, true);
     CM_File::create(CM_Util::getModulePath($namespace) . '/resources/db/structure.sql', $dump);
 }
예제 #17
0
파일: PageTest.php 프로젝트: cargomedia/cm
 public function testFetchDescriptionKeywordsConsiderNamespaceWideLocation()
 {
     $dirTmp = CM_Bootloader::getInstance()->getDirTmp();
     $render = $this->getMockBuilder('CM_Frontend_Render')->setMethods(array('getTemplatePath', 'getLayoutPath'))->getMock();
     $render->expects($this->any())->method('getTemplatePath')->will($this->returnValue(null));
     $render->expects($this->exactly(2))->method('getLayoutPath')->will($this->returnCallback(function ($templateName) use($dirTmp) {
         $templateFile = new CM_File($dirTmp . $templateName);
         $templateFile->ensureParentDirectory();
         $templateFile->write('test-' . $templateName);
         return $templateFile->getPath();
     }));
     /** @var CM_Frontend_Render $render */
     $page = $this->getMockBuilder('CM_Page_Abstract')->getMockForAbstractClass();
     /** @var CM_Page_Abstract $page */
     $renderAdapter = new CM_RenderAdapter_Page($render, $page);
     $this->assertSame('test-Page/Abstract/meta-description.tpl', $renderAdapter->fetchDescription());
     $this->assertSame('test-Page/Abstract/meta-keywords.tpl', $renderAdapter->fetchKeywords());
 }
예제 #18
0
 /**
  * @throws CM_Exception
  */
 public function mount()
 {
     if ($this->isMounted()) {
         return;
     }
     $tmpDir = CM_File::createTmpDir();
     $mountpointPath = (string) $tmpDir->getPathOnLocalFilesystem();
     CM_Util::exec('sudo mount', [$this->_path, $mountpointPath]);
     $this->_waitForMountStatus(true);
 }
예제 #19
0
파일: Cli.php 프로젝트: cargomedia/cm
 /**
  * @param string    $filename
  * @param string    $configJson
  * @param bool|null $merge
  */
 public function setConfig($filename, $configJson, $merge = null)
 {
     $merge = (bool) $merge;
     $configJson = (object) CM_Util::jsonDecode($configJson);
     $configFile = new CM_File(DIR_ROOT . 'resources/config/' . $filename . '.php');
     $config = new CM_Config_Node();
     if ($merge && $configFile->exists()) {
         $config->extendWithFile($configFile);
     }
     $config->extendWithConfig($configJson);
     $configStr = $config->exportAsString('$config');
     $indentation = '    ';
     $indent = function ($content) use($indentation) {
         return preg_replace('/(:?^|[\\n])/', '$1' . $indentation, $content);
     };
     $configFile->ensureParentDirectory();
     $configFile->write(join(PHP_EOL, ['<?php', '// This is autogenerated config file. You should not change it manually.', '', 'return function (CM_Config_Node $config) {', $indent($configStr), '};', '']));
     $this->_getStreamOutput()->writeln('Created `' . $configFile->getPath() . '`');
 }
예제 #20
0
파일: Example.php 프로젝트: cargomedia/cm
 /**
  * @return array
  */
 private function _getColorStyles()
 {
     $site = $this->getParams()->getSite('site');
     $style = '';
     foreach (array_reverse($site->getModules()) as $moduleName) {
         $file = new CM_File(CM_Util::getModulePath($moduleName) . 'layout/default/variables.less');
         if ($file->exists()) {
             $style .= $file->read() . PHP_EOL;
         }
     }
     preg_match_all('#@(color\\w+)#', $style, $matches);
     $colors = array_unique($matches[1]);
     foreach ($colors as $variableName) {
         $style .= '.' . $variableName . ' { background-color: @' . $variableName . '; }' . PHP_EOL;
     }
     $lessCompiler = new lessc();
     $style = $lessCompiler->compile($style);
     preg_match_all('#.(color\\w+)\\s+\\{([^}]+)\\}#', $style, $matches);
     return array_combine($matches[1], $matches[2]);
 }
예제 #21
0
파일: Layout.php 프로젝트: cargomedia/cm
 protected function _process()
 {
     $path = $this->getRequest()->getPath();
     $content = null;
     $mimeType = null;
     if ($pathRaw = $this->getRender()->getLayoutPath('resource/' . $path, null, null, true, false)) {
         $file = new CM_File($pathRaw);
         if (in_array($file->getExtension(), $this->_getFiletypesForbidden())) {
             throw new CM_Exception_Nonexistent('Forbidden filetype', CM_Exception::WARN, ['path' => $path]);
         }
         $content = $file->read();
         $mimeType = $file->getMimeType();
     } elseif ($pathTpl = $this->getRender()->getLayoutPath('resource/' . $path . '.smarty', null, null, true, false)) {
         $content = $this->getRender()->fetchTemplate($pathTpl);
         $mimeType = CM_File::getMimeTypeByContent($content);
     } else {
         throw new CM_Exception_Nonexistent('Invalid filename', CM_Exception::WARN, ['path' => $path]);
     }
     $this->setHeader('Content-Type', $mimeType);
     $this->_setContent($content);
 }
예제 #22
0
 public function testValidateFileNoImage()
 {
     $image = CM_File::createTmp();
     $formField = new CM_FormField_FileImage();
     $exception = $this->catchException(function () use($formField, $image) {
         $formField->validateFile($image);
     });
     $this->assertInstanceOf(CM_Exception_FormFieldValidation::class, $exception);
     $this->assertSame('FormField Validation failed', $exception->getMessage());
     /** @var CM_Exception $exception */
     $this->assertSame('Invalid image', $exception->getMessagePublic(new CM_Frontend_Render()));
 }
예제 #23
0
파일: Cli.php 프로젝트: cargomedia/cm
 /**
  * @param string  $streamChannelMediaId
  * @param CM_File $archiveSource
  * @throws CM_Exception_Invalid
  */
 public function importArchive($streamChannelMediaId, CM_File $archiveSource)
 {
     $streamChannelMediaId = (string) $streamChannelMediaId;
     $streamChannelArchive = CM_Model_StreamChannelArchive_Media::findByMediaId($streamChannelMediaId);
     if (!$streamChannelArchive) {
         $streamChannel = CM_Model_StreamChannel_Media::findByMediaId($streamChannelMediaId);
         if ($streamChannel) {
             throw new CM_Exception_Invalid('Archive not created, please try again later', null, ['streamChannelMediaId' => $streamChannelMediaId]);
         }
         $exception = new CM_Exception_Invalid('Archive not found, stream channel not found, skipping', CM_Exception::WARN, ['streamChannelMediaId' => $streamChannelMediaId]);
         $context = new CM_Log_Context();
         $context->setException($exception);
         $this->getServiceManager()->getLogger()->warning('Archive creating error', $context);
         return;
     }
     $filename = $streamChannelArchive->getId() . '-' . $streamChannelArchive->getHash() . '-original.' . $archiveSource->getExtension();
     $archiveDestination = new CM_File_UserContent('streamChannels', $filename, $streamChannelArchive->getId());
     $archiveDestination->ensureParentDirectory();
     $archiveSource->copyToFile($archiveDestination);
     $streamChannelArchive->setFile($archiveDestination);
 }
예제 #24
0
 /**
  * @param           $manifestPath
  * @param string    $devicePath
  * @param bool|null $skipFormat
  * @param bool|null $dryRun
  */
 public function createJob($manifestPath, $devicePath, $skipFormat = null, $dryRun = null)
 {
     $manifestPath = (string) $manifestPath;
     if (!preg_match('/^\\//', $manifestPath)) {
         $manifestPath = getcwd() . '/' . $manifestPath;
     }
     $devicePath = (string) $devicePath;
     $skipFormat = (bool) $skipFormat;
     $dryRun = (bool) $dryRun;
     $awsBackupManager = $this->_getBackupManager();
     $this->_getStreamOutput()->writeln('Preparing backup device');
     $device = new S3Export_Device($devicePath);
     if (!$skipFormat) {
         $device->format();
     }
     $device->mount();
     $this->_getStreamOutput()->writeln('Creating AWS backup job');
     $manifestFile = new CM_File($manifestPath);
     $job = $awsBackupManager->createJob($manifestFile->read(), $dryRun);
     $this->_getStreamOutput()->writeln("Job created, id: `{$job->getId()}`");
     $this->_getStreamOutput()->writeln('Storing AWS Signature on backup device');
     $awsBackupManager->storeJobSignatureOnDevice($job, $device);
     $device->unmount();
 }
예제 #25
0
 /**
  * @param string                  $namespace
  * @param string                  $filename
  * @param int|null                $sequence
  * @param CM_Service_Manager|null $serviceManager
  */
 public function __construct($namespace, $filename, $sequence = null, CM_Service_Manager $serviceManager = null)
 {
     $namespace = (string) $namespace;
     $filename = (string) $filename;
     if (null !== $sequence) {
         $sequence = (int) $sequence;
     }
     if (null === $serviceManager) {
         $serviceManager = CM_Service_Manager::getInstance();
     }
     $this->_pathRelative = $this->_calculateRelativeDir($namespace, $filename, $sequence);
     $this->_namespace = $namespace;
     $this->setServiceManager($serviceManager);
     $filesystem = $serviceManager->getUserContent()->getFilesystem($this->getNamespace());
     parent::__construct($this->getPathRelative(), $filesystem);
 }
예제 #26
0
 /**
  * @param CM_File     $file
  * @param string|null $content
  * @param bool|null   $overwrite
  */
 public function createFile(CM_File $file, $content = null, $overwrite = null)
 {
     $parentDirectory = $file->getParentDirectory();
     if (!$parentDirectory->exists()) {
         $this->createDirectory($parentDirectory);
     }
     if ($file->exists()) {
         if (!$overwrite) {
             $this->notify('skip', $file->getPath());
         } else {
             $this->notify('modify', $file->getPath());
             $file->write($content);
         }
     } else {
         $this->notify('create', $file->getPath());
         $file->write($content);
     }
 }
예제 #27
0
 /**
  * @runInSeparateProcess
  * @preserveGlobalState disabled
  */
 public function testForkAndWaitForChildren()
 {
     $file = CM_File::createTmp();
     $process = CM_Process::getInstance();
     $parentOutput = [];
     for ($i = 1; $i <= 4; $i++) {
         $parentOutput[] = "Child {$i} forked.";
         $process->fork(function () use($i, $file) {
             $ms = 100 * $i;
             usleep($ms * 1000);
             $file->appendLine("Child {$i} terminated after {$ms} ms.");
         });
     }
     $parentOutput[] = 'Parent waiting for 250 ms...';
     usleep(250000);
     $parentOutput[] = 'Parent listening to children...';
     $process->waitForChildren();
     $parentOutput[] = 'Parent terminated.';
     $childrenOutput = explode(PHP_EOL, $file->read());
     $this->assertSame(['Child 1 forked.', 'Child 2 forked.', 'Child 3 forked.', 'Child 4 forked.', 'Parent waiting for 250 ms...', 'Parent listening to children...', 'Parent terminated.'], $parentOutput);
     $this->assertContainsAll(['Child 2 terminated after 200 ms.', 'Child 1 terminated after 100 ms.', 'Child 3 terminated after 300 ms.', 'Child 4 terminated after 400 ms.'], $childrenOutput);
 }
예제 #28
0
 public function testDeleteByPrefix()
 {
     $filesystem = new CM_File_Filesystem(new CM_File_Filesystem_Adapter_Local());
     $dirTmp = CM_Bootloader::getInstance()->getDirTmp();
     $pathList = array('foo/foobar/bar', 'foo/bar2', 'foo/bar');
     /** @var CM_File[] $fileList */
     $fileList = array();
     foreach ($pathList as $path) {
         $file = new CM_File($dirTmp . $path, $filesystem);
         $file->ensureParentDirectory();
         $file->write('hello');
         $fileList[] = $file;
         $fileList[] = $file->getParentDirectory();
     }
     foreach ($fileList as $file) {
         $this->assertTrue($file->exists());
     }
     $filesystem->deleteByPrefix($dirTmp);
     foreach ($fileList as $file) {
         $this->assertFalse($file->exists());
     }
     $this->assertTrue((new CM_File($dirTmp))->exists());
 }
예제 #29
0
 public function testGetFileNonexistent()
 {
     $fileNonexistent = new CM_File('foo/bar');
     $params = new CM_Params(array('nonexistent' => $fileNonexistent->getPath()));
     $this->assertEquals($fileNonexistent, $params->getFile('nonexistent'));
 }
예제 #30
0
 /**
  * @expectedException CM_Exception_FormFieldValidation
  */
 public function testValidateFileNoImage()
 {
     $image = CM_File::createTmp();
     $formField = new CM_FormField_FileImage();
     $formField->validateFile($image);
 }