Exemple #1
0
 /**
  * @param mixed      $variable
  * @param array|null $options
  * @return string
  */
 public function getDebugInfo($variable, array $options = null)
 {
     $options = array_merge(['recursive' => false, 'lengthMax' => null], (array) $options);
     $recursive = (bool) $options['recursive'];
     $lengthMax = null === $options['lengthMax'] ? null : (int) $options['lengthMax'];
     if (is_array($variable)) {
         if ($recursive) {
             $elementList = Functional\map($variable, function ($value, $key) use($options) {
                 return $this->getDebugInfo($key, $options) . ' => ' . $this->getDebugInfo($value, $options);
             });
             return '[' . implode(', ', $elementList) . ']';
         } else {
             return '[]';
         }
     }
     if (is_object($variable)) {
         if ($variable instanceof stdClass) {
             return 'object';
         }
         if ($variable instanceof CM_Debug_DebugInfoInterface) {
             return $variable->getDebugInfo();
         }
         return get_class($variable);
     }
     if (is_string($variable)) {
         if (null !== $lengthMax && strlen($variable) > $lengthMax) {
             $variable = substr($variable, 0, $lengthMax) . '...';
         }
         return "'" . $variable . "'";
     }
     if (is_bool($variable) || is_numeric($variable)) {
         return var_export($variable, true);
     }
     return gettype($variable);
 }
Exemple #2
0
 /**
  * @param CM_Log_Handler_HandlerInterface[] $handlers
  */
 public function setHandlers($handlers)
 {
     $this->_handlers = [];
     \Functional\map($handlers, function (CM_Log_Handler_HandlerInterface $handler) {
         $this->addHandler($handler);
     });
 }
Exemple #3
0
 public function testOnDelete()
 {
     /** @var CM_Model_StreamChannel_Media $streamChannel */
     $streamChannel = CMTest_TH::createStreamChannel();
     $archive = CMTest_TH::createStreamChannelVideoArchive($streamChannel, null, 'tempFileName.mp4');
     CM_StreamChannel_Thumbnail::create($archive->getId(), 1);
     CM_StreamChannel_Thumbnail::create($archive->getId(), 1);
     CM_StreamChannel_Thumbnail::create($archive->getId(), 1);
     $this->_createArchiveFiles($archive);
     /** @var CM_File_UserContent[] $thumbnailFiles */
     $thumbnailFiles = \Functional\map($archive->getThumbnails(), function (CM_StreamChannel_Thumbnail $thumbnail) {
         return $thumbnail->getFile();
     });
     $thumbnailDir = $thumbnailFiles[0]->getParentDirectory();
     $mediaFile = $archive->getFile();
     $this->assertCount(3, $archive->getThumbnails());
     foreach ($thumbnailFiles as $file) {
         $this->assertTrue($file->exists());
     }
     $this->assertTrue($thumbnailDir->exists());
     $this->assertTrue($mediaFile->exists());
     $archive->delete();
     foreach ($thumbnailFiles as $file) {
         $this->assertFalse($file->exists());
     }
     $this->assertFalse($thumbnailDir->exists());
     $this->assertFalse($mediaFile->exists());
     $this->assertCount(0, $archive->getThumbnails());
     $exception = $this->catchException(function () use($archive) {
         CMTest_TH::reinstantiateModel($archive);
     });
     $this->assertInstanceOf('CM_Exception_Nonexistent', $exception);
 }
Exemple #4
0
 /**
  * @return CM_Elasticsearch_Type_Abstract[]
  */
 public function getTypes()
 {
     $types = CM_Util::getClassChildren('CM_Elasticsearch_Type_Abstract');
     return \Functional\map($types, function ($className) {
         return new $className($this->getRandomClient());
     });
 }
Exemple #5
0
 /**
  * @param string[]    $expectedNameList
  * @param array[]     $actualItemList
  * @param string|null $message
  */
 private function _assertItemsByName($expectedNameList, $actualItemList, $message = null)
 {
     $actualNameList = Functional\map($actualItemList, function (array $actualItem) {
         $actualLocation = new CM_Model_Location($actualItem['level'], $actualItem['id']);
         return $actualLocation->getName();
     });
     $this->assertSame($expectedNameList, $actualNameList, $message);
 }
