How to add Status = KO in Gatling script? - java

Is it possible to fail my request?
I would like to put Status = KO in asLongAs() section. My condition is like, if I get WorkflowFailed = True or Count > 8 then I want to fail that request using Status = KO.
I have seen somewhere about session.markAsFailed but how and where to use this?
Thanks.
Here is the code,
class LaunchResources extends Simulation {
val scenarioRepeatCount = Integer.getInteger("scenarioRepeatCount", 1).toInt
val userCount = Integer.getInteger("userCount", 1).toInt
val UUID = System.getProperty("UUID", "24d0e03")
val username = System.getProperty("username", "p1")
val password = System.getProperty("password", "P12")
val testServerUrl = System.getProperty("testServerUrl", "https://someurl.net")
val count = new java.util.concurrent.atomic.AtomicInteger(0)
val httpProtocol = http
.baseURL(testServerUrl)
.basicAuth(username, password)
.connection("""keep-alive""")
.contentTypeHeader("""application/vnd+json""")
val headers_0 = Map(
"""Cache-Control""" -> """no-cache""",
"""Origin""" -> """chrome-extension://fdmmgasdw1dojojpjoooidkmcomcm""")
val scn = scenario("LaunchAction")
.repeat (scenarioRepeatCount) {
exec(http("LaunchAResources")
.post( """/api/actions""")
.headers(headers_0)
.body(StringBody(s"""{"UUID": "$UUID", "stringVariables" : {"externalFilePath" : "/Test.mp4"}}"""))
.check(jsonPath("$.id").saveAs("WorkflowID")))
.exec(http("SaveWorkflowStatus")
.get("""/api/actions/{$WorkflowID}""")
.headers(headers_0)
.check(jsonPath("$.status").saveAs("WorkflowStatus")))
}
.asLongAs(session => session.attributes("WorkflowStatus") != "false" && count.getAndIncrement() < 8) {
doIf(session => session("WorkflowFailed").validate[String].map(WorkflowFailed => !WorkflowFailed.contains("true")).recover(true))
{
pause(pauseTime)
.exec(http("SaveWorkflowStatus")
.get("""/api/actions/${WorkflowID}""")
.headers(headers_0)
.check(jsonPath("$.running").saveAs("WorkflowStatus"))
.check(jsonPath("$.failed").saveAs("WorkflowFailed")))
.exec(session => {
val wflowStatus1 = session.get("WorkflowStatus").asOption[String]
val wflowFailed1 = session.get("WorkflowFailed").asOption[String]
println("Inner Loop Workflow Status: ========>>>>>>>> " + wflowStatus1.getOrElse("COULD NOT FIND STATUS"))
println("Inner Loop Workflow Failed?? ========>>>>>>>> " + wflowFailed1.getOrElse("COULD NOT FIND STATUS"))
println("Count =====>> " + count)
session})
}
}
setUp(scn.inject(atOnceUsers(userCount))).protocols(httpProtocol)
}

there's a method available on the session
exec(session => session.markAsFailed)

Related

How to pass dynamic value in .apned in reactjs

