Prepare span for for sending to APM.
@param Span $span
@return Span
@throws \Exception
976835
private function prepareSpan(Span $span): Span
    {
        $span->setTransactionId($this->transaction->getId());
        $span->setTraceId($this->transaction->getTraceId());

        if ($span->getId() === null) {
            $span->setId(AbstractEventBuilder::generateRandomBitsInHex(64));
        }

        if ($span->getParentId() === null) {
            $span->setParentId($this->transaction->getId());
        }

        if ($span->getStart() === null) {
            $span->setStart(
                intval(round(($span->getTimestamp() - $this->transaction->getTimestamp()) / 1000))
            );
        }

        return $span;
    }
271963
public function span($value, $attributes = [])
    {
        $tag = new Tag('span', $attributes);
        $tag->setText($value);
        return $tag;
    }
969789
public function fromReceivedMessage(AMQPMessage $message)
    {
        return new Span(
            $this->getIdentifierOrGenerate($message, 'X-B3-SpanId'),
            $this->getMessageName($message),
            $this->getIdentifierOrGenerate($message, 'X-B3-TraceId'),
            [
                new Annotation(Annotation::SERVER_RECEIVE, $this->clock->microseconds(), $this->endpointResolver->resolve()),
            ],
            [],
            $this->getIdentifier($message, 'X-B3-ParentSpanId'),
            $this->getMessageHeader($message, 'X-B3-Flags') == '1'
        );
    }
917196
private Span startTracing(String spanName) {
        if (!environment.operationTracingEnabled()) {
            return null;
        }
        Scope scope = environment.tracer()
            .buildSpan(spanName)
            .startActive(false);
        Span parent = scope.span();
        scope.close();
        return parent;
    }
887486
private function collect(): array
    {
        $spans = [];

        foreach ($this->collectors as $collector) {
            foreach ($collector->getSpans() as $span) {
                $spans[] = $this->prepareSpan($span);
            }
        }

        return $spans;
    }