Exemple #6
0
 /**
  * @param string[] $stringList
  */
 public function addMultiple(array $stringList)
 {
     $data = \Functional\map($stringList, function ($string) {
         return ['type' => $this->_type, 'string' => (string) $string];
     });
     CM_Db_Db::replace('cm_string', ['type', 'string'], $data);
     $this->_change();
 }
Exemple #7
0
 public function getHtml($zoneName, $zoneData, array $variables)
 {
     $src = (string) $zoneData['src'];
     $width = (string) $zoneData['width'];
     $height = (string) $zoneData['height'];
     $params = ['src' => $src, 'width' => $width, 'height' => $height, 'class' => 'advertisement-hasContent', 'data-variables' => json_encode($variables, JSON_FORCE_OBJECT), 'frameborder' => 0, 'scrolling' => 'no'];
     $params = Functional\map($params, function ($value, $key) {
         return $key . '="' . CM_Util::htmlspecialchars($value) . '"';
     });
     return '<iframe ' . join(' ', $params) . '></iframe>';
 }
Exemple #8
0
 public function load(CM_OutputStream_Interface $output)
 {
     $dbClient = $this->getServiceManager()->getDatabases()->getMaster();
     $values = Functional\map($this->_getAllTypes(), function ($className, $type) {
         return [$type, $className];
     });
     $query = new CM_Db_Query_Truncate($dbClient, 'cm_tmp_classType');
     $query->execute();
     $query = new CM_Db_Query_Insert($dbClient, 'cm_tmp_classType', ['type', 'className'], $values, null, 'REPLACE');
     $query->execute();
 }
Exemple #9
0
 public function testRun()
 {
     $job = $this->getMockBuilder('CM_Jobdistribution_Job_Abstract')->setMethods(array('runMultiple'))->getMockForAbstractClass();
     $job->expects($this->once())->method('runMultiple')->will($this->returnCallback(function (array $paramsList) {
         return Functional\map($paramsList, function ($params) {
             return array_flip($params);
         });
     }));
     /** @var CM_Jobdistribution_Job_Abstract $job */
     $result = $job->run(array('foo' => 'bar'));
     $this->assertSame(array('bar' => 'foo'), $result);
 }
Exemple #10
0
 protected function _save(array $data)
 {
     $values = \Functional\map($data, function (DateTime $dateTime) {
         return $dateTime->getTimestamp();
     });
     $content = CM_Params::jsonEncode($values, true);
     $file = $this->_getStorageFile();
     if (!$file->exists()) {
         $file->ensureParentDirectory();
     }
     $file->write($content);
 }
Exemple #11
0
 /**
  * @param string     $collection
  * @param array[]    $objectList
  * @param array|null $options
  * @return mixed[] insertIds
  * @throws CM_MongoDb_Exception
  */
 public function batchInsert($collection, array $objectList, array $options = null)
 {
     $options = $options ?: [];
     CM_Service_Manager::getInstance()->getDebug()->incStats('mongo', "Batch Insert `{$collection}`: " . CM_Params::jsonEncode($objectList));
     $dataList = \Functional\map($objectList, function (array &$object) {
         return $object;
     });
     $result = $this->_getCollection($collection)->batchInsert($dataList, $options);
     $this->_checkResultForErrors($result);
     return \Functional\map($dataList, function (array $data) {
         return $data['_id'];
     });
 }
Exemple #12
0
 /**
  * @param array|null $params
  * @param bool|null  $encoded Defaults to true
  */
 public function __construct(array $params = null, $encoded = null)
 {
     $params = $params ?: array();
     if (null === $encoded) {
         $encoded = true;
     }
     $this->_params = \Functional\map($params, function ($value) use($encoded) {
         if ($encoded) {
             return ['encoded' => $value, 'decoded' => null];
         } else {
             return ['encoded' => null, 'decoded' => $value];
         }
     });
 }