I m using file upload with react and axios and fileupload working fine. and currently i am using fixed id in data.append('customeId', '123456'); but i want to use id value dynamic bcz there are multiple user. i want to use this id like let customeId = localStorage.getItem("customeId");. please help me use id value dynamic.
i am currently using
uploadFile = ({ target: { files } }) =>{
console.log( files[0] )
let data = new FormData();
data.append('customeId', '123456');
data.append( 'file', files[0] )
// data.append = localStorage.getItem("brokerId");
const options = {
onUploadProgress: (progressEvent) => {
const {loaded, total} = progressEvent;
let percent = Math.floor( (loaded * 100) / total )
console.log( `${loaded}kb of ${total}kb | ${percent}%` );
if( percent < 100 ){
this.setState({ uploadPercentage: percent })
}
}
}
axios.post("https://apimarkp.com/user/", data, options).then(res => { }
What i want
uploadFile = ({ target: { files } }) =>{
let customeId = localStorage.getItem("customeId");
console.log( files[0] )
let data = new FormData();
data.append('customeId', 'customeId');
data.append( 'file', files[0] )
// data.append = localStorage.getItem("brokerId");
const options = {
onUploadProgress: (progressEvent) => {
const {loaded, total} = progressEvent;
let percent = Math.floor( (loaded * 100) / total )
console.log( `${loaded}kb of ${total}kb | ${percent}%` );
if( percent < 100 ){
this.setState({ uploadPercentage: percent })
}
}
}
axios.post("https://apimarkp.com/user/", data, options).then(res => { }
when you log in at the APP you should write on the localStorage
localStorage.setItem("customeId", customer.Id);
now you can use in your function:
uploadFile = ({ target: { files } }) =>{
let customeId = localStorage.getItem("customeId");

How to show Realm Data base results to an edit text?

so I'm new to realm data base and I'm trying to show the data that the user wrote throw an Edit text and show it in a Textview..
My realm class
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
import io.realm.annotations.RealmClass
#RealmClass
open class GoodStudents : RealmObject(){
#PrimaryKey
var id: Long = 0
var name : String? = null
var grade : Int? = null
}
Main activity code
Realm.init(this)
val convig = RealmConfiguration.Builder()
.name("GoodStudents").build()
val realm = Realm.getInstance(convig)
realm.beginTransaction()
count = realm.where(GoodStudents::class.java).findAll().size
val goodStudents = realm.createObject(GoodStudents::class.java, count+1)
goodStudents.name = name.text.toString()
goodStudents.grade
realm.commitTransaction()
val readData = realm.where(GoodStudents::class.java).findAll()
saveButton.setOnClickListener {
Toast.makeText(this,"Data is saved", Toast.LENGTH_LONG).show()
var text = text.text
readData.forEach { save ->
save.name = text as String?
}
}
P.C. Java code is acceptable..
so I found out that writing this code will work
saveButton.setOnClickListener {
val convig = RealmConfiguration.Builder()
.name("GoodStudents").build()
val realm = Realm.getInstance(convig)
realm.beginTransaction()
count = realm.where(GoodStudents::class.java).findAll().size
val goodStudents = realm.createObject(GoodStudents::class.java, count+1)
goodStudents.name = name.text.toString()
goodStudents.grade = grade.text.toString().toInt()
val readData = realm.where(GoodStudents::class.java).findAll()
readData.forEach { save ->
text.text = "" + save.name + ": " + goodStudents.grade
}
realm.commitTransaction()
}

java llegal base64 character 20 with base64 string from php

I generate PDF files with php and return the php file as base64 string like this:
$base64 = base64_encode(file_get_contents("http://localhost/pdfgen" . $file));
I send the result of this to a java server which should send mails.
but then I got this error:
[error] a.a.OneForOneStrategy - Illegal base64 character 20
java.lang.IllegalArgumentException: Illegal base64 character 20
at java.util.Base64$Decoder.decode0(Unknown Source)
at java.util.Base64$Decoder.decode(Unknown Source)
at java.util.Base64$Decoder.decode(Unknown Source)
How do I have to encode the pdf file in php that my java service cann consume it.
Thanks in advance
Update:
I call in my ReactJs Frontend via a Post Request the php function which returns a pdf as base64 encoded string. That looks like above.
In my frontend I send again a post to a java backend which is responsible for the mail service.
UPDATE Mail function:
package scheduler
import java.util.Base64
import akka.actor.{Actor, ActorRef, ActorSystem}
import dto.email.models._
import dto.email.{emailDTO, emailLogDTO, smtpServerDTO}
import javax.inject.{Inject, Named}
import javax.mail.Message.RecipientType
import org.codemonkey.simplejavamail.{Email, MailException, Mailer, TransportStrategy}
import play.api.Configuration
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}
import scala.util.Random
object EmailSendActor {
case class Start(id: Int)
trait Factory {
def apply(): Actor
}
}
class EmailSendActor #Inject()(
implicit val executionContext: scala.concurrent.ExecutionContext,
implicit val emailDTO: emailDTO,
implicit val emailLogDTO: emailLogDTO,
implicit val smtpServerDTO: smtpServerDTO,
configuration: Configuration,
val system: ActorSystem, #Named("email-send-scheduler") val schedulerActor: ActorRef
) extends Actor {
import EmailSendActor._
private val retryDelay = configuration.get[Int](EmailSchedulerActor.retryDelayKey)
private val idlePause = configuration.get[Boolean](EmailSchedulerActor.idlePauseKey)
private val simulateFailures = configuration.get[Boolean](EmailSchedulerActor.simulateFailuresKey)
def receive: PartialFunction[Any, Unit] = {
case x: Start =>
println("Email Sender Running")
schedulerActor ! EmailSchedulerActor.Busy(x.id)
var emailCount = 0
var retry = false
val smtpServer = Await.result(smtpServerDTO.getGlobal, Duration.Inf)
if (smtpServer.isDefined) {
val globalSmtpServer = smtpServer.get
println("Got Global Smtp Server " + globalSmtpServer)
val result = emailDTO.getEmailsToSend(globalSmtpServer.smtpServerTypeId, retryDelay).map(emails => {
emails.foreach { email =>
emailCount += 1
if (email.emailStatusTypeId == EmailStatusTypes.pending) {
println("Sending new email[" + email.emailId + "]: " + email.recipients + ": " + email.subject)
if (tryToSendEmail(globalSmtpServer, email)) retry = true
} else if (email.emailStatusTypeId == EmailStatusTypes.retrying) {
println("Retrying to send email[" + email.emailId + "]: " + email.recipients + ": " + email.subject)
if (tryToSendEmail(globalSmtpServer, email)) retry = true
}
}
})
Await.result(result, Duration.Inf)
if (emailCount > 0) {
println("Done sending " + emailCount + " e-mails")
} else {
println("No e-mails to send")
}
} else {
println("No Global Smtp Server Configurations, idling")
}
// reschedule next run
if (retry) {
schedulerActor ! EmailSchedulerActor.Retry(x.id)
} else if (!idlePause || emailCount > 0) {
schedulerActor ! EmailSchedulerActor.Done(x.id)
} else {
schedulerActor ! EmailSchedulerActor.Pause(x.id)
}
}
private def tryToSendEmail(smtpServer: SmtpServerModel, email: EmailModel) = {
var retry = false
val sendResult = if (simulateFailures) Random.nextInt(5) else 0
val result: (Future[Int], Future[Int]) = sendResult match {
case 1 => // retry
println("retrying")
retry = true
(emailDTO.updateEmailStatus(email.emailId.get, EmailStatusTypes.retrying),
emailLogDTO.create(EmailLogModel(
emailStatusTypeId = EmailStatusTypes.retrying,
smtpServerId = smtpServer.smtpServerId.get,
emailId = email.emailId.get,
statusMessage = Option("Retrying")
)))
case 2 => // failed
val status = Random.nextInt(EmailStatusTypes.retryTimeout - EmailStatusTypes.unknownDestination) + EmailStatusTypes.unknownDestination
println("failed, status: " + status)
(emailDTO.updateEmailStatus(email.emailId.get, status),
emailLogDTO.create(EmailLogModel(
emailStatusTypeId = status,
smtpServerId = smtpServer.smtpServerId.get,
emailId = email.emailId.get,
statusMessage = Option("Failed randomly")
)))
case _ => // success
val sendEmail = new Email()
sendEmail.setFromAddress(smtpServer.fromName, smtpServer.fromEmail)
sendEmail.setSubject(email.subject)
val recipients: Option[Seq[EmailRecipient]] = EmailApi.getRecipients(email.recipients)
if (recipients.isDefined) {
recipients.get.foreach({ recipient =>
sendEmail.addRecipient(recipient.name, recipient.email, RecipientType.TO)
})
}
val ccRecipients: Option[Seq[EmailRecipient]] = EmailApi.getRecipients(email.ccRecipients)
if (ccRecipients.isDefined) {
ccRecipients.get.foreach({ recipient =>
sendEmail.addRecipient(recipient.name, recipient.email, RecipientType.CC)
})
}
val bccRecipients: Option[Seq[EmailRecipient]] = EmailApi.getRecipients(email.bccRecipients)
if (bccRecipients.isDefined) {
bccRecipients.get.foreach({ recipient =>
sendEmail.addRecipient(recipient.name, recipient.email, RecipientType.BCC)
})
}
var emailStatusTypeId = EmailStatusTypes.sent
var statusMessage = "Sent"
if (sendEmail.getRecipients.isEmpty) {
emailStatusTypeId = EmailStatusTypes.unknownRecipient
statusMessage = "No recipients"
} else {
if (email.isHtml.get) sendEmail.setTextHTML(email.body)
else sendEmail.setText(email.body)
if (!email.attachments.isEmpty) {
val attachments: Option[Seq[EmailAttachment]] = EmailApi.getAttachments(email.attachments)
if (attachments.isDefined) {
attachments.get.foreach(attachment => {
val bytes = Base64.getDecoder.decode(attachment.base64Content)
sendEmail.addAttachment(attachment.name, bytes, attachment.mimeType)
})
}
}
try {
new Mailer(smtpServer.address, smtpServer.port, smtpServer.username, smtpServer.password, smtpServer.smtpEncryptionTypeId match {
case SmtpEncryptionTypes.none => TransportStrategy.SMTP_PLAIN
case SmtpEncryptionTypes.ssl => TransportStrategy.SMTP_SSL
case SmtpEncryptionTypes.tls => TransportStrategy.SMTP_TLS
}).sendMail(sendEmail)
println("email sent")
} catch {
case t: Throwable =>
statusMessage = t.getMessage
println(s"Send Failed with message $statusMessage")
t match {
case e: MailException =>
emailStatusTypeId = statusMessage match {
case OpenMailException.GENERIC_ERROR => EmailStatusTypes.serverError
case OpenMailException.MISSING_HOST => EmailStatusTypes.serverError
case OpenMailException.MISSING_USERNAME => EmailStatusTypes.unknownRecipient
case OpenMailException.INVALID_ENCODING => EmailStatusTypes.serverError
case OpenMailException.INVALID_RECIPIENT => EmailStatusTypes.unknownRecipient
case OpenMailException.INVALID_REPLYTO => EmailStatusTypes.serverError
case OpenMailException.INVALID_SENDER => EmailStatusTypes.serverError
case OpenMailException.MISSING_SENDER => EmailStatusTypes.serverError
case OpenMailException.MISSING_RECIPIENT => EmailStatusTypes.unknownDestination
case OpenMailException.MISSING_SUBJECT => EmailStatusTypes.serverError
case OpenMailException.MISSING_CONTENT => EmailStatusTypes.serverError
case _ => EmailStatusTypes.serverError
}
case _ => EmailStatusTypes.serverError
}
}
}
(emailDTO.updateEmailStatus(email.emailId.get, emailStatusTypeId),
emailLogDTO.create(EmailLogModel(
emailStatusTypeId = emailStatusTypeId,
smtpServerId = smtpServer.smtpServerId.get,
emailId = email.emailId.get,
statusMessage = Option(statusMessage)
)))
}
Await.result(result._1, Duration.Inf)
Await.result(result._2, Duration.Inf)
retry
}
}
error is in this line:
val bytes = Base64.getDecoder.decode(attachment.base64Content)
I solved it with:
pdf.trim()
Now I have a valid base64 and all works fine.

Scala how to inject mock object to ScalatraFlatSpec

I stuck with Unit test in Scala for many days. I cannot inject mock object to Unit test. The ScalatraFlatSpec call to the actual database not my mock variable and i have no idea to do.
This is my API
class Dashboard extends Servlet {
get("/:brand_code") {
val start = System.currentTimeMillis
val brandCode = params.get("brand_code").get
var brandId = 0;
val sqlFind = "SELECT DISTINCT(id) FROM brands WHERE brand_code=?"
val found:List[Map[String, Any]] = ConnectionModel.getExecuteQuery(sqlFind, List(brandCode))
if(found.isEmpty){
halt(404, send("error", s"brand_code [$brandCode] not found."))
}else{
brandId = found(0).getOrElse("id", 0).toString.toInt
send("Yeah55", brandId)
}
}
And this is Servlet
abstract class Servlet extends ScalatraServlet with CorsSupport with JacksonJsonSupport {
protected implicit lazy val jsonFormats: Formats = DefaultFormats.withBigDecimal
protected override def transformResponseBody(body: JValue): JValue = body.underscoreKeys
protected lazy val body = parsedBody.extract[Map[String, Any]]
protected def send(message: String, data: Any = None) = Map("message" -> message, "data" -> data)
options("/*") {
response.setHeader(
"Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers")
)
}
before() {
contentType = formats("json")
}
}
And this is ConnectionModel and ConnectionModelAble
trait ConnectionModelAble {
def getExecuteQuery(sql: String, parameters: List[Any]): List[Map[String, Any]]
}
object ConnectionModel extends ConnectionModelAble{
var connection:Connection = {
val url = "jdbc:mysql://localhost:3306/db"
val username = "root"
val password = ""\
Class.forName("com.mysql.jdbc.Driver")
DriverManager.getConnection(url, username, password)
}
def getExecuteQuery(sql: String, parameters: List[Any]): List[Map[String, Any]]= {
try {
val statement = connection.createStatement()
var preparedStatement: PreparedStatement = connection.prepareStatement(sql);
var formatDate: DateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
// Do some execute
for (i <- 0 until parameters.size) {
parameters(i) match {
case _: Int => preparedStatement.setInt(i + 1, parameters(i).toString.toInt)
case _: Double => preparedStatement.setDouble(i + 1, parameters(i).toString.toDouble)
case _: Date => preparedStatement.setDate(i + 1, new java.sql.Date(formatDate.parse(parameters(i).toString).getTime))
case default => preparedStatement.setString(i + 1, parameters(i).toString)
}
}
val resultSet = preparedStatement.executeQuery()
val metaData: ResultSetMetaData = resultSet.getMetaData();
val columnCount = metaData.getColumnCount();
var ret: List[Map[String, Any]] = List();
while (resultSet.next()) {
var row: Map[String, Any] = Map[String, Any]();
for (i <- 1 to columnCount) {
val columnName = metaData.getColumnName(i);
var obj = resultSet.getObject(i);
row += columnName -> obj
}
ret = ret :+ row
}
ret
}catch {
case e: Exception => {
e.printStackTrace();
List()
}
}
}
And this is my unit test
class DashboardSpec extends ScalatraFlatSpec with MockitoSugar {
addServlet(new Dashboard, "/v1/dashboard/*")
it should "return get dashboard correctly" in {
val brandCode = "APAAA"
val brandId = 157
get("/v1/dashboard/APAAA") {
val connectModel = mock[ConnectionModelAble]
val sqlFind = "SELECT DISTINCT(id) FROM brands WHERE brand_code=?"
Mockito.when(connectModel.getExecuteQuery(sqlFind, List(brandCode))).thenReturn(
List(Map("id" -> 150))
)
assert(status == 200)
println(connectModel.getExecuteQuery(sqlFind, List(brandCode)))
println(body)
}
}
}
I found that body from unit test is not from my mock data, it's from real database. What should i do.
Thank you.
You aren't injecting your mock into the Dashboard, so the Connection you're seeing in getExecuteQuery is the one provided by ConnectionModel.connection. You probably want to use a dependency injection framework or something like the Cake pattern to make sure your Dashboard is referring to your mock instance.

PHP multidimentional associative array performance or similar code in Java

I am doing a lot of operations using a below code in PHP. The issue is PHP is getting slower and slower as my data gets bigger and bigger.
My solution to fix this is to move the code in Java so it can provide a better performance as it is complied language and I can also multithread or use async functions to do multiple such operations to make it faster.
What I want to know is how to speed up this kind of operation in PHP or what other data structure should I use to improve the performance of this code. And if not PHP how can I do this in Java.
foreach ( $dataArr as $direct ) {
//total dfpimpr for the date-li combi
if ( isset( $arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']]['COUNTER_TOTALIMPR'] ) ) {
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']]['COUNTER_TOTALIMPR'] += $direct[0]['DFPIMPR'];
}else {
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']]['COUNTER_TOTALIMPR'] = $direct[0]['DFPIMPR'];
}
$dfpAdUnit = $direct['AD1']['DFPAD1'].'/'.$direct['AD2']['DFPAD2'];
// can go on the first level of the array as not dependent on AD1/AD2-COUNTRY
if ( isset( self::$orderLineitemSetting[$direct['DOX']['ORDID']][$direct['DLI']['LIID']]['setting']['is_direct'] ) ) {
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['ISDIRECT'] = self::$orderLineitemSetting[$direct['DOX']['ORDID']][$direct['DLI']['LIID']]['setting']['is_direct'];
}else {
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['ISDIRECT'] = 1;
}
if ( isset( self::$orderLineitemSetting[$direct['DOX']['ORDID']][$direct['DLI']['LIID']]['setting']['is_ron'] ) ) {
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['ISRON'] = self::$orderLineitemSetting[$direct['DOX']['ORDID']][$direct['DLI']['LIID']]['setting']['is_ron'];
}else {
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['ISRON'] = 0;
}
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['DATE'] = $direct['DS']['DATE'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['ISADEX'] = 0;
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['ISMM'] = 0;
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['ADVERTISER'] = $direct['DA']['ADVERTISER'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['ORDID'] = $direct['DOX']['ORDID'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['ORDNAME'] = $direct['DOX']['ORDNAME'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['LINAME'] = $direct['DLI']['LINAME'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['LIID'] = $direct['DLI']['LIID'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['LISIZE'] = $direct['DSZ']['LISIZE'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['SITEID'] = $direct['PUBSITE']['SITEID'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['COUNTRYID'] = $direct['DC']['COUNTRYID'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['COUNTRY'] = $direct['DC']['COUNTRY'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['DFPADUNIT'] = $dfpAdUnit;
//if it is passback (ISDIRECT=2) make its revenue && impr = 0
//and add its impr to a new pbImpr column
if ( isset( self::$orderLineitemSetting[$direct['DOX']['ORDID']][$direct['DLI']['LIID']]['setting']['is_direct'] )
&& self::$orderLineitemSetting[$direct['DOX']['ORDID']][$direct['DLI']['LIID']]['setting']['is_direct'] == 2 ) {
//passback imprs
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['PBIMPR'] = $direct[0]['DFPIMPR'];
//make dfpimpr for passback all 0
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['DFPIMPR'] = $direct[0]['DFPIMPR'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['DFPCLCKS'] = $direct[0]['DFPCLCKS'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['DFPREV'] = 0;
//make tpimpr for passback all 0
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['TPIMPR'] = 0;
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['TPCLCKS'] = 0;
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['TPREV'] = 0;
}else {
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['DFPIMPR'] = $direct[0]['DFPIMPR'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['DFPCLCKS'] = $direct[0]['DFPCLCKS'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['DFPREV'] = $direct[0]['DFPREV'];
//include direct data into 3rd party
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['TPIMPR'] = $direct[0]['DFPIMPR'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['TPCLCKS'] = $direct[0]['DFPCLCKS'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['TPREV'] = $direct[0]['DFPREV'];
}
//include direct data into 3rd party
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['TP'] = '';
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['TPTAGID'] = 0;
}
Follow DRY principle. That way you'll reduce the length of the code, its complexity, and - what's most important in this case - you'll get rid of several dozens of multidimensional-arrays dereferences. Also the final code will be much easier to maintain:
foreach ($dataArr as $direct) {
// create a few references to reduce "ugly" code
$counter = &$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']]['COUNTER_TOTALIMPR'];
$directStatus = &self::$orderLineitemSetting[$direct['DOX']['ORDID']][$direct['DLI']['LIID']]['setting']['is_direct'];
$ronStatus = &self::$orderLineitemSetting[$direct['DOX']['ORDID']][$direct['DLI']['LIID']]['setting']['is_ron'];
$dfpAdUnit = $direct['AD1']['DFPAD1'].'/'.$direct['AD2']['DFPAD2'];
if (!isset($counter)) {
$counter = 0;
}
$counter += $direct[0]['DFPIMPR'];
$e = array(
'DATE' => $direct['DS']['DATE'],
'ISADEX' => 0,
'ISMM' => 0,
'ADVERTISER' => $direct['DA']['ADVERTISER'],
'ORDID' => $direct['DOX']['ORDID'],
'ORDNAME' => $direct['DOX']['ORDNAME'],
'LINAME' => $direct['DLI']['LINAME'],
'LIID' => $direct['DLI']['LIID'],
'LISIZE' => $direct['DSZ']['LISIZE'],
'SITEID' => $direct['PUBSITE']['SITEID'],
'COUNTRYID' => $direct['DC']['COUNTRYID'],
'COUNTRY' => $direct['DC']['COUNTRY'],
'DFPADUNIT' => $dfpAdUnit,
'TP' => '',
'TPTAGID' => 0
);
$e['ISDIRECT'] = !isset($directStatus) ? 1 : $directStatus;
$e['ISRON'] = !isset($ronStatus) ? 0 : $ronStatus;
if (isset($directStatus) && $directStatus === 2) { // Hint: don't use magic numbers (2),
// create some constant with appropriate name
$e += array(
'PBIMPR' => $direct[0]['DFPIMPR'],
'DFPIMPR' => $direct[0]['DFPIMPR'],
'DFPCLCKS' => $direct[0]['DFPCLCKS'],
'DFPREV' => 0,
'TPIMPR' => 0,
'TPCLCKS' => 0,
'TPREV' => 0
);
} else {
$e += array(
'DFPIMPR' => $direct[0]['DFPIMPR'],
'DFPCLCKS' => $direct[0]['DFPCLCKS'],
'DFPREV' => $direct[0]['DFPREV'],
'TPIMPR' => $direct[0]['DFPIMPR'],
'TPCLCKS' => $direct[0]['DFPCLCKS'],
'TPREV' => $direct[0]['DFPREV']
);
}
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']] = $e;
}
Optimize PHP itself. Use OP code accelerator like APC (for PHP < 5.5) or even better: a JIT compiler (HHVM) as suggested by #Alasdair

Categories