コード例 #1
0
ファイル: Definition.php プロジェクト: cargomedia/cm
 /**
  * @param string $key
  * @param mixed  $value
  * @return mixed
  * @throws CM_Exception_Invalid
  * @throws CM_Model_Exception_Validation
  */
 public function encodeField($key, $value)
 {
     $key = (string) $key;
     if ($this->hasField($key)) {
         $schemaField = $this->_schema[$key];
         if (null !== $value) {
             $type = isset($schemaField['type']) ? $schemaField['type'] : null;
             if (null !== $type) {
                 switch ($type) {
                     case 'integer':
                     case 'int':
                         $value = (int) $value;
                         break;
                     case 'float':
                         $value = (double) $value;
                         break;
                     case 'string':
                         $value = (string) $value;
                         break;
                     case 'boolean':
                     case 'bool':
                         $value = (bool) $value;
                         break;
                     case 'array':
                         break;
                     case 'DateTime':
                         /** @var DateTime $value */
                         $value = $value->getTimestamp();
                         break;
                     default:
                         if (!class_exists($type)) {
                             throw new CM_Model_Exception_Validation('Field type is not a valid class', null, ['type' => $type]);
                         }
                         $className = $type;
                         if (!$value instanceof $className) {
                             throw new CM_Model_Exception_Validation('Value is not an instance of the class', null, ['value' => CM_Util::var_line($value), 'className' => $className]);
                         }
                         if (is_a($className, 'CM_Model_Abstract', true)) {
                             /** @var CM_Model_Abstract $value */
                             $id = $value->getIdRaw();
                             if (count($id) == 1) {
                                 $value = $value->getId();
                             } else {
                                 $value = CM_Util::jsonEncode($id);
                             }
                         } elseif (is_subclass_of($className, 'CM_ArrayConvertible', true)) {
                             /** @var CM_ArrayConvertible $value */
                             $value = $value->toArray();
                             $value = CM_Util::jsonEncode($value);
                         } else {
                             throw new CM_Model_Exception_Validation('Class is neither CM_Model_Abstract nor CM_ArrayConvertible', null, ['className' => $className]);
                         }
                 }
             }
         }
     }
     return $value;
 }
コード例 #2
0
ファイル: HttpApiClient.php プロジェクト: cargomedia/cm
 /**
  * @param string          $method
  * @param CM_Janus_Server $server
  * @param string          $path
  * @param array|null      $body
  * @return string
  * @throws CM_Exception_Invalid
  */
 protected function _request($method, CM_Janus_Server $server, $path, array $body = null)
 {
     $context = CM_Service_Manager::getInstance()->getLogger()->getContext();
     $appContext = $this->_contextFormatter->formatAppContext($context);
     $url = $server->getHttpAddress() . $path;
     $body = (array) $body;
     $options = ['query' => ['context' => CM_Util::jsonEncode($appContext)], 'body' => $body, 'headers' => ['Server-Key' => $server->getKey()]];
     $request = $this->_httpClient->createRequest($method, $url, $options);
     try {
         $response = $this->_httpClient->send($request);
     } catch (GuzzleHttp\Exception\TransferException $e) {
         throw new CM_Exception_Invalid('Fetching contents from url failed', null, ['url' => $url, 'originalExceptionMessage' => $e->getMessage()]);
     }
     $body = $response->getBody();
     if (null === $body) {
         throw new CM_Exception_Invalid('Empty response body');
     }
     return $body->getContents();
 }
コード例 #3
0
ファイル: Cargomedia.php プロジェクト: cargomedia/cm
 public function formatContext(CM_Log_Context $context)
 {
     $result = [];
     if ($computerInfo = $context->getComputerInfo()) {
         $result['computerInfo'] = ['fqdn' => $computerInfo->getFullyQualifiedDomainName(), 'phpVersion' => $computerInfo->getPhpVersion()];
     }
     $request = $context->getHttpRequest();
     if (null !== $request) {
         $serverArray = $request->getServer();
         $formattedRequest = ['uri' => $request->getUri(), 'method' => $request->getMethodName()];
         $query = $request->findQuery();
         unset($query['viewInfoList']);
         $formattedRequest['query'] = CM_Util::jsonEncode($query, true);
         if (array_key_exists('http_referer', $serverArray)) {
             $formattedRequest['referer'] = (string) $serverArray['http_referer'];
         }
         if (array_key_exists('http_user_agent', $serverArray)) {
             $formattedRequest['useragent'] = (string) $serverArray['http_user_agent'];
         }
         if ($ip = $request->getIp()) {
             $formattedRequest['ip'] = (string) $ip;
         }
         if ($request->hasHeader('host')) {
             $formattedRequest['hostname'] = $request->getHost();
         }
         $result['httpRequest'] = $formattedRequest;
     }
     $result = array_merge($result, $this->formatAppContext($context));
     if ($exception = $context->getException()) {
         $serializableException = new CM_ExceptionHandling_SerializableException($exception);
         $stack = $serializableException->getTrace();
         if (!empty($stack)) {
             $stackAsString = trim(Functional\reduce_left(array_reverse($stack), function ($value, $index, $collection, $reduction) {
                 return $reduction . '#' . $index . ' ' . $value['file'] . '(' . $value['line'] . '): ' . $value['code'] . PHP_EOL;
             }, ''));
         } else {
             $stackAsString = $serializableException->getTraceAsString();
         }
         $result['exception'] = ['type' => $serializableException->getClass(), 'message' => $serializableException->getMessage(), 'stack' => $stackAsString, 'metaInfo' => $serializableException->getMeta()];
     }
     return $result;
 }