Exemple #13
0
 /**
  * @param string   $key
  * @param DateTime $date
  */
 public function restoreByDeletingNewerVersions($key, DateTime $date)
 {
     $versions = $this->getVersions($key);
     $versionsToDelete = Functional\select($versions, function (CMService_AwsS3Versioning_Response_Version $version) use($key, $date) {
         $isExactKeyMatch = $key === $version->getKey();
         $isModifiedAfter = $date < $version->getLastModified();
         return $isExactKeyMatch && $isModifiedAfter;
     });
     $this->_streamOutput->writeln('Restoring `' . $key . '` - deleting ' . count($versionsToDelete) . ' versions...');
     if (count($versionsToDelete) > 0) {
         $objectsData = Functional\map($versionsToDelete, function (CMService_AwsS3Versioning_Response_Version $version) {
             return array('Key' => $version->getKey(), 'VersionId' => $version->getId());
         });
         $this->_client->deleteObjects(array('Bucket' => $this->_bucket, 'Objects' => $objectsData));
     }
 }
Exemple #14
0
 /**
  * @param int|null $offset
  * @param int|null $count
  * @return array
  */
 private function _getResult($offset = null, $count = null)
 {
     $cacheKey = array($this->_query->getSort(), $offset, $count);
     if (($result = $this->_cacheGet($cacheKey)) === false) {
         $data = array('query' => $this->_query->getQuery(), 'sort' => $this->_query->getSort());
         if ($this->_fields) {
             $data['fields'] = $this->_fields;
         }
         if ($offset !== null) {
             $data['from'] = $offset;
         }
         if ($count !== null) {
             $data['size'] = $count;
         }
         $searchResult = CM_Service_Manager::getInstance()->getElasticsearch()->query($this->_types, $data);
         $result = array('items' => array(), 'total' => 0);
         if (isset($searchResult['hits'])) {
             foreach ($searchResult['hits']['hits'] as $hit) {
                 if ($this->_fields && array_key_exists('fields', $hit)) {
                     if ($this->_returnType) {
                         $idArray = array('id' => $hit['_id'], 'type' => $hit['_type']);
                     } else {
                         $idArray = array('id' => $hit['_id']);
                     }
                     $fields = $hit['fields'];
                     $fields = Functional\map($fields, function ($field) {
                         if (is_array($field) && 1 == count($field)) {
                             $field = reset($field);
                         }
                         return $field;
                     });
                     $result['items'][] = array_merge($idArray, $fields);
                 } else {
                     if ($this->_returnType) {
                         $item = array('id' => $hit['_id'], 'type' => $hit['_type']);
                     } else {
                         $item = $hit['_id'];
                     }
                     $result['items'][] = $item;
                 }
             }
             $result['total'] = $searchResult['hits']['total'];
         }
         $this->_cacheSet($cacheKey, $result);
     }
     return $result;
 }
Exemple #15
0
 public function generateFavicon()
 {
     $faviconConfigList = $this->_getFaviconConfigList();
     $this->_getStreamOutput()->writeln('Generating favicons');
     $themeDirStructList = Functional\map(CM_Site_Abstract::getAll(), function (CM_Site_Abstract $site) {
         $render = new CM_Frontend_Render(new CM_Frontend_Environment($site));
         return ['render' => $render, 'themeDir' => new CM_File($render->getThemeDir(true))];
     });
     $themeDirStructList = Functional\unique($themeDirStructList, function (array $themeDirStruct) {
         /** @var CM_File $themeDir */
         $themeDir = $themeDirStruct['themeDir'];
         return $themeDir->getPath();
     });
     //filter site aliases
     foreach ($themeDirStructList as $themeDirStruct) {
         /** @var CM_Frontend_Render $render */
         $render = $themeDirStruct['render'];
         /** @var CM_File $themeDir */
         $themeDir = $themeDirStruct['themeDir'];
         $svgFile = $themeDir->joinPath('resource', 'img', self::FAVICON_SVG_FILENAME);
         if ($svgFile->exists()) {
             foreach ($faviconConfigList as $outputFilename => $config) {
                 $backgroundWidth = (int) $config['width'];
                 $backgroundHeight = (int) $config['height'];
                 $backgroundColor = false === $config['transparent'] ? $render->getLessVariable(self::FAVICON_BACKGROUND_LESS_VARIABLE) : 'transparent';
                 $background = new Imagick();
                 $background->newPseudoImage($backgroundWidth, $backgroundHeight, 'canvas:' . $backgroundColor);
                 $backgroundImage = new CM_Image_Image($background);
                 $iconSize = (int) (min($backgroundWidth, $backgroundHeight) * (double) $config['iconSize']);
                 $iconImage = CM_Image_Image::createFromSVGWithSize($svgFile->read(), $iconSize, $iconSize);
                 $backgroundImage->compositeImage($iconImage, ($backgroundWidth - $iconSize) / 2, ($backgroundHeight - $iconSize) / 2);
                 $backgroundImage->setFormat(CM_Image_Image::FORMAT_PNG);
                 $targetFile = $themeDir->joinPath('resource', 'img', 'meta', $outputFilename);
                 $targetFile->ensureParentDirectory();
                 $targetFile->write($backgroundImage->getBlob());
                 $this->_getStreamOutput()->writeln('Generated ' . $targetFile->getPath());
             }
         }
     }
 }