1250518
def build_registered_span(self, span):
        
        data = Data(baggage=span.context.baggage)

        kind = 1 # entry
        if span.operation_name in self.exit_spans:
            kind = 2 # exit
        # log is a special case as it is not entry nor exit
        if span.operation_name == "log":
            kind = 3 # intermediate span

        logs = self.collect_logs(span)
        if len(logs) > 0:
            if data.custom is None:
                data.custom = CustomData()
            data.custom.logs = logs

        if span.operation_name in self.http_spans:
            data.http = HttpData(host=span.tags.pop("http.host", None),
                                 url=span.tags.pop(ext.HTTP_URL, None),
                                 params=span.tags.pop('http.params', None),
                                 method=span.tags.pop(ext.HTTP_METHOD, None),
                                 status=span.tags.pop(ext.HTTP_STATUS_CODE, None),
                                 path_tpl=span.tags.pop("http.path_tpl", None),
                                 error=span.tags.pop('http.error', None))

        if span.operation_name == "rabbitmq":
            data.rabbitmq = RabbitmqData(exchange=span.tags.pop('exchange', None),
                                         queue=span.tags.pop('queue', None),
                                         sort=span.tags.pop('sort', None),
                                         address=span.tags.pop('address', None),
                                         key=span.tags.pop('key', None))
            if data.rabbitmq.sort == 'consume':
                kind = 1 # entry

        if span.operation_name == "redis":
            data.redis = RedisData(connection=span.tags.pop('connection', None),
                                   driver=span.tags.pop('driver', None),
                                   command=span.tags.pop('command', None),
                                   error=span.tags.pop('redis.error', None),
                                   subCommands=span.tags.pop('subCommands', None))

        if span.operation_name == "rpc-client" or span.operation_name == "rpc-server":
            data.rpc = RPCData(flavor=span.tags.pop('rpc.flavor', None),
                               host=span.tags.pop('rpc.host', None),
                               port=span.tags.pop('rpc.port', None),
                               call=span.tags.pop('rpc.call', None),
                               call_type=span.tags.pop('rpc.call_type', None),
                               params=span.tags.pop('rpc.params', None),
                               baggage=span.tags.pop('rpc.baggage', None),
                               error=span.tags.pop('rpc.error', None))

        if span.operation_name == "sqlalchemy":
            data.sqlalchemy = SQLAlchemyData(sql=span.tags.pop('sqlalchemy.sql', None),
                                             eng=span.tags.pop('sqlalchemy.eng', None),
                                             url=span.tags.pop('sqlalchemy.url', None),
                                             err=span.tags.pop('sqlalchemy.err', None))

        if span.operation_name == "soap":
            data.soap = SoapData(action=span.tags.pop('soap.action', None))

        if span.operation_name == "mysql":
            data.mysql = MySQLData(host=span.tags.pop('host', None),
                                   db=span.tags.pop(ext.DATABASE_INSTANCE, None),
                                   user=span.tags.pop(ext.DATABASE_USER, None),
                                   stmt=span.tags.pop(ext.DATABASE_STATEMENT, None))
            if (data.custom is not None) and (data.custom.logs is not None) and len(data.custom.logs):
                tskey = list(data.custom.logs.keys())[0]
                data.mysql.error = data.custom.logs[tskey]['message']

        if span.operation_name == "log":
            data.log = {}
            # use last special key values
            # TODO - logic might need a tweak here
            for l in span.logs:
                if "message" in l.key_values:
                    data.log["message"] = l.key_values.pop("message", None)
                if "parameters" in l.key_values:
                    data.log["parameters"] = l.key_values.pop("parameters", None)

        entity_from = {'e': instana.singletons.agent.from_.pid,
                      'h': instana.singletons.agent.from_.agentUuid}

        json_span = JsonSpan(n=span.operation_name,
                             k=kind,
                             t=span.context.trace_id,
                             p=span.parent_id,
                             s=span.context.span_id,
                             ts=int(round(span.start_time * 1000)),
                             d=int(round(span.duration * 1000)),
                             f=entity_from,
                             data=data)

        if span.stack:
            json_span.stack = span.stack

        error = span.tags.pop("error", False)
        ec = span.tags.pop("ec", None)

        if error and ec:
            json_span.error = error
            json_span.ec = ec

        if len(span.tags) > 0:
            if data.custom is None:
                data.custom = CustomData()
            data.custom.tags = span.tags

        return json_span
143339
public function setSpan($span)
    {
        if (is_int($span) === true && $span > 0) {
            $this->span = $span;
        } else {
            $msg = "The 'span' attribute must be a strictly positive (> 0) integer, '" . gettype($span) . "' given.";
            throw new InvalidArgumentException($msg);
        }
    }
1003493
public function attributeAdded(Span $span, $attribute, $value)
    {
        // If the span is already attached (managed by the extension), then
        // tell the extension to add the attribute.
        if ($span->attached()) {
            $this->addAttribute($attribute, $value, [
                'span' => $span
            ]);
        }
    }
1064551
public function addSpan(DateTimeSpan $dtsSpan)
    {
        // And add the Span Second count to it
        $this->Timestamp = $this->Timestamp + $dtsSpan->Seconds;
        return $this;
    }
681134
public function prepare(Exception $exception)
  {
    if ($exception instanceof NotFoundHttpException) {
      return $exception->createsClientError();
    } else if ($exception instanceof ServiceUnavailableHttpException) {
      return $exception->createsServerError();
    }

    return $exception;
  }
1210656
public function span_first($match = null, int $end = null): SpanFirst
    {
        return new SpanFirst($match, $end);
    }