コード例 #4
0
ファイル: Cli.php プロジェクト: cargomedia/cm
 public function generateConfigInternal()
 {
     $indentation = '    ';
     $indent = function ($content) use($indentation) {
         return preg_replace('/(:?^|[\\n])/', '$1' . $indentation, $content);
     };
     $generator = new CM_Config_Generator();
     $classTypesConfig = $generator->getConfigClassTypes()->exportAsString('$config');
     $actionVerbsConfig = $generator->getConfigActionVerbs()->exportAsString('$config');
     foreach ($generator->getClassTypesRemoved() as $classRemoved) {
         $this->_getStreamOutput()->writeln('Removed `' . $classRemoved . '`');
     }
     foreach ($generator->getClassTypesAdded() as $type => $classAdded) {
         $this->_getStreamOutput()->writeln('Added `' . $classAdded . '` with type `' . $type . '`');
     }
     // Create model class types and action verbs config PHP
     $configPhp = new CM_File(DIR_ROOT . 'resources/config/internal.php');
     $configPhp->ensureParentDirectory();
     $configPhp->truncate();
     $configPhp->appendLine('<?php');
     $configPhp->appendLine('// This is autogenerated config file. You should not change it manually.');
     $configPhp->appendLine();
     $configPhp->appendLine('return function (CM_Config_Node $config) {');
     $configPhp->appendLine($indent($classTypesConfig));
     $configPhp->appendLine($indent($actionVerbsConfig));
     $configPhp->appendLine('};');
     $this->_getStreamOutput()->writeln('Created `' . $configPhp->getPath() . '`');
     // Create model class types and action verbs config JS
     $configJs = new CM_File(DIR_ROOT . 'resources/config/js/internal.js');
     $configJs->ensureParentDirectory();
     $configJs->truncate();
     $classTypes = $generator->getNamespaceTypes();
     $configJs->appendLine('cm.model.types = ' . CM_Util::jsonEncode(array_flip($classTypes['CM_Model_Abstract']), true) . ';');
     $configJs->appendLine('cm.action.types = ' . CM_Util::jsonEncode(array_flip($classTypes['CM_Action_Abstract']), true) . ';');
     $this->_getStreamOutput()->writeln('Created `' . $configJs->getPath() . '`');
 }
コード例 #5
0
ファイル: Params.php プロジェクト: cargomedia/cm
 /**
  * @param mixed     $value
  * @param bool|null $prettyPrint
  * @throws CM_Exception_Invalid
  * @return string
  */
 public static function jsonEncode($value, $prettyPrint = null)
 {
     return CM_Util::jsonEncode($value, $prettyPrint);
 }
コード例 #6
0
ファイル: AbstractTest.php プロジェクト: cargomedia/cm
 public function testSanitize()
 {
     $malformedString = pack("H*", 'c32e');
     $malformedUri = 'http://foo.bar/' . $malformedString;
     $this->assertFalse(mb_check_encoding($malformedUri, 'UTF-8'));
     $exception = $this->catchException(function () use($malformedUri) {
         CM_Util::jsonEncode($malformedUri);
     });
     $this->assertInstanceOf('CM_Exception_Invalid', $exception);
     $this->assertSame('Cannot json_encode value.', $exception->getMessage());
     $request = new CM_Http_Request_Get($malformedUri, null, ['baz' => pack("H*", 'c32e')]);
     $this->assertInstanceOf('CM_Http_Request_Get', $request);
     $this->assertTrue(mb_check_encoding($request->getUri(), 'UTF-8'));
     $this->assertTrue(mb_check_encoding($request->getServer()['baz'], 'UTF-8'));
     $this->assertNotEmpty(CM_Util::jsonEncode($request->getUri()));
 }
コード例 #7
0
ファイル: UtilTest.php プロジェクト: cargomedia/cm
 /**
  * @expectedException CM_Exception_Invalid
  */
 public function testJsonEncodeInvalid()
 {
     $resource = fopen(sys_get_temp_dir(), 'r');
     CM_Util::jsonEncode(['foo' => $resource]);
 }
コード例 #8
0
ファイル: Conversion.php プロジェクト: cargomedia/cm
 /**
  * @return string
  */
 public function toJson()
 {
     $array = $this->toArray();
     return empty($array) ? '{}' : CM_Util::jsonEncode($array);
 }