Exemple #16
0
 public function testGetItemsAggregation()
 {
     $mongodb = CM_Service_Manager::getInstance()->getMongoDb();
     $items = array();
     for ($i = 0; $i < 2; $i++) {
         $j = $i * 2;
         $item = array('foo' => 12, 'bar' => array(array('sub' => $j), array('sub' => $j + 1)));
         $items = array_merge($items, \Functional\map($item['bar'], function ($bar) use($item, $i) {
             return ['foo' => $item['foo'], 'bar' => $bar];
         }));
         $mongodb->insert('my-collection', $item);
     }
     $source = new CM_PagingSource_MongoDb('my-collection', array('bar.sub' => 2), array('bar' => 1, '_id' => 0), [['$unwind' => '$bar']]);
     $this->assertEquals([['bar' => ['sub' => 2]], ['bar' => ['sub' => 3]]], $source->getItems());
     $source = new CM_PagingSource_MongoDb('my-collection', null, null, [['$unwind' => '$bar']]);
     $result = \Functional\map($source->getItems(), function ($doc) {
         unset($doc['_id']);
         return $doc;
     });
     $this->assertEquals($items, $result);
     $this->assertEquals(array_slice($items, 1), \Functional\map($source->getItems(1), function ($doc) {
         unset($doc['_id']);
         return $doc;
     }));
     $this->assertEquals(array_slice($items, 1, 2), \Functional\map($source->getItems(1, 2), function ($doc) {
         unset($doc['_id']);
         return $doc;
     }));
     $source = new CM_PagingSource_MongoDb('my-collection', null, null, [['$unwind' => '$bar']], ['bar.sub' => -1]);
     $this->assertEquals(array_reverse($items), \Functional\map($source->getItems(), function ($doc) {
         unset($doc['_id']);
         return $doc;
     }));
     $this->assertEquals(array_slice(array_reverse($items), 2, 1), \Functional\map($source->getItems(2, 1), function ($doc) {
         unset($doc['_id']);
         return $doc;
     }));
 }
Exemple #17
0
 private function find()
 {
     $results = \Functional\map($this->regexes, function (RegexResult $r) {
         return $r->next($this->current_index);
     });
     usort($results, function ($a, $b) {
         if ($a === null && $b === null) {
             return 0;
         } else {
             if ($a === null) {
                 return 1;
             } else {
                 if ($b === null) {
                     return -1;
                 }
             }
         }
         $aStart = $a[1];
         $aEnd = $a[1] + strlen($a[0]);
         $bStart = $b[1];
         $bEnd = $b[1] + strlen($b[0]);
         if ($aStart <= $bStart && $aEnd > $bStart) {
             if ($a['priority'] < $b['priority']) {
                 return 1;
             } else {
                 if ($a['priority'] > $b['priority']) {
                     return -1;
                 } else {
                     return 0;
                 }
             }
             /**
              * Bug 1 fixed:
              *  bEnd and aStart does not overlap if they are equal. Because end of string is one more than actual
              *  like normal array indexing.
              */
         } else {
             if ($bStart <= $aStart && $bEnd > $aStart) {
                 if ($a['priority'] < $b['priority']) {
                     return -1;
                 } else {
                     if ($a['priority'] > $b['priority']) {
                         return 1;
                     } else {
                         return 0;
                     }
                 }
             }
         }
         if ($aStart < $bStart) {
             return -1;
         } else {
             if ($aStart > $bStart) {
                 return 1;
             } else {
                 return 0;
             }
         }
     });
     $res = $results[0];
     if ($res) {
         $this->current_index = $res[1] + strlen($res[0]);
     }
     return $res;
 }