997938
protected function buildHeading( $span = NULL )
	{
		$month	= (int) $this->getOption( 'show_month' );
		$year	= (int) $this->getOption( 'show_year' );
		$prev_month	= $month - 1;
		$next_month	= $month + 1;
		$prev_year	= $next_year = $year;

		$month	= $this->months[$month - 1];
		if( $prev_month < 1 )
		{
			$prev_month	= 12;
			$prev_year--;
		}
		else if( $next_month > 12 )
		{
			$next_month	= 1;
			$next_year++;
		}
		$colspan	= "";
		if( $span )
			$colspan	= " colspan='5'";
		$url	= $this->getOption( 'url' )."&".$this->getOption( 'carrier_year' )."=".$prev_year."&".$this->getOption( 'carrier_month' )."=".$prev_month;
		$prev	= UI_HTML_Elements::Link( $url, "&lt;" );
		$url	= $this->getOption( 'url' )."&".$this->getOption( 'carrier_year' )."=".$next_year."&".$this->getOption( 'carrier_month' )."=".$next_month;
		$next	= UI_HTML_Elements::Link( $url, "&gt;" );

		$left	= UI_HTML_Tag::create( "div", $prev, array( 'class' => "go-left" ) );
		$right	= UI_HTML_Tag::create( "div", $next, array( 'class' => "go-right" ) );
		$label	= UI_HTML_Tag::create( "div", htmlspecialchars( $month ).' '.$year, array( 'class' => "label" ) );
		$code	= UI_HTML_Tag::create( "div", $left.$label.$right, array( 'class' => 'month' ) );
		return $code;
	}
784012
public function fromOutgoingRequest(RequestInterface $request)
    {
        $currentSpan = $this->spanStack->current();

        return new Span(
            $this->identifierGenerator->generate(),
            $this->getName($request),
            null !== $currentSpan ? $currentSpan->getTraceIdentifier() : $this->identifierGenerator->generate(),
            [
                new Annotation(Annotation::CLIENT_SEND, $this->clock->microseconds(), $this->endpointResolver->resolve()),
            ],
            [
                new BinaryAnnotation('http.host', $request->getUri()->getHost(), BinaryAnnotation::TYPE_STRING),
                new BinaryAnnotation('http.path', $request->getUri()->getPath(), BinaryAnnotation::TYPE_STRING),
                new BinaryAnnotation('http.method', $request->getMethod(), BinaryAnnotation::TYPE_STRING),
            ],
            $currentSpan !== null ? $currentSpan->getIdentifier() : null,
            $currentSpan !== null ? $currentSpan->getDebug() : null
        );
    }
162394
public function inject(OTSpanContext $spanContext, $format, &$carrier)
    {
        if ($spanContext instanceof SpanContext) {
            $codec = $this->codecs[$format] ?? null;

            if ($codec == null) {
                throw UnsupportedFormat::forFormat(is_scalar($format) ? $format : gettype($format));
            }


            $codec->inject($spanContext, $carrier);
            return;
        }

        $message = sprintf(
            'Invalid span context. Expected Jaeger\SpanContext, got %s.',
            is_object($spanContext) ? get_class($spanContext) : gettype($spanContext)
        );

        $this->logger->warning($message);
    }
285553
public function prependContent($content)
    {
        if ($this->isVoid) {
            throw new Exception\RuntimeException(
                'Void elements can\'t contain content.'
            );
        }

        $this->content = $content . $this->content;

        return $this;
    }
1268266
public function spanData()
    {
        return new SpanData(
            $this->name,
            $this->traceId,
            $this->spanId,
            $this->startTime,
            $this->endTime,
            [
                'parentSpanId' => $this->parentSpanId,
                'attributes' => $this->attributes,
                'timeEvents' => $this->timeEvents,
                'links' => $this->links,
                'status' => $this->status,
                'sameProcessAsParentSpan' => $this->sameProcessAsParentSpan,
                'stackTrace' => $this->stackTrace,
                'kind' => $this->kind
            ]
        );
    }
817543
public function inject(SpanContext $spanContext, $format, &$carrier){
        if($format == Formats\TEXT_MAP){
            $this->propagator->inject($spanContext, $format, $carrier);
        }else{
            throw new \Exception("not support format");
        }
    }