Exemple #18
0
 /**
  * @return CM_App_Package[]
  * @throws CM_Exception_Invalid
  */
 public function getPackages()
 {
     return \Functional\map($this->getComposerPackagesFiltered(), function (\Composer\Package\CompletePackage $package) {
         return $this->_getPackageFromComposerPackage($package);
     });
 }
Exemple #19
0
 /**
  * @param int $type
  * @return bool
  */
 public static function isValidType($type)
 {
     $type = (int) $type;
     $childrenTypeList = \Functional\map(CM_Paging_Log::getClassChildren(), function ($className) {
         /** @type CM_Class_Abstract $className */
         return $className::getTypeStatic();
     });
     return in_array($type, $childrenTypeList);
 }
Exemple #20
0
 protected function _getContainingCacheables()
 {
     $languages = new CM_Paging_Language_All();
     return array_flatten(\Functional\map($languages, function (CM_Model_Language $language) {
         return [$language->getTranslations(false), $language->getTranslations(true)];
     }));
 }
Exemple #21
0
 /**
  * @param boolean|null $noRecursion
  * @return CM_File[]
  */
 public function listFiles($noRecursion = null)
 {
     $result = $this->_filesystem->listByPrefix($this->getPath(), $noRecursion);
     return \Functional\map(array_merge($result['dirs'], $result['files']), function ($path) {
         return new CM_File($path, $this->_filesystem);
     });
 }
Exemple #22
0
<?php

$rowList = CM_Db_Db::select('cm_log', '*')->fetchAll();
foreach ($rowList as $row) {
    $metaInfo = @unserialize($row['metaInfo']);
    if (is_array($metaInfo)) {
        $variableInspector = new CM_Debug_VariableInspector();
        $metaInfo = Functional\map($metaInfo, function ($value) use($variableInspector) {
            return $variableInspector->getDebugInfo($value, ['recursive' => true]);
        });
    } else {
        $metaInfo = null;
    }
    CM_Db_Db::update('cm_log', ['metaInfo' => serialize($metaInfo)], ['id' => $row['id']]);
}
 /**
  * @param Exception $exception
  */
 private function _extract(Exception $exception)
 {
     $this->class = get_class($exception);
     $this->message = $exception->getMessage();
     $this->line = $exception->getLine();
     $this->file = $exception->getFile();
     if ($exception instanceof CM_Exception) {
         $variableInspector = new CM_Debug_VariableInspector();
         $this->metaInfo = Functional\map($exception->getMetaInfo(), function ($value) use($variableInspector) {
             return $variableInspector->getDebugInfo($value);
         });
     }
     try {
         $trace = array();
         $trace[] = array('code' => '{main}', 'line' => 0, 'file' => $_SERVER['SCRIPT_FILENAME']);
         foreach (array_reverse($exception->getTrace()) as $row) {
             $trace[] = self::_extractTraceRow($row);
         }
         $trace[] = ['code' => '{throw}', 'line' => $this->line, 'file' => $this->file];
         $this->trace = $trace;
     } catch (Exception $e) {
         $this->trace = null;
     }
     $this->traceString = $exception->getTraceAsString();
 }
Exemple #24
0
 /**
  * @return DateTimeZone|null
  */
 public function getTimeZone()
 {
     $pointCurrent = $this->getGeoPoint();
     if (null === $pointCurrent) {
         return null;
     }
     $timezoneNameList = \Functional\reject(DateTimeZone::listIdentifiers(), function ($timeZoneName) {
         return null === IntlTimeZone::fromDateTimeZone(new DateTimeZone($timeZoneName));
     });
     $distanceList = Functional\map($timezoneNameList, function ($timezoneName) use($pointCurrent) {
         $timezoneLocation = (new DateTimeZone($timezoneName))->getLocation();
         $pointTimeZone = new CM_Geo_Point($timezoneLocation['latitude'], $timezoneLocation['longitude']);
         return ['timezoneName' => $timezoneName, 'distance' => $pointCurrent->calculateDistanceTo($pointTimeZone)];
     });
     $closestDistance = Functional\reduce_left($distanceList, function (array $current, $index, $collection, array $minimal) {
         return $current['distance'] < $minimal['distance'] ? $current : $minimal;
     }, $distanceList[0]);
     return new DateTimeZone($closestDistance['timezoneName']);
 }
Exemple #25
0
 public function testFind()
 {
     $mongoDb = CM_Service_Manager::getInstance()->getMongoDb();
     $collectionName = 'find';
     $mongoDb->insert($collectionName, array('userId' => 1, 'groupId' => 1, 'name' => 'alice', 'foo' => [1]));
     $mongoDb->insert($collectionName, array('userId' => 2, 'groupId' => 2, 'name' => 'steve', 'foo' => [1, 2]));
     $mongoDb->insert($collectionName, array('userId' => 3, 'groupId' => 1, 'name' => 'bob', 'foo' => [1, 2, 3]));
     $users = $mongoDb->find($collectionName, array('groupId' => 1));
     $this->assertSame(2, $users->count());
     $expectedNames = array('alice', 'bob');
     foreach ($users as $user) {
         $expectedNames = array_diff($expectedNames, array($user['name']));
     }
     $this->assertEmpty($expectedNames);
     $result = $mongoDb->find($collectionName, ['groupId' => 1], ['_id' => 0, 'foo' => 1], [['$unwind' => '$foo']]);
     $actual = \Functional\map($result, function ($val) {
         return $val;
     });
     $this->assertEquals([['foo' => 1], ['foo' => 1], ['foo' => 2], ['foo' => 3]], $actual);
 }
Exemple #26
0
 /**
  * @param mixed[] $valueList
  * @return string
  */
 protected function _serialize(array $valueList)
 {
     $variableInspector = new CM_Debug_VariableInspector();
     $valueListString = Functional\map($valueList, function ($value) use($variableInspector) {
         return $variableInspector->getDebugInfo($value, ['recursive' => true]);
     });
     return serialize($valueListString);
 }
Exemple #27
0
 /**
  * @param array $list
  * @return array
  */
 private function _evaluateConstantsInKeys(array $list)
 {
     $keys = array_keys($list);
     $keys = \Functional\map($keys, function ($key) {
         if (null !== ($value = $this->_evaluateClassConstant($key))) {
             return $value;
         }
         return $key;
     });
     return array_combine($keys, array_values($list));
 }
Exemple #28
0
 public function testRestoreByCopyingOldVersion()
 {
     $this->_filesystem->write('bar', 'mega1');
     sleep(1);
     $this->_filesystem->write('bar', 'mega2');
     sleep(1);
     $this->_filesystem->delete('bar');
     sleep(1);
     $this->_filesystem->write('bar', 'mega3');
     sleep(1);
     $this->_filesystem->write('bar', 'mega4');
     $versionList = $this->_restore->getVersions('bar');
     /** @var DateTime[] $lastModifiedList */
     $lastModifiedList = Functional\map($versionList, function (CMService_AwsS3Versioning_Response_Version $version) {
         return $version->getLastModified();
     });
     $this->_restore->restoreByCopyingOldVersion('bar', $lastModifiedList[0]->add(new DateInterval('PT1S')));
     $this->assertCount(5, $this->_restore->getVersions('bar'));
     $this->assertSame('mega4', $this->_filesystem->read('bar'));
     $this->_restore->restoreByCopyingOldVersion('bar', $lastModifiedList[1]);
     $this->assertCount(6, $this->_restore->getVersions('bar'));
     $this->assertSame('mega3', $this->_filesystem->read('bar'));
     $this->_restore->restoreByCopyingOldVersion('bar', $lastModifiedList[2]);
     $this->assertCount(7, $this->_restore->getVersions('bar'));
     $this->assertSame(false, $this->_filesystem->exists('bar'));
     $this->_restore->restoreByCopyingOldVersion('bar', $lastModifiedList[4]);
     $this->assertCount(8, $this->_restore->getVersions('bar'));
     $this->assertSame('mega1', $this->_filesystem->read('bar'));
     $this->_restore->restoreByCopyingOldVersion('bar', $lastModifiedList[4]->sub(new DateInterval('PT1S')));
     $this->assertCount(9, $this->_restore->getVersions('bar'));
     $this->assertSame(false, $this->_filesystem->exists('bar'));
 }